]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_ConstraintGroup.cpp
Salome HOME
68b5c4736f710c4c9dea6dd697fbd91fe5416a1a
[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   if (isEntExists) {
401     if (!myEntOfConstr[aEntPos]) // the entity is not used by constraints, no need to resolve them
402       myNeedToSolve = isNeedToSolve;
403     else
404       myNeedToSolve = myNeedToSolve || isNeedToSolve;
405     return aEntIter->second;
406   }
407
408   if (aNewEntity.h != SLVS_E_UNKNOWN) {
409     myEntities.push_back(aNewEntity);
410     myEntOfConstr.push_back(false);
411     myEntityAttrMap[theEntity] = aNewEntity.h;
412     return aNewEntity.h;
413   }
414
415   // Unsupported or wrong entity type
416   return SLVS_E_UNKNOWN;
417 }
418
419 // ============================================================================
420 //  Function: changeEntity
421 //  Class:    SketchSolver_ConstraintGroup
422 //  Purpose:  create/update the element defined by the feature affected by any constraint
423 // ============================================================================
424 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(FeaturePtr theEntity)
425 {
426   if (!theEntity->data()->isValid())
427     return SLVS_E_UNKNOWN;
428   // If the entity is already in the group, try to find it
429   std::map<FeaturePtr, Slvs_hEntity>::const_iterator aEntIter = myEntityFeatMap.find(theEntity);
430   // defines that the entity already exists
431   const bool isEntExists = (myEntityFeatMap.find(theEntity) != myEntityFeatMap.end());
432   
433   Slvs_Entity aNewEntity;
434   aNewEntity.h = SLVS_E_UNKNOWN;
435
436   // SketchPlugin features
437   boost::shared_ptr<SketchPlugin_Feature> aFeature = boost::dynamic_pointer_cast<
438       SketchPlugin_Feature>(theEntity);
439   if (aFeature) {  // Verify the feature by its kind
440     const std::string& aFeatureKind = aFeature->getKind();
441
442     std::list<AttributePtr> anAttributes = aFeature->data()->attributes(std::string());
443     std::list<AttributePtr>::iterator anAttrIter = anAttributes.begin();
444     for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
445       if (!(*anAttrIter)->isInitialized()) // the entity is not fully initialized, don't add it into solver
446         return SLVS_E_UNKNOWN;
447
448     // Line
449     if (aFeatureKind.compare(SketchPlugin_Line::ID()) == 0) {
450       Slvs_hEntity aStart = changeEntity(
451           aFeature->data()->attribute(SketchPlugin_Line::START_ID()));
452       Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(SketchPlugin_Line::END_ID()));
453
454       if (!isEntExists) // New entity
455         aNewEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
456     }
457     // Circle
458     else if (aFeatureKind.compare(SketchPlugin_Circle::ID()) == 0) {
459       Slvs_hEntity aCenter = changeEntity(
460           aFeature->data()->attribute(SketchPlugin_Circle::CENTER_ID()));
461       Slvs_hEntity aRadius = changeEntity(
462           aFeature->data()->attribute(SketchPlugin_Circle::RADIUS_ID()));
463
464       if (!isEntExists) // New entity
465         aNewEntity = Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter,
466                                      myWorkplane.normal, aRadius);
467     }
468     // Arc
469     else if (aFeatureKind.compare(SketchPlugin_Arc::ID()) == 0) {
470       Slvs_hEntity aCenter = changeEntity(
471           aFeature->data()->attribute(SketchPlugin_Arc::CENTER_ID()));
472       Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(SketchPlugin_Arc::START_ID()));
473       Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(SketchPlugin_Arc::END_ID()));
474
475       if (!isEntExists)
476         aNewEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID, myWorkplane.h,
477                                           myWorkplane.normal, aCenter, aStart, aEnd);
478     }
479     // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
480     else if (aFeatureKind.compare(SketchPlugin_Point::ID()) == 0) {
481       Slvs_hEntity aPoint = changeEntity(
482           aFeature->data()->attribute(SketchPlugin_Point::COORD_ID()));
483
484       if (isEntExists)
485         return aEntIter->second;
486
487       // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
488       myEntityFeatMap[theEntity] = aPoint;
489       myNeedToSolve = true;
490       return aPoint;
491     }
492   }
493   /// \todo Other types of features
494
495   if (isEntExists)
496     return aEntIter->second;
497
498   if (aNewEntity.h != SLVS_E_UNKNOWN) {
499     myEntities.push_back(aNewEntity);
500     myEntOfConstr.push_back(false);
501     myEntityFeatMap[theEntity] = aNewEntity.h;
502     myNeedToSolve = true;
503     return aNewEntity.h;
504   }
505
506
507   // Unsupported or wrong entity type
508   return SLVS_E_UNKNOWN;
509 }
510
511 // ============================================================================
512 //  Function: changeNormal
513 //  Class:    SketchSolver_ConstraintGroup
514 //  Purpose:  create/update the normal of workplane
515 // ============================================================================
516 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
517     boost::shared_ptr<ModelAPI_Attribute> theDirX, boost::shared_ptr<ModelAPI_Attribute> theDirY,
518     boost::shared_ptr<ModelAPI_Attribute> theNorm)
519 {
520   boost::shared_ptr<GeomDataAPI_Dir> aDirX = boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
521   boost::shared_ptr<GeomDataAPI_Dir> aDirY = boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
522   if (!aDirX || !aDirY || (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance)
523       || (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
524     return SLVS_E_UNKNOWN;
525
526   // quaternion parameters of normal vector
527   double qw, qx, qy, qz;
528   Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(), aDirY->x(), aDirY->y(), aDirY->z(), &qw,
529                       &qx, &qy, &qz);
530   double aNormCoord[4] = { qw, qx, qy, qz };
531
532   // Try to find existent normal
533   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aEntIter =
534       myEntityAttrMap.find(theNorm);
535   std::vector<Slvs_Param>::const_iterator aParamIter;  // looks to the first parameter of already existent entity or to the end of vector otherwise
536   if (aEntIter == myEntityAttrMap.end())  // no such entity => should be created
537     aParamIter = myParams.end();
538   else {  // the entity already exists, update it
539     int aEntPos = Search(aEntIter->second, myEntities);
540     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
541     aParamIter = myParams.begin() + aParamPos;
542   }
543
544   // Change parameters of the normal
545   Slvs_hParam aNormParams[4];
546   for (int i = 0; i < 4; i++)
547     aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
548
549   if (aEntIter != myEntityAttrMap.end())  // the entity already exists
550     return aEntIter->second;
551
552   // Create a normal
553   Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID, aNormParams[0], aNormParams[1],
554                                           aNormParams[2], aNormParams[3]);
555   myEntities.push_back(aNormal);
556   myEntOfConstr.push_back(false);
557   myEntityAttrMap[theNorm] = aNormal.h;
558   return aNormal.h;
559 }
560
561 // ============================================================================
562 //  Function: addWorkplane
563 //  Class:    SketchSolver_ConstraintGroup
564 //  Purpose:  create workplane for the group
565 // ============================================================================
566 bool SketchSolver_ConstraintGroup::addWorkplane(boost::shared_ptr<SketchPlugin_Feature> theSketch)
567 {
568   if (myWorkplane.h || theSketch->getKind().compare(SketchPlugin_Sketch::ID()) != 0)
569     return false;  // the workplane already exists or the function parameter is not Sketch
570
571   mySketch = theSketch;
572   updateWorkplane();
573   return true;
574 }
575
576 // ============================================================================
577 //  Function: updateWorkplane
578 //  Class:    SketchSolver_ConstraintGroup
579 //  Purpose:  update parameters of workplane
580 // ============================================================================
581 bool SketchSolver_ConstraintGroup::updateWorkplane()
582 {
583   // Get parameters of workplane
584   boost::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(
585       SketchPlugin_Sketch::DIRX_ID());
586   boost::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(
587       SketchPlugin_Sketch::DIRY_ID());
588   boost::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(
589       SketchPlugin_Sketch::NORM_ID());
590   boost::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(
591       SketchPlugin_Sketch::ORIGIN_ID());
592   // Transform them into SolveSpace format
593   Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
594   if (!aNormalWP)
595     return false;
596   Slvs_hEntity anOriginWP = changeEntity(anOrigin);
597   if (!anOriginWP)
598     return false;
599
600   if (!myWorkplane.h) {
601     // Create workplane
602     myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
603     // Workplane should be added to the list of entities
604     myEntities.push_back(myWorkplane);
605     myEntOfConstr.push_back(false);
606   }
607   return true;
608 }
609
610 // ============================================================================
611 //  Function: changeParameter
612 //  Class:    SketchSolver_ConstraintGroup
613 //  Purpose:  create/update value of parameter
614 // ============================================================================
615 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
616     const double& theParam, std::vector<Slvs_Param>::const_iterator& thePrmIter)
617 {
618   if (thePrmIter != myParams.end()) {  // Parameter should be updated
619     int aParamPos = thePrmIter - myParams.begin();
620     if (fabs(thePrmIter->val - theParam) > tolerance) {
621       myNeedToSolve = true;  // parameter is changed, need to resolve constraints
622       myParams[aParamPos].val = theParam;
623     }
624     thePrmIter++;
625     return myParams[aParamPos].h;
626   }
627
628   // Newly created parameter
629   Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
630   myParams.push_back(aParam);
631   myNeedToSolve = true;
632   // The list of parameters is changed, move iterator to the end of the list to avoid problems
633   thePrmIter = myParams.end();
634   return aParam.h;
635 }
636
637 // ============================================================================
638 //  Function: resolveConstraints
639 //  Class:    SketchSolver_ConstraintGroup
640 //  Purpose:  solve the set of constraints for the current group
641 // ============================================================================
642 bool SketchSolver_ConstraintGroup::resolveConstraints()
643 {
644   if (!myNeedToSolve)
645     return false;
646
647   myConstrSolver.setGroupID(myID);
648   myConstrSolver.setParameters(myParams);
649   myConstrSolver.setEntities(myEntities);
650   myConstrSolver.setConstraints(myConstraints);
651   myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
652
653   int aResult = myConstrSolver.solve();
654   if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
655                                       // Obtain result into the same list of parameters
656     if (!myConstrSolver.getResult(myParams))
657       return true;
658
659     // We should go through the attributes map, because only attributes have valued parameters
660     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntIter =
661         myEntityAttrMap.begin();
662     for (; anEntIter != myEntityAttrMap.end(); anEntIter++)
663       if (updateAttribute(anEntIter->first, anEntIter->second))
664         updateRelatedConstraints(anEntIter->first);
665   } else if (!myConstraints.empty())
666     Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
667
668   removeTemporaryConstraints();
669   myNeedToSolve = false;
670   return true;
671 }
672
673 // ============================================================================
674 //  Function: mergeGroups
675 //  Class:    SketchSolver_ConstraintGroup
676 //  Purpose:  append specified group to the current group
677 // ============================================================================
678 void SketchSolver_ConstraintGroup::mergeGroups(const SketchSolver_ConstraintGroup& theGroup)
679 {
680   // If specified group is empty, no need to merge
681   if (theGroup.myConstraintMap.empty())
682     return;
683
684   // Map between old and new indexes of SolveSpace constraints
685   std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
686
687   // Add all constraints from theGroup to the current group
688   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrIter =
689       theGroup.myConstraintMap.begin();
690   for (; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
691     if (changeConstraint(aConstrIter->first))
692       aConstrMap[aConstrIter->second] = myConstrMaxID;  // the constraint was added => store its ID
693
694   // Add temporary constraints from theGroup
695   std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
696   for (; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++) {
697     std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(
698         *aTempConstrIter);
699     if (aFind != aConstrMap.end())
700       myTempConstraints.push_back(aFind->second);
701   }
702
703   if (myTempPointWhereDragged.empty())
704     myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
705   else if (!theGroup.myTempPointWhereDragged.empty()) {  // Need to create additional transient constraint
706     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aFeatureIter =
707         theGroup.myEntityAttrMap.begin();
708     for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
709       if (aFeatureIter->second == myTempPointWDrgdID) {
710         addTemporaryConstraintWhereDragged(aFeatureIter->first);
711         break;
712       }
713   }
714
715   myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
716 }
717
718 // ============================================================================
719 //  Function: splitGroup
720 //  Class:    SketchSolver_ConstraintGroup
721 //  Purpose:  divide the group into several subgroups
722 // ============================================================================
723 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
724 {
725   // Divide constraints and entities into several groups
726   std::vector<std::set<Slvs_hEntity> > aGroupsEntities;
727   std::vector<std::set<Slvs_hConstraint> > aGroupsConstr;
728   int aMaxNbEntities = 0;  // index of the group with maximal nuber of elements (this group will be left in the current)
729   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
730   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
731     Slvs_hEntity aConstrEnt[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA,
732         aConstrIter->entityB };
733     std::vector<int> anIndexes;
734     // Go through the groupped entities and find even one of entities of current constraint
735     std::vector<std::set<Slvs_hEntity> >::iterator aGrEntIter;
736     for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++) {
737       bool isFound = false;
738       for (int i = 0; i < 4 && !isFound; i++)
739         if (aConstrEnt[i] != 0) {
740           isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
741           // Also we need to check sub-entities
742           int aEntPos = Search(aConstrEnt[i], myEntities);
743           Slvs_hEntity* aSub = myEntities[aEntPos].point;
744           for (int j = 0; *aSub != 0 && j < 4 && !isFound; aSub++)
745             isFound = (aGrEntIter->find(*aSub) != aGrEntIter->end());
746         }
747       if (isFound)
748         anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
749     }
750     // Add new group if no one is found
751     if (anIndexes.empty()) {
752       std::set<Slvs_hEntity> aNewGrEnt;
753       for (int i = 0; i < 4; i++)
754         if (aConstrEnt[i] != 0)
755           aNewGrEnt.insert(aConstrEnt[i]);
756       std::set<Slvs_hConstraint> aNewGrConstr;
757       aNewGrConstr.insert(aConstrIter->h);
758
759       aGroupsEntities.push_back(aNewGrEnt);
760       aGroupsConstr.push_back(aNewGrConstr);
761       if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
762         aMaxNbEntities = aGroupsEntities.size() - 1;
763     } else if (anIndexes.size() == 1) {  // Add entities indexes into the found group
764       aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
765       for (int i = 0; i < 4; i++)
766         if (aConstrEnt[i] != 0)
767           aGrEntIter->insert(aConstrEnt[i]);
768       aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
769       if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
770         aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
771     } else {  // There are found several connected groups, merge them
772       std::vector<std::set<Slvs_hEntity> >::iterator aFirstGroup = aGroupsEntities.begin()
773           + anIndexes.front();
774       std::vector<std::set<Slvs_hConstraint> >::iterator aFirstConstr = aGroupsConstr.begin()
775           + anIndexes.front();
776       std::vector<int>::iterator anInd = anIndexes.begin();
777       for (++anInd; anInd != anIndexes.end(); anInd++) {
778         aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
779         aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
780       }
781       if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
782         aMaxNbEntities = anIndexes.front();
783       // Remove merged groups
784       for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--) {
785         aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
786         aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
787       }
788     }
789   }
790
791   if (aGroupsEntities.size() <= 1)
792     return;
793
794   // Remove the group with maximum elements as it will be left in the current group
795   aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
796   aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
797
798   // Add new groups of constraints and divide current group
799   std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
800   for (int i = aGroupsEntities.size(); i > 0; i--) {
801     SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
802     aNewGroups.push_back(aG);
803   }
804   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrMapIter =
805       myConstraintMap.begin();
806   int aConstrMapPos = 0;  // position of iterator in the map (used to restore iterator after removing constraint)
807   while (aConstrMapIter != myConstraintMap.end()) {
808     std::vector<std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
809     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
810     for (; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
811       if (aGIter->find(aConstrMapIter->second) != aGIter->end()) {
812         (*aGroup)->changeConstraint(aConstrMapIter->first);
813         removeConstraint(aConstrMapIter->first);
814         // restore iterator
815         aConstrMapIter = myConstraintMap.begin();
816         for (int i = 0; i < aConstrMapPos; i++)
817           aConstrMapIter++;
818         break;
819       }
820     if (aGIter == aGroupsConstr.end()) {
821       aConstrMapIter++;
822       aConstrMapPos++;
823     }
824   }
825
826   theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
827 }
828
829 // ============================================================================
830 //  Function: updateGroup
831 //  Class:    SketchSolver_ConstraintGroup
832 //  Purpose:  search removed entities and constraints
833 // ============================================================================
834 bool SketchSolver_ConstraintGroup::updateGroup()
835 {
836   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator aConstrIter =
837       myConstraintMap.rbegin();
838   bool isAllValid = true;
839   bool isCCRemoved = false;  // indicates that at least one of coincidence constraints was removed
840   int aConstrIndex = 0;
841   while (/*isAllValid && */aConstrIter != myConstraintMap.rend()) {
842     if (!aConstrIter->first->data() || !aConstrIter->first->data()->isValid()) {
843       if (aConstrIter->first->getKind().compare(SketchPlugin_ConstraintCoincidence::ID()) == 0)
844         isCCRemoved = true;
845       removeConstraint(aConstrIter->first);
846       isAllValid = false;
847       // Get back the correct position of iterator after the "remove" operation
848       aConstrIter = myConstraintMap.rbegin();
849       for (int i = 0; i < aConstrIndex && aConstrIter != myConstraintMap.rend(); i++)
850         aConstrIter++;
851     } else {
852       aConstrIter++;
853       aConstrIndex++;
854     }
855   }
856
857   // Check if some entities are invalid too
858   std::set<Slvs_hEntity> anEntToRemove;
859   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
860       anAttrIter = myEntityAttrMap.begin();
861   while (anAttrIter != myEntityAttrMap.end()) {
862     if (!anAttrIter->first->owner() || !anAttrIter->first->owner()->data() ||
863         !anAttrIter->first->owner()->data()->isValid()) {
864       anEntToRemove.insert(anAttrIter->second);
865       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
866           aRemovedIter = anAttrIter;
867       anAttrIter++;
868       myEntityAttrMap.erase(aRemovedIter);
869     } else
870       anAttrIter++;
871   }
872   std::map<FeaturePtr, Slvs_hEntity>::iterator aFeatIter = myEntityFeatMap.begin();
873   while (aFeatIter != myEntityFeatMap.end()) {
874     if (!aFeatIter->first || !aFeatIter->first->data() ||
875         !aFeatIter->first->data()->isValid()) {
876       anEntToRemove.insert(aFeatIter->second);
877       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = aFeatIter;
878       aFeatIter++;
879       myEntityFeatMap.erase(aRemovedIter);
880     } else
881       aFeatIter++;
882   }
883   removeEntitiesById(anEntToRemove);
884
885   // Probably, need to update coincidence constraints
886   if (isCCRemoved && !myExtraCoincidence.empty()) {
887     // Make a copy, because the new list of unused constrtaints will be generated
888     std::set<boost::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
889     myExtraCoincidence.clear();
890
891     std::set<boost::shared_ptr<SketchPlugin_Constraint> >::iterator aCIter = anExtraCopy.begin();
892     for (; aCIter != anExtraCopy.end(); aCIter++)
893       if ((*aCIter)->data() && (*aCIter)->data()->isValid())
894         changeConstraint(*aCIter);
895   }
896
897   return !isAllValid;
898 }
899
900 // ============================================================================
901 //  Function: updateAttribute
902 //  Class:    SketchSolver_ConstraintGroup
903 //  Purpose:  update features of sketch after resolving constraints
904 // ============================================================================
905 bool SketchSolver_ConstraintGroup::updateAttribute(
906     boost::shared_ptr<ModelAPI_Attribute> theAttribute, const Slvs_hEntity& theEntityID)
907 {
908   // Search the position of the first parameter of the entity
909   int anEntPos = Search(theEntityID, myEntities);
910   int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
911
912   // Look over supported types of entities
913
914   // Point in 3D
915   boost::shared_ptr<GeomDataAPI_Point> aPoint = boost::dynamic_pointer_cast<GeomDataAPI_Point>(
916       theAttribute);
917   if (aPoint) {
918     if (fabs(aPoint->x() - myParams[aFirstParamPos].val) > tolerance
919         || fabs(aPoint->y() - myParams[aFirstParamPos + 1].val) > tolerance
920         || fabs(aPoint->z() - myParams[aFirstParamPos + 2].val) > tolerance) {
921       aPoint->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val,
922                        myParams[aFirstParamPos + 2].val);
923       return true;
924     }
925     return false;
926   }
927
928   // Point in 2D
929   boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
930       boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
931   if (aPoint2D) {
932     if (fabs(aPoint2D->x() - myParams[aFirstParamPos].val) > tolerance
933         || fabs(aPoint2D->y() - myParams[aFirstParamPos + 1].val) > tolerance) {
934       aPoint2D->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val);
935       return true;
936     }
937     return false;
938   }
939
940   // Scalar value
941   AttributeDoublePtr aScalar = boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
942   if (aScalar) {
943     if (fabs(aScalar->value() - myParams[aFirstParamPos].val) > tolerance) {
944       aScalar->setValue(myParams[aFirstParamPos].val);
945       return true;
946     }
947     return false;
948   }
949
950   /// \todo Support other types of entities
951   return false;
952 }
953
954 // ============================================================================
955 //  Function: updateEntityIfPossible
956 //  Class:    SketchSolver_ConstraintGroup
957 //  Purpose:  search the entity in this group and update it
958 // ============================================================================
959 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
960     boost::shared_ptr<ModelAPI_Attribute> theEntity)
961 {
962   if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end()) {
963     // If the attribute is a point and it is changed (the group needs to rebuild),
964     // probably user has dragged this point into this position,
965     // so it is necessary to add constraint which will guarantee the point will not change
966
967     // Store myNeedToSolve flag to verify the entity is really changed
968     bool aNeedToSolveCopy = myNeedToSolve;
969     myNeedToSolve = false;
970
971     changeEntity(theEntity);
972
973     if (myNeedToSolve)  // the entity is changed
974     {
975       // Verify the entity is a point and add temporary constraint of permanency
976       boost::shared_ptr<GeomDataAPI_Point> aPoint = boost::dynamic_pointer_cast<GeomDataAPI_Point>(
977           theEntity);
978       boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D = boost::dynamic_pointer_cast<
979           GeomDataAPI_Point2D>(theEntity);
980       if (aPoint || aPoint2D)
981         addTemporaryConstraintWhereDragged(theEntity);
982     }
983
984     // Restore flag of changes
985     myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
986
987     if (myNeedToSolve)
988       updateRelatedConstraints(theEntity);
989   }
990 }
991
992 // ============================================================================
993 //  Function: addTemporaryConstraintWhereDragged
994 //  Class:    SketchSolver_ConstraintGroup
995 //  Purpose:  add transient constraint SLVS_C_WHERE_DRAGGED for the entity, 
996 //            which was moved by user
997 // ============================================================================
998 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
999     boost::shared_ptr<ModelAPI_Attribute> theEntity)
1000 {
1001   // Find identifier of the entity
1002   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator anEntIter =
1003       myEntityAttrMap.find(theEntity);
1004   if (anEntIter == myEntityAttrMap.end())
1005     return;
1006
1007   // If this is a first dragged point, its parameters should be placed 
1008   // into Slvs_System::dragged field to avoid system inconsistense
1009   if (myTempPointWhereDragged.empty()) {
1010     int anEntPos = Search(anEntIter->second, myEntities);
1011     Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
1012     for (int i = 0; i < 4; i++, aDraggedParam++)
1013       if (*aDraggedParam != 0)
1014         myTempPointWhereDragged.push_back(*aDraggedParam);
1015     myTempPointWDrgdID = myEntities[anEntPos].h;
1016     return;
1017   }
1018
1019   // Get identifiers of all dragged points
1020   std::set<Slvs_hEntity> aDraggedPntID;
1021   aDraggedPntID.insert(myTempPointWDrgdID);
1022   std::list<Slvs_hConstraint>::iterator aTmpCoIter = myTempConstraints.begin();
1023   for (; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++) {
1024     unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
1025     if (aConstrPos < myConstraints.size())
1026       aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
1027   }
1028   // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
1029   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1030   for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++) {
1031     if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
1032       continue;  // the entity was not found in current set
1033
1034     // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
1035     std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
1036     for (; aDrgIter != aDraggedPntID.end(); aDrgIter++)
1037       if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
1038         return;  // the SLVS_C_WHERE_DRAGGED constraint already exists
1039   }
1040
1041   // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
1042   Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
1043                                                   myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
1044   myConstraints.push_back(aWDConstr);
1045   myTempConstraints.push_back(aWDConstr.h);
1046 }
1047
1048 // ============================================================================
1049 //  Function: removeTemporaryConstraints
1050 //  Class:    SketchSolver_ConstraintGroup
1051 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
1052 //            resolving the set of constraints
1053 // ============================================================================
1054 void SketchSolver_ConstraintGroup::removeTemporaryConstraints()
1055 {
1056   std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
1057   for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend();
1058       aTmpConstrIter++) {
1059     unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
1060     if (aConstrPos >= myConstraints.size())
1061       continue;
1062     myConstraints.erase(myConstraints.begin() + aConstrPos);
1063
1064     // If the removing constraint has higher index, decrease the indexer
1065     if (*aTmpConstrIter == myConstrMaxID)
1066       myConstrMaxID--;
1067   }
1068   myTempConstraints.clear();
1069
1070   // Clear basic dragged point
1071   myTempPointWhereDragged.clear();
1072 }
1073
1074 // ============================================================================
1075 //  Function: removeConstraint
1076 //  Class:    SketchSolver_ConstraintGroup
1077 //  Purpose:  remove constraint and all unused entities
1078 // ============================================================================
1079 void SketchSolver_ConstraintGroup::removeConstraint(
1080     boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
1081 {
1082   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::iterator anIterToRemove =
1083       myConstraintMap.find(theConstraint);
1084   if (anIterToRemove == myConstraintMap.end())
1085     return;
1086
1087   Slvs_hConstraint aCnstrToRemove = anIterToRemove->second;
1088   // Remove constraint from the map
1089   myConstraintMap.erase(anIterToRemove);
1090
1091   // Find unused entities
1092   int aConstrPos = Search(aCnstrToRemove, myConstraints);
1093   std::set<Slvs_hEntity> anEntToRemove;
1094   Slvs_hEntity aCnstEnt[] = { myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
1095       myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB };
1096   for (int i = 0; i < 4; i++)
1097     if (aCnstEnt[i] != 0)
1098       anEntToRemove.insert(aCnstEnt[i]);
1099   myConstraints.erase(myConstraints.begin() + aConstrPos);
1100   if (aCnstrToRemove == myConstrMaxID)
1101     myConstrMaxID--;
1102
1103   // Find all entities which are based on these unused
1104   std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
1105   for ( ; anEntIter != myEntities.end(); anEntIter++)
1106     if (anEntIter->type == SLVS_E_LINE_SEGMENT || anEntIter->type == SLVS_E_CIRCLE ||
1107         anEntIter->type == SLVS_E_ARC_OF_CIRCLE) {
1108       for (int i = 0; i < 4; i++)
1109         if (anEntToRemove.find(anEntIter->point[i]) != anEntToRemove.end()) {
1110           anEntToRemove.insert(anEntIter->h);
1111           for (int j = 0; j < 4; j++)
1112             if (anEntIter->param[j] != 0)
1113               anEntToRemove.insert(anEntIter->point[j]);
1114           break;
1115         }
1116     }
1117
1118   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1119   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
1120     Slvs_hEntity aEnts[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA, aConstrIter
1121         ->entityB };
1122     for (int i = 0; i < 4; i++)
1123       if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
1124         anEntToRemove.erase(aEnts[i]);
1125   }
1126
1127   if (anEntToRemove.empty())
1128     return;
1129
1130   // Remove unused entities
1131   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntAttrIter =
1132       myEntityAttrMap.begin();
1133   while (anEntAttrIter != myEntityAttrMap.end()) {
1134     if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end()) {
1135       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator aRemovedIter =
1136           anEntAttrIter;
1137       anEntAttrIter++;
1138       myEntityAttrMap.erase(aRemovedIter);
1139     } else
1140       anEntAttrIter++;
1141   }
1142   std::map<FeaturePtr, Slvs_hEntity>::iterator anEntFeatIter = myEntityFeatMap.begin();
1143   while (anEntFeatIter != myEntityFeatMap.end()) {
1144     if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end()) {
1145       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = anEntFeatIter;
1146       anEntFeatIter++;
1147       myEntityFeatMap.erase(aRemovedIter);
1148     } else
1149       anEntFeatIter++;
1150   }
1151
1152   removeEntitiesById(anEntToRemove);
1153
1154   if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1155     myCoincidentPoints.clear();
1156 }
1157
1158 // ============================================================================
1159 //  Function: removeEntitiesById
1160 //  Class:    SketchSolver_ConstraintGroup
1161 //  Purpose:  Removes specified entities and their parameters
1162 // ============================================================================
1163 void SketchSolver_ConstraintGroup::removeEntitiesById(const std::set<Slvs_hEntity>& theEntities)
1164 {
1165   std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = theEntities.rbegin();
1166   for (; aRemIter != theEntities.rend(); aRemIter++) {
1167     unsigned int anEntPos = Search(*aRemIter, myEntities);
1168     if (anEntPos >= myEntities.size())
1169       continue;
1170     if (myEntities[anEntPos].param[0] != 0) {
1171       unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1172       if (aParamPos >= myParams.size())
1173         continue;
1174       int aNbParams = 0;
1175       while (myEntities[anEntPos].param[aNbParams] != 0)
1176         aNbParams++;
1177       if (myEntities[anEntPos].param[aNbParams - 1] == myParamMaxID)
1178         myParamMaxID -= aNbParams;
1179       myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1180       if (*aRemIter == myEntityMaxID)
1181         myEntityMaxID--;
1182     }
1183     myEntities.erase(myEntities.begin() + anEntPos);
1184     myEntOfConstr.erase(myEntOfConstr.begin() + anEntPos);
1185
1186     // Remove entity's ID from the lists of conincident points
1187     std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1188     for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1189       aCoPtIter->erase(*aRemIter);
1190   }
1191 }
1192
1193 // ============================================================================
1194 //  Function: addCoincidentPoints
1195 //  Class:    SketchSolver_ConstraintGroup
1196 //  Purpose:  add coincident point the appropriate list of such points
1197 // ============================================================================
1198 bool SketchSolver_ConstraintGroup::addCoincidentPoints(const Slvs_hEntity& thePoint1,
1199                                                        const Slvs_hEntity& thePoint2)
1200 {
1201   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1202   std::vector<std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1203   while (aCoPtIter != myCoincidentPoints.end()) {
1204     bool isFound[2] = {  // indicate which point ID was already in coincidence constraint
1205         aCoPtIter->find(thePoint1) != aCoPtIter->end(), aCoPtIter->find(thePoint2)
1206             != aCoPtIter->end(), };
1207     if (isFound[0] && isFound[1])  // points are already connected by coincidence constraints => no need additional one
1208       return false;
1209     if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1])) {
1210       if (aFirstFound != myCoincidentPoints.end()) {  // there are two groups of coincident points connected by created constraint => merge them
1211         int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1212         int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1213         aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1214         myCoincidentPoints.erase(aCoPtIter);
1215         aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1216         aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1217         continue;
1218       } else {
1219         aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1220         aFirstFound = aCoPtIter;
1221       }
1222     }
1223     aCoPtIter++;
1224   }
1225   // No points were found, need to create new set
1226   if (aFirstFound == myCoincidentPoints.end()) {
1227     std::set<Slvs_hEntity> aNewSet;
1228     aNewSet.insert(thePoint1);
1229     aNewSet.insert(thePoint2);
1230     myCoincidentPoints.push_back(aNewSet);
1231   }
1232
1233   return true;
1234 }
1235
1236 // ============================================================================
1237 //  Function: updateRelatedConstraints
1238 //  Class:    SketchSolver_ConstraintGroup
1239 //  Purpose:  emit the signal to update constraints
1240 // ============================================================================
1241 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1242     boost::shared_ptr<ModelAPI_Attribute> theEntity) const
1243 {
1244   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrIter =
1245       myConstraintMap.begin();
1246   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1247     std::list<boost::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1248         ->attributes(std::string());
1249
1250     std::list<boost::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1251     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1252       bool isUpd = (*anAttrIter == theEntity);
1253       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = boost::dynamic_pointer_cast<
1254           ModelAPI_AttributeRefAttr>(*anAttrIter);
1255       if (aRefAttr && !aRefAttr->isObject() && aRefAttr->attr() == theEntity)
1256         isUpd = true;
1257
1258       if (isUpd) {
1259         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1260         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1261         break;
1262       }
1263     }
1264   }
1265 }
1266
1267 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1268     boost::shared_ptr<ModelAPI_Feature> theFeature) const
1269 {
1270   std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator aConstrIter =
1271       myConstraintMap.begin();
1272   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1273     std::list<boost::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1274         ->attributes(std::string());
1275
1276     std::list<boost::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1277     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1278       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = boost::dynamic_pointer_cast<
1279           ModelAPI_AttributeRefAttr>(*anAttrIter);
1280       if (aRefAttr && aRefAttr->isObject() && aRefAttr->object() == theFeature) {
1281         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1282         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1283         break;
1284       }
1285     }
1286   }
1287 }
1288
1289 // ========================================================
1290 // =========      Auxiliary functions       ===============
1291 // ========================================================
1292
1293 template<typename T>
1294 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1295 {
1296   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1297   int aVecSize = theEntities.size();
1298   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1299     aResIndex--;
1300   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1301     aResIndex++;
1302   if (aResIndex == -1)
1303     aResIndex = aVecSize;
1304   return aResIndex;
1305 }