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