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