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