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