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