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