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