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