]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_ConstraintGroup.cpp
Salome HOME
d54915677b9f3ceffc9560e94fd574e6e9440145
[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 <GeomDataAPI_Dir.h>
12 #include <GeomDataAPI_Point.h>
13 #include <GeomDataAPI_Point2D.h>
14 #include <ModelAPI_AttributeDouble.h>
15 #include <ModelAPI_AttributeRefList.h>
16 #include <Model_Events.h>
17
18 #include <SketchPlugin_Constraint.h>
19 #include <SketchPlugin_ConstraintLength.h>
20 #include <SketchPlugin_ConstraintCoincidence.h>
21
22 #include <SketchPlugin_Arc.h>
23 #include <SketchPlugin_Circle.h>
24 #include <SketchPlugin_Line.h>
25 #include <SketchPlugin_Point.h>
26 #include <SketchPlugin_Sketch.h>
27
28 #include <math.h>
29 #include <assert.h>
30
31 /// Tolerance for value of parameters
32 const double tolerance = 1.e-10;
33
34 const std::string ERROR_SOLVE_CONSTRAINTS = "Conflicting constraints";
35
36 /// This value is used to give unique index to the groups
37 static Slvs_hGroup myGroupIndexer = 0;
38
39 /** \brief Search the entity/parameter with specified ID in the list of elements
40  *  \param[in] theEntityID unique ID of the element
41  *  \param[in] theEntities list of elements
42  *  \return position of the found element or -1 if the element is not found
43  */
44 template <typename T>
45 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
46
47
48 // ========================================================
49 // =========  SketchSolver_ConstraintGroup  ===============
50 // ========================================================
51
52 SketchSolver_ConstraintGroup::
53   SketchSolver_ConstraintGroup(boost::shared_ptr<SketchPlugin_Feature> theWorkplane)
54   : myID(++myGroupIndexer),
55     myParamMaxID(0),
56     myEntityMaxID(0),
57     myConstrMaxID(0),
58     myConstraintMap(),
59     myNeedToSolve(false),
60     myConstrSolver()
61 {
62   myParams.clear();
63   myEntities.clear();
64   myConstraints.clear();
65   
66   myTempConstraints.clear();
67   myTempPointWhereDragged.clear();
68   myTempPointWDrgdID = 0;
69
70   // Initialize workplane
71   myWorkplane.h = SLVS_E_UNKNOWN;
72 #ifndef NDEBUG
73   assert(addWorkplane(theWorkplane));
74 #else
75   addWorkplane(theWorkplane);
76 #endif
77 }
78
79 SketchSolver_ConstraintGroup::~SketchSolver_ConstraintGroup()
80 {
81   myParams.clear();
82   myEntities.clear();
83   myConstraints.clear();
84   myConstraintMap.clear();
85   myTempConstraints.clear();
86   myTempPointWhereDragged.clear();
87
88   // If the group with maximal identifier is deleted, decrease the indexer
89   if (myID == myGroupIndexer)
90     myGroupIndexer--;
91 }
92
93 // ============================================================================
94 //  Function: isBaseWorkplane
95 //  Class:    SketchSolver_ConstraintGroup
96 //  Purpose:  verify the group is based on the given workplane
97 // ============================================================================
98 bool SketchSolver_ConstraintGroup::isBaseWorkplane(
99                 boost::shared_ptr<SketchPlugin_Feature> theWorkplane) const
100 {
101   return theWorkplane == mySketch;
102 }
103
104 // ============================================================================
105 //  Function: isInteract
106 //  Class:    SketchSolver_ConstraintGroup
107 //  Purpose:  verify are there any entities in the group used by given constraint
108 // ============================================================================
109 bool SketchSolver_ConstraintGroup::isInteract(
110                 boost::shared_ptr<SketchPlugin_Constraint> theConstraint) const
111 {
112   // Check the group is empty
113   if (myWorkplane.h != SLVS_E_UNKNOWN && myConstraints.empty())
114     return true;
115
116   // Go through constraint entities and verify if some of them already in the group
117   for (int i = 0; i < CONSTRAINT_ATTR_SIZE; i++)
118   {
119     boost::shared_ptr<ModelAPI_AttributeRefAttr> aCAttrRef =
120       boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
121         theConstraint->data()->attribute(CONSTRAINT_ATTRIBUTES[i])
122       );
123     if (!aCAttrRef) continue;
124     if (!aCAttrRef->isFeature() && 
125         myEntityAttrMap.find(aCAttrRef->attr()) != myEntityAttrMap.end())
126       return true;
127     if (aCAttrRef->isFeature() && 
128         myEntityFeatMap.find(aCAttrRef->feature()) != myEntityFeatMap.end())
129       return true;
130   }
131
132   // Entities did not found
133   return false;
134 }
135
136 // ============================================================================
137 //  Function: changeConstraint
138 //  Class:    SketchSolver_ConstraintGroup
139 //  Purpose:  create/update the constraint in the group
140 // ============================================================================
141 bool SketchSolver_ConstraintGroup::changeConstraint(
142                 boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
143 {
144   // There is no workplane yet, something wrong
145   if (myWorkplane.h == SLVS_E_UNKNOWN)
146     return false;
147
148   // Search this constraint in the current group to update it
149   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
150     aConstrMapIter = myConstraintMap.find(theConstraint);
151   std::vector<Slvs_Constraint>::iterator aConstrIter;
152   if (aConstrMapIter != myConstraintMap.end())
153   {
154     int aConstrPos = Search(aConstrMapIter->second, myConstraints);
155     aConstrIter = myConstraints.begin() + aConstrPos;
156   }
157
158   // Get constraint type and verify the constraint parameters are correct
159   SketchSolver_Constraint aConstraint(theConstraint);
160   int aConstrType = aConstraint.getType();
161   if (aConstrType == SLVS_C_UNKNOWN ||
162      (aConstrMapIter != myConstraintMap.end() && aConstrIter->type != aConstrType))
163     return false;
164   const std::vector<std::string>& aConstraintAttributes = aConstraint.getAttributes();
165
166   // Create constraint parameters
167   double aDistance = 0.0; // scalar value of the constraint
168   AttributeDoublePtr aDistAttr =
169     boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theConstraint->data()->attribute(CONSTRAINT_ATTR_VALUE));
170   if (aDistAttr)
171   {
172     aDistance = aDistAttr->value();
173     // SketchPlugin circle defined by its radius, but SolveSpace uses constraint for diameter
174     if (aConstrType == SLVS_C_DIAMETER)
175       aDistance *= 2.0;
176     if (aConstrMapIter != myConstraintMap.end() && fabs(aConstrIter->valA - aDistance) > tolerance)
177     {
178       myNeedToSolve = true;
179       aConstrIter->valA = aDistance;
180     }
181   }
182
183   Slvs_hEntity aConstrEnt[CONSTRAINT_ATTR_SIZE]; // parameters of the constraint
184   for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++)
185   {
186     aConstrEnt[indAttr] = SLVS_E_UNKNOWN;
187     boost::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr =
188       boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
189         theConstraint->data()->attribute(aConstraintAttributes[indAttr])
190       );
191     if (!aConstrAttr) continue;
192
193     // For the length constraint the start and end points of the line should be added to the entities list instead of line
194     if (aConstrType == SLVS_C_PT_PT_DISTANCE && theConstraint->getKind().compare(SKETCH_CONSTRAINT_LENGTH_KIND) == 0)
195     {
196       boost::shared_ptr<ModelAPI_Data> aData = aConstrAttr->feature()->data();
197       aConstrEnt[indAttr]   = changeEntity(aData->attribute(LINE_ATTR_START));
198       aConstrEnt[indAttr+1] = changeEntity(aData->attribute(LINE_ATTR_END));
199       myEntityFeatMap[aConstrAttr->feature()] = 0; // measured object is added into the map of objects to avoid problems with interaction betwee constraint and group
200       break; // there should be no other entities
201     }
202     else if (aConstrAttr->isFeature())
203       aConstrEnt[indAttr] = changeEntity(aConstrAttr->feature());
204     else
205       aConstrEnt[indAttr] = changeEntity(aConstrAttr->attr());
206   }
207
208   if (aConstrMapIter == myConstraintMap.end())
209   {
210     // Several points may be coincident, it is not necessary to store all constraints between them.
211     // Try to find sequence of coincident points which connects the points of new constraint
212     if (aConstrType == SLVS_C_POINTS_COINCIDENT)
213     {
214       if (aConstrEnt[0] == aConstrEnt[1]) // no need to add self coincidence
215       {
216         return false;
217       }
218       if (!addCoincidentPoints(aConstrEnt[0], aConstrEnt[1]))
219       {
220         myExtraCoincidence.insert(theConstraint); // the constraint is stored for further purposes
221         return false;
222       }
223     }
224
225     // Create SolveSpace constraint structure
226     Slvs_Constraint aConstraint =
227       Slvs_MakeConstraint(++myConstrMaxID, myID, aConstrType, myWorkplane.h,
228                           aDistance, aConstrEnt[0], aConstrEnt[1], aConstrEnt[2], aConstrEnt[3]);
229     myConstraints.push_back(aConstraint);
230     myConstraintMap[theConstraint] = aConstraint.h;
231   }
232   return true;
233 }
234
235 // ============================================================================
236 //  Function: changeEntity
237 //  Class:    SketchSolver_ConstraintGroup
238 //  Purpose:  create/update the element affected by any constraint
239 // ============================================================================
240 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
241                 boost::shared_ptr<ModelAPI_Attribute> theEntity)
242 {
243   // If the entity is already in the group, try to find it
244   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
245     aEntIter = myEntityAttrMap.find(theEntity);
246   std::vector<Slvs_Param>::const_iterator aParamIter; // looks at first parameter of already existent entity or at the end of vector otherwise
247   if (aEntIter == myEntityAttrMap.end()) // no such entity => should be created
248     aParamIter = myParams.end();
249   else
250   { // the entity already exists
251     int aEntPos = Search(aEntIter->second, myEntities);
252     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
253     aParamIter = myParams.begin() + aParamPos;
254   }
255   const bool isEntExists = (aEntIter != myEntityAttrMap.end()); // defines that the entity already exists
256
257   // Look over supported types of entities
258
259   // Point in 3D
260   boost::shared_ptr<GeomDataAPI_Point> aPoint =
261     boost::dynamic_pointer_cast<GeomDataAPI_Point>(theEntity);
262   if (aPoint)
263   {
264     Slvs_hParam aX = changeParameter(aPoint->x(), aParamIter);
265     Slvs_hParam aY = changeParameter(aPoint->y(), aParamIter);
266     Slvs_hParam aZ = changeParameter(aPoint->z(), aParamIter);
267
268     if (isEntExists)
269       return aEntIter->second;
270
271     // New entity
272     Slvs_Entity aPtEntity = Slvs_MakePoint3d(++myEntityMaxID, myID, aX, aY, aZ);
273     myEntities.push_back(aPtEntity);
274     myEntityAttrMap[theEntity] = aPtEntity.h;
275     return aPtEntity.h;
276   }
277
278   // All entities except 3D points are created on workplane. So, if there is no workplane yet, then error
279   if (myWorkplane.h == SLVS_E_UNKNOWN)
280     return SLVS_E_UNKNOWN;
281
282   // Point in 2D
283   boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
284     boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
285   if (aPoint2D)
286   {
287     Slvs_hParam aU = changeParameter(aPoint2D->x(), aParamIter);
288     Slvs_hParam aV = changeParameter(aPoint2D->y(), aParamIter);
289
290     if (isEntExists)
291       return aEntIter->second;
292
293     // New entity
294     Slvs_Entity aPt2DEntity = Slvs_MakePoint2d(++myEntityMaxID, myID, myWorkplane.h, aU, aV);
295     myEntities.push_back(aPt2DEntity);
296     myEntityAttrMap[theEntity] = aPt2DEntity.h;
297     return aPt2DEntity.h;
298   }
299
300   // Scalar value (used for the distance entities)
301   AttributeDoublePtr aScalar = 
302     boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theEntity);
303   if (aScalar)
304   {
305     Slvs_hParam aValue = changeParameter(aScalar->value(), aParamIter);
306
307     if (isEntExists)
308       return aEntIter->second;
309
310     // New entity
311     Slvs_Entity aDistance = Slvs_MakeDistance(++myEntityMaxID, myID, myWorkplane.h, aValue);
312     myEntities.push_back(aDistance);
313     myEntityAttrMap[theEntity] = aDistance.h;
314     return aDistance.h;
315   }
316
317   /// \todo Other types of entities
318
319   // Unsupported or wrong entity type
320   return SLVS_E_UNKNOWN;
321 }
322
323
324 // ============================================================================
325 //  Function: changeEntity
326 //  Class:    SketchSolver_ConstraintGroup
327 //  Purpose:  create/update the element defined by the feature affected by any constraint
328 // ============================================================================
329 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
330                 FeaturePtr theEntity)
331 {
332   // If the entity is already in the group, try to find it
333   std::map<FeaturePtr, Slvs_hEntity>::const_iterator
334     aEntIter = myEntityFeatMap.find(theEntity);
335   // defines that the entity already exists
336   const bool isEntExists = (myEntityFeatMap.find(theEntity) != myEntityFeatMap.end());
337
338   // SketchPlugin features
339   boost::shared_ptr<SketchPlugin_Feature> aFeature =
340     boost::dynamic_pointer_cast<SketchPlugin_Feature>(theEntity);
341   if (aFeature)
342   { // Verify the feature by its kind
343     const std::string& aFeatureKind = aFeature->getKind();
344
345     // Line
346     if (aFeatureKind.compare(SKETCH_LINE_KIND) == 0)
347     {
348       Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(LINE_ATTR_START));
349       Slvs_hEntity aEnd   = changeEntity(aFeature->data()->attribute(LINE_ATTR_END));
350
351       if (isEntExists)
352         return aEntIter->second;
353
354       // New entity
355       Slvs_Entity aLineEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
356       myEntities.push_back(aLineEntity);
357       myEntityFeatMap[theEntity] = aLineEntity.h;
358       return aLineEntity.h;
359     }
360     // Circle
361     else if (aFeatureKind.compare(SKETCH_CIRCLE_KIND) == 0)
362     {
363       Slvs_hEntity aCenter = changeEntity(aFeature->data()->attribute(CIRCLE_ATTR_CENTER));
364       Slvs_hEntity aRadius = changeEntity(aFeature->data()->attribute(CIRCLE_ATTR_RADIUS));
365
366       if (isEntExists)
367         return aEntIter->second;
368
369       // New entity
370       Slvs_Entity aCircleEntity = 
371         Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter, myWorkplane.normal, aRadius);
372       myEntities.push_back(aCircleEntity);
373       myEntityFeatMap[theEntity] = aCircleEntity.h;
374       return aCircleEntity.h;
375     }
376     // Arc
377     else if (aFeatureKind.compare(SKETCH_ARC_KIND) == 0)
378     {
379       Slvs_hEntity aCenter = changeEntity(aFeature->data()->attribute(ARC_ATTR_CENTER));
380       Slvs_hEntity aStart  = changeEntity(aFeature->data()->attribute(ARC_ATTR_START));
381       Slvs_hEntity aEnd    = changeEntity(aFeature->data()->attribute(ARC_ATTR_END));
382
383       if (isEntExists)
384         return aEntIter->second;
385
386       Slvs_Entity anArcEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID, 
387                                   myWorkplane.h, myWorkplane.normal, aCenter, aStart, aEnd);
388       myEntities.push_back(anArcEntity);
389       myEntityFeatMap[theEntity] = anArcEntity.h;
390       return anArcEntity.h;
391     }
392     // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
393     else if (aFeatureKind.compare(SKETCH_POINT_KIND) == 0)
394     {
395       Slvs_hEntity aPoint = changeEntity(aFeature->data()->attribute(POINT_ATTR_COORD));
396
397       if (isEntExists)
398         return aEntIter->second;
399
400       // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
401       myEntityFeatMap[theEntity] = aPoint;
402       return aPoint;
403     }
404   }
405
406   /// \todo Other types of features
407
408   // Unsupported or wrong entity type
409   return SLVS_E_UNKNOWN;
410 }
411
412 // ============================================================================
413 //  Function: changeNormal
414 //  Class:    SketchSolver_ConstraintGroup
415 //  Purpose:  create/update the normal of workplane
416 // ============================================================================
417 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
418                 boost::shared_ptr<ModelAPI_Attribute> theDirX,
419                 boost::shared_ptr<ModelAPI_Attribute> theDirY,
420                 boost::shared_ptr<ModelAPI_Attribute> theNorm)
421 {
422   boost::shared_ptr<GeomDataAPI_Dir> aDirX =
423     boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
424   boost::shared_ptr<GeomDataAPI_Dir> aDirY =
425     boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
426   if (!aDirX || !aDirY ||
427      (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance) ||
428      (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
429     return SLVS_E_UNKNOWN;
430
431   // quaternion parameters of normal vector
432   double qw, qx, qy, qz;
433   Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(),
434                       aDirY->x(), aDirY->y(), aDirY->z(),
435                       &qw, &qx, &qy, &qz);
436   double aNormCoord[4] = {qw, qx, qy, qz};
437
438   // Try to find existent normal
439   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
440     aEntIter = myEntityAttrMap.find(theNorm);
441   std::vector<Slvs_Param>::const_iterator aParamIter; // looks to the first parameter of already existent entity or to the end of vector otherwise
442   if (aEntIter == myEntityAttrMap.end()) // no such entity => should be created
443     aParamIter = myParams.end();
444   else
445   { // the entity already exists, update it
446     int aEntPos = Search(aEntIter->second, myEntities);
447     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
448     aParamIter = myParams.begin() + aParamPos;
449   }
450
451   // Change parameters of the normal
452   Slvs_hParam aNormParams[4];
453   for (int i = 0; i < 4; i++)
454     aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
455
456   if (aEntIter != myEntityAttrMap.end()) // the entity already exists
457     return aEntIter->second;
458
459   // Create a normal
460   Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID,
461                 aNormParams[0], aNormParams[1], aNormParams[2], aNormParams[3]);
462   myEntities.push_back(aNormal);
463   myEntityAttrMap[theNorm] = aNormal.h;
464   return aNormal.h;
465 }
466
467
468 // ============================================================================
469 //  Function: addWorkplane
470 //  Class:    SketchSolver_ConstraintGroup
471 //  Purpose:  create workplane for the group
472 // ============================================================================
473 bool SketchSolver_ConstraintGroup::addWorkplane(
474                 boost::shared_ptr<SketchPlugin_Feature> theSketch)
475 {
476   if (myWorkplane.h || theSketch->getKind().compare(SKETCH_KIND) != 0)
477     return false; // the workplane already exists or the function parameter is not Sketch
478
479   mySketch = theSketch;
480   updateWorkplane();
481   return true;
482 }
483
484 // ============================================================================
485 //  Function: updateWorkplane
486 //  Class:    SketchSolver_ConstraintGroup
487 //  Purpose:  update parameters of workplane
488 // ============================================================================
489 bool SketchSolver_ConstraintGroup::updateWorkplane()
490 {
491   // Get parameters of workplane
492   boost::shared_ptr<ModelAPI_Attribute> aDirX    = mySketch->data()->attribute(SKETCH_ATTR_DIRX);
493   boost::shared_ptr<ModelAPI_Attribute> aDirY    = mySketch->data()->attribute(SKETCH_ATTR_DIRY);
494   boost::shared_ptr<ModelAPI_Attribute> aNorm    = mySketch->data()->attribute(SKETCH_ATTR_NORM);
495   boost::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(SKETCH_ATTR_ORIGIN);
496   // Transform them into SolveSpace format
497   Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
498   if (!aNormalWP) return false;
499   Slvs_hEntity anOriginWP = changeEntity(anOrigin);
500   if (!anOriginWP) return false;
501
502   if (!myWorkplane.h)
503   {
504     // Create workplane
505     myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
506     // Workplane should be added to the list of entities
507     myEntities.push_back(myWorkplane);
508   }
509   return true;
510 }
511
512 // ============================================================================
513 //  Function: changeParameter
514 //  Class:    SketchSolver_ConstraintGroup
515 //  Purpose:  create/update value of parameter
516 // ============================================================================
517 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
518                 const double&                            theParam,
519                 std::vector<Slvs_Param>::const_iterator& thePrmIter)
520 {
521   if (thePrmIter != myParams.end())
522   { // Parameter should be updated
523     int aParamPos = thePrmIter - myParams.begin();
524     if (fabs(thePrmIter->val - theParam) > tolerance)
525     {
526       myNeedToSolve = true; // parameter is changed, need to resolve constraints
527       myParams[aParamPos].val = theParam;
528     }
529     thePrmIter++;
530     return myParams[aParamPos].h;
531   }
532
533   // Newly created parameter
534   Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
535   myParams.push_back(aParam);
536   myNeedToSolve = true;
537   // The list of parameters is changed, move iterator to the end of the list to avoid problems
538   thePrmIter = myParams.end();
539   return aParam.h;
540 }
541
542 // ============================================================================
543 //  Function: resolveConstraints
544 //  Class:    SketchSolver_ConstraintGroup
545 //  Purpose:  solve the set of constraints for the current group
546 // ============================================================================
547 void SketchSolver_ConstraintGroup::resolveConstraints()
548 {
549   if (!myNeedToSolve)
550     return;
551
552   myConstrSolver.setGroupID(myID);
553   myConstrSolver.setParameters(myParams);
554   myConstrSolver.setEntities(myEntities);
555   myConstrSolver.setConstraints(myConstraints);
556   myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
557
558   int aResult = myConstrSolver.solve();
559   if (aResult == SLVS_RESULT_OKAY)
560   { // solution succeeded, store results into correspondent attributes
561     // Obtain result into the same list of parameters
562     if (!myConstrSolver.getResult(myParams))
563       return;
564
565     // We should go through the attributes map, because only attributes have valued parameters
566     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
567       anEntIter = myEntityAttrMap.begin();
568     for ( ; anEntIter != myEntityAttrMap.end(); anEntIter++)
569       updateAttribute(anEntIter->first, anEntIter->second);
570   }
571   else if (!myConstraints.empty())
572     Events_Error::send(ERROR_SOLVE_CONSTRAINTS, this);
573
574   removeTemporaryConstraints();
575   myNeedToSolve = false;
576 }
577
578 // ============================================================================
579 //  Function: mergeGroups
580 //  Class:    SketchSolver_ConstraintGroup
581 //  Purpose:  append specified group to the current group
582 // ============================================================================
583 void SketchSolver_ConstraintGroup::mergeGroups(
584                 const SketchSolver_ConstraintGroup& theGroup)
585 {
586   // If specified group is empty, no need to merge
587   if (theGroup.myConstraintMap.empty())
588     return ;
589
590   // Map between old and new indexes of SolveSpace constraints
591   std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
592
593   // Add all constraints from theGroup to the current group
594   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
595     aConstrIter = theGroup.myConstraintMap.begin();
596   for ( ; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
597     if (changeConstraint(aConstrIter->first))
598       aConstrMap[aConstrIter->second] = myConstrMaxID; // the constraint was added => store its ID
599
600   // Add temporary constraints from theGroup
601   std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
602   for ( ; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++)
603   {
604     std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(*aTempConstrIter);
605     if (aFind != aConstrMap.end())
606       myTempConstraints.push_back(aFind->second);
607   }
608
609   if (myTempPointWhereDragged.empty())
610     myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
611   else if (!theGroup.myTempPointWhereDragged.empty())
612   { // Need to create additional transient constraint
613     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
614       aFeatureIter = theGroup.myEntityAttrMap.begin();
615     for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
616       if (aFeatureIter->second == myTempPointWDrgdID)
617       {
618         addTemporaryConstraintWhereDragged(aFeatureIter->first);
619         break;
620       }
621   }
622
623   myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
624 }
625
626 // ============================================================================
627 //  Function: splitGroup
628 //  Class:    SketchSolver_ConstraintGroup
629 //  Purpose:  divide the group into several subgroups
630 // ============================================================================
631 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
632 {
633   // Divide constraints and entities into several groups
634   std::vector< std::set<Slvs_hEntity> >     aGroupsEntities;
635   std::vector< std::set<Slvs_hConstraint> > aGroupsConstr;
636   int aMaxNbEntities = 0; // index of the group with maximal nuber of elements (this group will be left in the current)
637   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
638   for ( ; aConstrIter != myConstraints.end(); aConstrIter++)
639   {
640     Slvs_hEntity aConstrEnt[] = {
641       aConstrIter->ptA,     aConstrIter->ptB,
642       aConstrIter->entityA, aConstrIter->entityB};
643     std::vector<int> anIndexes;
644     // Go through the groupped entities and find even one of entities of current constraint
645     std::vector< std::set<Slvs_hEntity> >::iterator aGrEntIter;
646     for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++)
647     {
648       bool isFound = false;
649       for (int i = 0; i < 4 && !isFound; i++)
650         if (aConstrEnt[i] != 0)
651           isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
652       if (isFound)
653         anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
654     }
655     // Add new group if no one is found
656     if (anIndexes.empty())
657     {
658       std::set<Slvs_hEntity> aNewGrEnt;
659       for (int i = 0; i < 4; i++)
660         if (aConstrEnt[i] != 0)
661           aNewGrEnt.insert(aConstrEnt[i]);
662       std::set<Slvs_hConstraint> aNewGrConstr;
663       aNewGrConstr.insert(aConstrIter->h);
664
665       aGroupsEntities.push_back(aNewGrEnt);
666       aGroupsConstr.push_back(aNewGrConstr);
667       if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
668         aMaxNbEntities = aGroupsEntities.size() - 1;
669     }
670     else if (anIndexes.size() == 1)
671     { // Add entities indexes into the found group
672       aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
673       for (int i = 0; i < 4; i++)
674         if (aConstrEnt[i] != 0)
675           aGrEntIter->insert(aConstrEnt[i]);
676       aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
677       if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
678         aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
679     }
680     else 
681     { // There are found several connected groups, merge them
682       std::vector< std::set<Slvs_hEntity> >::iterator aFirstGroup = 
683         aGroupsEntities.begin() + anIndexes.front();
684       std::vector< std::set<Slvs_hConstraint> >::iterator aFirstConstr = 
685         aGroupsConstr.begin() + anIndexes.front();
686       std::vector<int>::iterator anInd = anIndexes.begin();
687       for (++anInd; anInd != anIndexes.end(); anInd++)
688       {
689         aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
690         aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
691       }
692       if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
693         aMaxNbEntities = anIndexes.front();
694       // Remove merged groups
695       for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--)
696       {
697         aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
698         aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
699       }
700     }
701   }
702
703   if (aGroupsEntities.size() <= 1)
704     return ;
705
706   // Remove the group with maximum elements as it will be left in the current group
707   aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
708   aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
709
710   // Add new groups of constraints and divide current group
711   std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
712   for (int i = aGroupsEntities.size(); i > 0; i--)
713   {
714     SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
715     aNewGroups.push_back(aG);
716   }
717   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
718     aConstrMapIter = myConstraintMap.begin();
719   int aConstrMapPos = 0; // position of iterator in the map (used to restore iterator after removing constraint)
720   while (aConstrMapIter != myConstraintMap.end())
721   {
722     std::vector< std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
723     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
724     for ( ; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
725       if (aGIter->find(aConstrMapIter->second) != aGIter->end())
726       {
727         (*aGroup)->changeConstraint(aConstrMapIter->first);
728         removeConstraint(aConstrMapIter->first);
729         // restore iterator
730         aConstrMapIter = myConstraintMap.begin();
731         for (int i = 0; i < aConstrMapPos; i++)
732           aConstrMapIter++;
733         break;
734       }
735     if (aGIter == aGroupsConstr.end())
736     {
737       aConstrMapIter++;
738       aConstrMapPos++;
739     }
740   }
741
742   theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
743 }
744
745 // ============================================================================
746 //  Function: updateGroup
747 //  Class:    SketchSolver_ConstraintGroup
748 //  Purpose:  search removed entities and constraints
749 // ============================================================================
750 bool SketchSolver_ConstraintGroup::updateGroup()
751 {
752   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator
753     aConstrIter = myConstraintMap.rbegin();
754   bool isAllValid = true;
755   bool isCCRemoved = false; // indicates that at least one of coincidence constraints was removed
756   while (isAllValid && aConstrIter != myConstraintMap.rend())
757   {
758     if (!aConstrIter->first->data()->isValid())
759     {
760       if (aConstrIter->first->getKind().compare(SKETCH_CONSTRAINT_COINCIDENCE_KIND) == 0)
761         isCCRemoved = true;
762       std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator
763         aCopyIter = aConstrIter++;
764       removeConstraint(aCopyIter->first);
765       isAllValid = false;
766     }
767     else aConstrIter++;
768   }
769
770   // Probably, need to update coincidence constraints
771   if (isCCRemoved && !myExtraCoincidence.empty())
772   {
773     // Make a copy, because the new list of unused constrtaints will be generated
774     std::set< boost::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
775     myExtraCoincidence.clear();
776
777     std::set< boost::shared_ptr<SketchPlugin_Constraint> >::iterator
778       aCIter = anExtraCopy.begin();
779     for ( ; aCIter != anExtraCopy.end(); aCIter++)
780       if ((*aCIter)->data()->isValid())
781         changeConstraint(*aCIter);
782   }
783
784   return !isAllValid;
785 }
786
787 // ============================================================================
788 //  Function: updateAttribute
789 //  Class:    SketchSolver_ConstraintGroup
790 //  Purpose:  update features of sketch after resolving constraints
791 // ============================================================================
792 void SketchSolver_ConstraintGroup::updateAttribute(
793                 boost::shared_ptr<ModelAPI_Attribute> theAttribute,
794                 const Slvs_hEntity&                   theEntityID)
795 {
796   // Search the position of the first parameter of the entity
797   int anEntPos = Search(theEntityID, myEntities);
798   int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
799
800   // Look over supported types of entities
801
802   // Point in 3D
803   boost::shared_ptr<GeomDataAPI_Point> aPoint =
804     boost::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
805   if (aPoint)
806   {
807     aPoint->setValue(myParams[aFirstParamPos].val,
808                      myParams[aFirstParamPos+1].val,
809                      myParams[aFirstParamPos+2].val);
810     return ;
811   }
812
813   // Point in 2D
814   boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
815     boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
816   if (aPoint2D)
817   {
818     aPoint2D->setValue(myParams[aFirstParamPos].val,
819                        myParams[aFirstParamPos+1].val);
820     return ;
821   }
822
823   // Scalar value
824   AttributeDoublePtr aScalar = 
825     boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
826   if (aScalar)
827   {
828     aScalar->setValue(myParams[aFirstParamPos].val);
829     return ;
830   }
831
832   /// \todo Support other types of entities
833 }
834
835 // ============================================================================
836 //  Function: updateEntityIfPossible
837 //  Class:    SketchSolver_ConstraintGroup
838 //  Purpose:  search the entity in this group and update it
839 // ============================================================================
840 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
841                 boost::shared_ptr<ModelAPI_Attribute> theEntity)
842 {
843   if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end())
844   {
845     // If the attribute is a point and it is changed (the group needs to rebuild),
846     // probably user has dragged this point into this position,
847     // so it is necessary to add constraint which will guarantee the point will not change
848
849     // Store myNeedToSolve flag to verify the entity is really changed
850     bool aNeedToSolveCopy = myNeedToSolve;
851     myNeedToSolve = false;
852
853     changeEntity(theEntity);
854
855     if (myNeedToSolve) // the entity is changed
856     {
857       // Verify the entity is a point and add temporary constraint of permanency
858       boost::shared_ptr<GeomDataAPI_Point> aPoint =
859         boost::dynamic_pointer_cast<GeomDataAPI_Point>(theEntity);
860       boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
861         boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
862       if (aPoint || aPoint2D)
863         addTemporaryConstraintWhereDragged(theEntity);
864     }
865
866     // Restore flag of changes
867     myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
868
869     updateRelatedConstraints(theEntity);
870   }
871 }
872
873 // ============================================================================
874 //  Function: addTemporaryConstraintWhereDragged
875 //  Class:    SketchSolver_ConstraintGroup
876 //  Purpose:  add transient constraint SLVS_C_WHERE_DRAGGED for the entity, 
877 //            which was moved by user
878 // ============================================================================
879 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
880                 boost::shared_ptr<ModelAPI_Attribute> theEntity)
881 {
882   // Find identifier of the entity
883   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
884     anEntIter = myEntityAttrMap.find(theEntity);
885   if (anEntIter == myEntityAttrMap.end())
886     return ;
887
888   // If this is a first dragged point, its parameters should be placed 
889   // into Slvs_System::dragged field to avoid system inconsistense
890   if (myTempPointWhereDragged.empty())
891   {
892     int anEntPos = Search(anEntIter->second, myEntities);
893     Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
894     for (int i = 0; i < 4; i++, aDraggedParam++)
895       if (*aDraggedParam != 0)
896         myTempPointWhereDragged.push_back(*aDraggedParam);
897     myTempPointWDrgdID = myEntities[anEntPos].h;
898     return ;
899   }
900
901   // Get identifiers of all dragged points
902   std::set<Slvs_hEntity> aDraggedPntID;
903   aDraggedPntID.insert(myTempPointWDrgdID);
904   std::list<Slvs_hConstraint>::iterator aTmpCoIter = myTempConstraints.begin();
905   for ( ; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++)
906   {
907     unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
908     if (aConstrPos < myConstraints.size())
909       aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
910   }
911   // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
912   std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
913   for ( ; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
914   {
915     if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
916       continue; // the entity was not found in current set
917
918     // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
919     std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
920     for ( ; aDrgIter != aDraggedPntID.end(); aDrgIter++)
921       if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
922         return ; // the SLVS_C_WHERE_DRAGGED constraint already exists
923   }
924
925   // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
926   Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
927                                                   myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
928   myConstraints.push_back(aWDConstr);
929   myTempConstraints.push_back(aWDConstr.h);
930 }
931
932 // ============================================================================
933 //  Function: removeTemporaryConstraints
934 //  Class:    SketchSolver_ConstraintGroup
935 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
936 //            resolving the set of constraints
937 // ============================================================================
938 void SketchSolver_ConstraintGroup::removeTemporaryConstraints()
939 {
940   std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
941   for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend(); aTmpConstrIter++)
942   {
943     unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
944     if (aConstrPos >= myConstraints.size())
945       continue;
946     myConstraints.erase(myConstraints.begin() + aConstrPos);
947
948     // If the removing constraint has higher index, decrease the indexer
949     if (*aTmpConstrIter == myConstrMaxID)
950       myConstrMaxID--;
951   }
952   myTempConstraints.clear();
953
954   // Clear basic dragged point
955   myTempPointWhereDragged.clear();
956 }
957
958 // ============================================================================
959 //  Function: removeConstraint
960 //  Class:    SketchSolver_ConstraintGroup
961 //  Purpose:  remove constraint and all unused entities
962 // ============================================================================
963 void SketchSolver_ConstraintGroup::removeConstraint(boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
964 {
965   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::iterator
966     anIterToRemove = myConstraintMap.find(theConstraint);
967   if (anIterToRemove == myConstraintMap.end())
968      return ;
969
970   Slvs_hConstraint aCnstrToRemove = anIterToRemove->second;
971   // Remove constraint from the map
972   myConstraintMap.erase(anIterToRemove);
973
974   // Find unused entities
975   int aConstrPos = Search(aCnstrToRemove, myConstraints);
976   std::set<Slvs_hEntity> anEntToRemove;
977   Slvs_hEntity aCnstEnt[] = {myConstraints[aConstrPos].ptA,     myConstraints[aConstrPos].ptB, 
978                              myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB};
979   for (int i = 0; i < 4; i++)
980     if (aCnstEnt[i] != 0)
981       anEntToRemove.insert(aCnstEnt[i]);
982   myConstraints.erase(myConstraints.begin() + aConstrPos);
983   if (aCnstrToRemove == myConstrMaxID)
984     myConstrMaxID--;
985   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
986   for ( ; aConstrIter != myConstraints.end(); aConstrIter++)
987   {
988     Slvs_hEntity aEnts[] = {aConstrIter->ptA,     aConstrIter->ptB, 
989                             aConstrIter->entityA, aConstrIter->entityB};
990     for (int i = 0; i < 4; i++)
991       if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
992         anEntToRemove.erase(aEnts[i]);
993   }
994
995   if (anEntToRemove.empty())
996     return ;
997
998   // Remove unused entities
999   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1000     anEntAttrIter = myEntityAttrMap.begin();
1001   while (anEntAttrIter != myEntityAttrMap.end())
1002   {
1003     if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end())
1004     {
1005       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1006         aRemovedIter = anEntAttrIter;
1007       anEntAttrIter++;
1008       myEntityAttrMap.erase(aRemovedIter);
1009     }
1010     else anEntAttrIter++;
1011   }
1012   std::map<FeaturePtr, Slvs_hEntity>::iterator
1013     anEntFeatIter = myEntityFeatMap.begin();
1014   while (anEntFeatIter != myEntityFeatMap.end())
1015   {
1016     if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end())
1017     {
1018       std::map<FeaturePtr, Slvs_hEntity>::iterator
1019         aRemovedIter = anEntFeatIter;
1020       anEntFeatIter++;
1021       myEntityFeatMap.erase(aRemovedIter);
1022     }
1023     else anEntFeatIter++;
1024   }
1025   std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = anEntToRemove.rbegin();
1026   for ( ; aRemIter != anEntToRemove.rend(); aRemIter++)
1027   {
1028     unsigned int anEntPos = Search(*aRemIter, myEntities);
1029     if (anEntPos >= myEntities.size())
1030       continue;
1031     unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1032     if (aParamPos >= myParams.size())
1033       continue;
1034     int aNbParams = 0;
1035     while (myEntities[anEntPos].param[aNbParams] != 0) 
1036       aNbParams++;
1037     if (myEntities[anEntPos].param[aNbParams-1] == myParamMaxID)
1038       myParamMaxID -= aNbParams;
1039     myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1040     if (*aRemIter == myEntityMaxID)
1041       myEntityMaxID--;
1042     myEntities.erase(myEntities.begin() + anEntPos);
1043
1044     // Remove entity's ID from the lists of conincident points
1045     std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1046     for ( ; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1047       aCoPtIter->erase(*aRemIter);
1048   }
1049   if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1050     myCoincidentPoints.clear();
1051 }
1052
1053
1054 // ============================================================================
1055 //  Function: addCoincidentPoints
1056 //  Class:    SketchSolver_ConstraintGroup
1057 //  Purpose:  add coincident point the appropriate list of such points
1058 // ============================================================================
1059 bool SketchSolver_ConstraintGroup::addCoincidentPoints(
1060                 const Slvs_hEntity& thePoint1, const Slvs_hEntity& thePoint2)
1061 {
1062   std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1063   std::vector< std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1064   while (aCoPtIter != myCoincidentPoints.end())
1065   {
1066     bool isFound[2] = { // indicate which point ID was already in coincidence constraint
1067       aCoPtIter->find(thePoint1) != aCoPtIter->end(),
1068       aCoPtIter->find(thePoint2) != aCoPtIter->end(),
1069     };
1070     if (isFound[0] && isFound[1]) // points are already connected by coincidence constraints => no need additional one
1071       return false;
1072     if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1]))
1073     {
1074       if (aFirstFound != myCoincidentPoints.end())
1075       { // there are two groups of coincident points connected by created constraint => merge them
1076         int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1077         int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1078         aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1079         myCoincidentPoints.erase(aCoPtIter);
1080         aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1081         aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1082         continue;
1083       }
1084       else
1085       {
1086         aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1087         aFirstFound = aCoPtIter;
1088       }
1089     }
1090     aCoPtIter++;
1091   }
1092   // No points were found, need to create new set
1093   if (aFirstFound == myCoincidentPoints.end())
1094   {
1095     std::set<Slvs_hEntity> aNewSet;
1096     aNewSet.insert(thePoint1);
1097     aNewSet.insert(thePoint2);
1098     myCoincidentPoints.push_back(aNewSet);
1099   }
1100
1101   return true;
1102 }
1103
1104
1105 // ============================================================================
1106 //  Function: updateRelatedConstraints
1107 //  Class:    SketchSolver_ConstraintGroup
1108 //  Purpose:  emit the signal to update constraints
1109 // ============================================================================
1110 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1111                     boost::shared_ptr<ModelAPI_Attribute> theEntity) const
1112 {
1113   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
1114     aConstrIter = myConstraintMap.begin();
1115   for ( ; aConstrIter != myConstraintMap.end(); aConstrIter++)
1116   {
1117     std::list< boost::shared_ptr<ModelAPI_Attribute> > anAttributes = 
1118       aConstrIter->first->data()->attributes(theEntity->attributeType());
1119
1120     std::list< boost::shared_ptr<ModelAPI_Attribute> >::iterator
1121       anAttrIter = anAttributes.begin();
1122     for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
1123       if (*anAttrIter == theEntity)
1124       {
1125         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
1126         Model_FeatureUpdatedMessage aMsg(aConstrIter->first, anEvent);
1127         Events_Loop::loop()->send(aMsg, true);
1128         break;
1129       }
1130   }
1131 }
1132
1133 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1134                     boost::shared_ptr<ModelAPI_Feature> theFeature) const
1135 {
1136   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
1137     aConstrIter = myConstraintMap.begin();
1138   for ( ; aConstrIter != myConstraintMap.end(); aConstrIter++)
1139   {
1140     std::list< boost::shared_ptr<ModelAPI_Attribute> > anAttributes = 
1141       aConstrIter->first->data()->attributes(std::string());
1142
1143     std::list< boost::shared_ptr<ModelAPI_Attribute> >::iterator
1144       anAttrIter = anAttributes.begin();
1145     for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
1146     {
1147       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = 
1148         boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
1149       if (aRefAttr && aRefAttr->isFeature() && aRefAttr->feature() == theFeature)
1150       {
1151         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
1152         Model_FeatureUpdatedMessage aMsg(aConstrIter->first, anEvent);
1153         Events_Loop::loop()->send(aMsg, true);
1154         break;
1155       }
1156     }
1157   }
1158 }
1159
1160
1161
1162 // ========================================================
1163 // =========      Auxiliary functions       ===============
1164 // ========================================================
1165
1166 template <typename T>
1167 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1168 {
1169   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1170   int aVecSize = theEntities.size();
1171   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1172     aResIndex--;
1173   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1174     aResIndex++;
1175   if (aResIndex == -1)
1176     aResIndex = aVecSize;
1177   return aResIndex;
1178 }