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