]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_Group.cpp
Salome HOME
Revert "First phase of SketchSolver refactoring"
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchSolver_Group.h"
8
9 #include <SketchSolver_Builder.h>
10 #include <SketchSolver_Constraint.h>
11 #include <SketchSolver_ConstraintCoincidence.h>
12 #include <SketchSolver_ConstraintMulti.h>
13 #include <SketchSolver_Error.h>
14
15 #include <Events_Error.h>
16 #include <Events_Loop.h>
17 #include <GeomAPI_XY.h>
18 #include <GeomAPI_Dir2d.h>
19 #include <GeomAPI_Pnt2d.h>
20 #include <GeomDataAPI_Dir.h>
21 #include <GeomDataAPI_Point.h>
22 #include <GeomDataAPI_Point2D.h>
23 #include <ModelAPI_AttributeDouble.h>
24 #include <ModelAPI_AttributeString.h>
25 #include <ModelAPI_Document.h>
26 #include <ModelAPI_Events.h>
27 #include <ModelAPI_ResultConstruction.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_Validator.h>
30
31 #include <SketchPlugin_Constraint.h>
32 #include <SketchPlugin_ConstraintAngle.h>
33 #include <SketchPlugin_ConstraintCoincidence.h>
34 #include <SketchPlugin_ConstraintDistance.h>
35 #include <SketchPlugin_ConstraintEqual.h>
36 #include <SketchPlugin_ConstraintHorizontal.h>
37 #include <SketchPlugin_ConstraintLength.h>
38 #include <SketchPlugin_ConstraintFillet.h>
39 #include <SketchPlugin_ConstraintMirror.h>
40 #include <SketchPlugin_ConstraintParallel.h>
41 #include <SketchPlugin_ConstraintPerpendicular.h>
42 #include <SketchPlugin_ConstraintRadius.h>
43 #include <SketchPlugin_ConstraintRigid.h>
44 #include <SketchPlugin_ConstraintTangent.h>
45 #include <SketchPlugin_ConstraintVertical.h>
46 #include <SketchPlugin_Feature.h>
47 #include <SketchPlugin_MultiRotation.h>
48 #include <SketchPlugin_MultiTranslation.h>
49 #include <SketchPlugin_Sketch.h>
50
51 #include <SketchPlugin_Arc.h>
52 #include <SketchPlugin_Circle.h>
53 #include <SketchPlugin_Line.h>
54 #include <SketchPlugin_Point.h>
55 #include <SketchPlugin_Sketch.h>
56
57 #include <math.h>
58 #include <assert.h>
59
60
61 /// \brief This class is used to give unique index to the groups
62 class GroupIndexer
63 {
64 public:
65   /// \brief Return vacant index
66   static Slvs_hGroup NEW_GROUP() { return ++myGroupIndex; }
67   /// \brief Removes the index
68   static void REMOVE_GROUP(const Slvs_hGroup& theIndex) {
69     if (myGroupIndex == theIndex)
70       myGroupIndex--;
71   }
72
73 private:
74   GroupIndexer() {};
75
76   static Slvs_hGroup myGroupIndex; ///< index of the group
77 };
78
79 Slvs_hGroup GroupIndexer::myGroupIndex = SLVS_G_OUTOFGROUP;
80
81
82 static void sendMessage(const char* theMessageName)
83 {
84   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
85       new Events_Message(Events_Loop::eventByName(theMessageName)));
86   Events_Loop::loop()->send(aMessage);
87 }
88
89
90
91 // ========================================================
92 // =========  SketchSolver_Group  ===============
93 // ========================================================
94
95 SketchSolver_Group::SketchSolver_Group(
96     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
97     : myID(GroupIndexer::NEW_GROUP()),
98       myPrevSolved(true)
99 {
100   // Initialize workplane
101   myWorkplaneID = SLVS_E_UNKNOWN;
102 #ifndef NDEBUG
103   assert(addWorkplane(theWorkplane));
104 #else
105   addWorkplane(theWorkplane);
106 #endif
107 }
108
109 SketchSolver_Group::~SketchSolver_Group()
110 {
111   myConstraints.clear();
112   GroupIndexer::REMOVE_GROUP(myID);
113 }
114
115 // ============================================================================
116 //  Function: isBaseWorkplane
117 //  Class:    SketchSolver_Group
118 //  Purpose:  verify the group is based on the given workplane
119 // ============================================================================
120 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
121 {
122   return theWorkplane == mySketch;
123 }
124
125 // ============================================================================
126 //  Function: isInteract
127 //  Class:    SketchSolver_Group
128 //  Purpose:  verify are there any entities in the group used by given constraint
129 // ============================================================================
130 bool SketchSolver_Group::isInteract(
131     std::shared_ptr<SketchPlugin_Feature> theFeature) const
132 {
133   // Empty group interacts with everything
134   if (isEmpty()) return true;
135   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
136   if (aConstraint)
137     return myFeatureStorage->isInteract(aConstraint);
138   return myFeatureStorage->isInteract(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
139 }
140
141 // check the entity is really exists
142 static void checkEntity(StoragePtr theStorage, Slvs_hEntity& theEntity)
143 {
144   if (theEntity == SLVS_E_UNKNOWN)
145     return;
146   Slvs_Entity anEnt = theStorage->getEntity(theEntity);
147   theEntity = anEnt.h;
148 }
149
150 // ============================================================================
151 //  Function: getFeatureId
152 //  Class:    SketchSolver_Group
153 //  Purpose:  Find the identifier of the feature, if it already exists in the group
154 // ============================================================================
155 Slvs_hEntity SketchSolver_Group::getFeatureId(FeaturePtr theFeature) const
156 {
157   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
158   if (!myFeatureStorage)
159     return aResult;
160   // Obtain regular constraints interacting with the feature and find its ID
161   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
162   for (; aCIter != myConstraints.end(); ++aCIter) {
163     aResult = aCIter->second->getId(theFeature);
164     checkEntity(myStorage, aResult);
165     if (aResult != SLVS_E_UNKNOWN)
166       return aResult;
167   }
168   // The feature is not found, check it in the temporary constraints
169   std::set<SolverConstraintPtr>::iterator aTmpCIter = myTempConstraints.begin();
170   for (; aTmpCIter != myTempConstraints.end() && aResult == SLVS_E_UNKNOWN; ++aTmpCIter) {
171     aResult = (*aTmpCIter)->getId(theFeature);
172     checkEntity(myStorage, aResult);
173   }
174   return aResult;
175 }
176
177 // ============================================================================
178 //  Function: getAttributeId
179 //  Class:    SketchSolver_Group
180 //  Purpose:  Find the identifier of the attribute, if it already exists in the group
181 // ============================================================================
182 Slvs_hEntity SketchSolver_Group::getAttributeId(AttributePtr theAttribute) const
183 {
184   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
185   if (!myFeatureStorage)
186     return aResult;
187   // Obtain regular constraints interacting with the attribute and find its ID
188   ConstraintConstraintMap::const_iterator aCIter = myConstraints.begin();
189   for (; aCIter != myConstraints.end(); ++aCIter) {
190     aResult = aCIter->second->getId(theAttribute);
191     checkEntity(myStorage, aResult);
192     if (aResult != SLVS_E_UNKNOWN)
193       return aResult;
194   }
195   // The attribute is not found, check it in the temporary constraints
196   std::set<SolverConstraintPtr>::const_iterator aTmpCIter = myTempConstraints.begin();
197   for (; aTmpCIter != myTempConstraints.end() && aResult == SLVS_E_UNKNOWN; ++aTmpCIter) {
198     aResult = (*aTmpCIter)->getId(theAttribute);
199     checkEntity(myStorage, aResult);
200   }
201   // Last chance to find attribute in parametric constraints
202   std::map<AttributePtr, SolverConstraintPtr>::const_iterator aParIter =
203       myParametricConstraints.find(theAttribute);
204   if (aParIter != myParametricConstraints.end()) {
205     aResult = aParIter->second->getId(theAttribute);
206     checkEntity(myStorage, aResult);
207   }
208   return aResult;
209 }
210
211 // ============================================================================
212 //  Function: changeConstraint
213 //  Class:    SketchSolver_Group
214 //  Purpose:  create/update the constraint in the group
215 // ============================================================================
216 bool SketchSolver_Group::changeConstraint(
217     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
218 {
219   // There is no workplane yet, something wrong
220   if (myWorkplaneID == SLVS_E_UNKNOWN)
221     return false;
222
223   if (!theConstraint || !theConstraint->data())
224     return false;
225
226   if (!checkFeatureValidity(theConstraint))
227     return false;
228
229   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
230   if (isNewConstraint) {
231     // Add constraint to the current group
232     SolverConstraintPtr aConstraint =
233         SketchSolver_Builder::getInstance()->createConstraint(theConstraint);
234     if (!aConstraint)
235       return false;
236     aConstraint->setGroup(this);
237     aConstraint->setStorage(myStorage);
238     if (!aConstraint->error().empty()) {
239       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
240         return false; // some attribute are not initialized yet, don't show message
241       Events_Error::send(aConstraint->error(), this);
242     }
243
244     // Additional verification of coincidence of several points
245     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
246       bool hasMultiCoincidence = false;
247       ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
248       for (; aCIter != myConstraints.end(); ++aCIter) {
249         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoincidence =
250           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aCIter->second);
251         if (!aCoincidence)
252           continue;
253         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoinc2 =
254           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
255         if (aCoincidence != aCoinc2 && aCoincidence->isCoincide(aCoinc2)) {
256           aCoinc2->attach(aCoincidence);
257           // update other coincidences
258           ConstraintConstraintMap::iterator anIt = aCIter;
259           for (++anIt; anIt != myConstraints.end(); ++anIt)
260             if (anIt->second == aCIter->second)
261               anIt->second = aCoinc2;
262           aCIter->second = aCoinc2;
263           hasMultiCoincidence = true;
264         }
265       }
266
267       if (hasMultiCoincidence)
268         notifyMultiConstraints();
269     }
270     myConstraints[theConstraint] = aConstraint;
271   }
272   else
273     myConstraints[theConstraint]->update();
274
275   // Fix base features for fillet
276   if (isNewConstraint && theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
277     std::list<AttributePtr> anAttrList =
278         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
279     std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
280     for (; anAttrIter != anAttrList.end(); anAttrIter++) {
281       AttributeRefAttrPtr aRefAttr =
282           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
283       if (!aRefAttr || !aRefAttr->isObject())
284         continue;
285       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
286       SolverConstraintPtr aConstraint =
287           SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
288       if (!aConstraint)
289         continue;
290       aConstraint->setGroup(this);
291       aConstraint->setStorage(myStorage);
292       setTemporary(aConstraint);
293     }
294   }
295   // Fix mirror line
296   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
297     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
298         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
299     if (aRefAttr && aRefAttr->isObject()) {
300       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
301       if (aFeature) {
302         SolverConstraintPtr aConstraint =
303             SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
304         if (aConstraint) {
305           aConstraint->setGroup(this);
306           aConstraint->setStorage(myStorage);
307           setTemporary(aConstraint);
308         }
309       }
310     }
311   }
312
313   if (!myFeatureStorage)
314     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
315   myFeatureStorage->changeConstraint(theConstraint);
316
317   // Check the attributes of constraint are given by parametric expression
318   std::list<AttributePtr> anAttributes =
319       theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
320   std::list<AttributePtr>::iterator anAttrIt = anAttributes.begin();
321   for (; anAttrIt != anAttributes.end(); ++anAttrIt) {
322     AttributeRefAttrPtr aRefAttr =
323         std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIt);
324     if (!aRefAttr)
325       continue;
326
327     std::shared_ptr<GeomDataAPI_Point2D> aPoint;
328     if (aRefAttr->isObject()) {
329       FeaturePtr aFeat = ModelAPI_Feature::feature(aRefAttr->object());
330       if (aFeat->getKind() != SketchPlugin_Point::ID())
331         continue;
332       aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
333           aFeat->attribute(SketchPlugin_Point::COORD_ID()));
334     } else
335       aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aRefAttr->attr());
336
337     if (!aPoint || (aPoint->textX().empty() && aPoint->textY().empty()))
338       continue;
339
340     std::map<AttributePtr, SolverConstraintPtr>::iterator aFound =
341         myParametricConstraints.find(aPoint);
342     if (aFound == myParametricConstraints.end()) {
343       SolverConstraintPtr aConstraint =
344           SketchSolver_Builder::getInstance()->createParametricConstraint(aPoint);
345       if (!aConstraint)
346         continue;
347       aConstraint->setGroup(this);
348       aConstraint->setStorage(myStorage);
349       myParametricConstraints[aPoint] = aConstraint;
350     } else
351       aFound->second->update();
352   }
353
354   return true;
355 }
356
357
358 void SketchSolver_Group::updateConstraints()
359 {
360   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
361
362   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
363   for (; anIt != myConstraints.end(); ++anIt) {
364     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
365       continue;
366     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
367         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
368       aPostponed.insert(anIt->second);
369     else
370       anIt->second->update();
371   }
372
373   // Update postponed constraints
374   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
375   for (; aSCIter != aPostponed.end(); ++aSCIter)
376     (*aSCIter)->update();
377
378   myChangedConstraints.clear();
379 }
380
381 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
382 {
383   if (!checkFeatureValidity(theFeature))
384     return false;
385
386   std::set<ConstraintPtr> aConstraints =
387       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
388   if (aConstraints.empty())
389     return false;
390   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
391   for (; aCIter != aConstraints.end(); aCIter++) {
392     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
393     if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
394         !aSolConIter->first->data()->isValid())
395       continue;
396     myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
397
398     aSolConIter->second->addFeature(theFeature);
399     myChangedConstraints.insert(aSolConIter->first);
400   }
401
402   // Search attributes of the feature in the set of parametric constraints and update them
403   std::list<AttributePtr> anAttrList =
404       theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
405   std::list<AttributePtr>::iterator anAttrIt = anAttrList.begin();
406   for (; anAttrIt != anAttrList.end(); ++anAttrIt) {
407     std::map<AttributePtr, SolverConstraintPtr>::iterator aFound =
408         myParametricConstraints.find(*anAttrIt);
409     if (aFound != myParametricConstraints.end())
410       aFound->second->update();
411     else {
412       std::shared_ptr<GeomDataAPI_Point2D> aPoint =
413           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anAttrIt);
414       if (aPoint && (!aPoint->textX().empty() || !aPoint->textY().empty())) {
415         // Create new parametric constraint
416         SolverConstraintPtr aConstraint =
417             SketchSolver_Builder::getInstance()->createParametricConstraint(*anAttrIt);
418         if (!aConstraint)
419           continue;
420         aConstraint->setGroup(this);
421         aConstraint->setStorage(myStorage);
422         myParametricConstraints[*anAttrIt] = aConstraint;
423       }
424     }
425   }
426   return true;
427 }
428
429 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
430 {
431   // Firstly, create temporary rigid constraint
432   SolverConstraintPtr aConstraint =
433       SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
434   if (!aConstraint)
435     return;
436   aConstraint->setGroup(this);
437   aConstraint->setStorage(myStorage);
438   if (aConstraint->error().empty())
439     setTemporary(aConstraint);
440   // Secondly, update the feature
441   updateFeature(theFeature);
442 }
443
444 // ============================================================================
445 //  Function: fixFeaturesList
446 //  Class:    SketchSolver_Group
447 //  Purpose:  Apply temporary rigid constraints for the list of features
448 // ============================================================================
449 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
450 {
451   std::list<ObjectPtr> aList = theList->list();
452   std::list<ObjectPtr>::iterator anIt = aList.begin();
453   std::list<FeaturePtr> aFeatures;
454   // Sort features, at begining there are features used by Equal constraint
455   for (; anIt != aList.end(); anIt++) {
456     if (!(*anIt))
457       continue;
458     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
459     std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
460     std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
461     for (; aCIter != aConstraints.end(); aCIter++)
462       if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
463         break;
464     if (aCIter != aConstraints.end())
465       aFeatures.push_front(aFeature);
466     else
467       aFeatures.push_back(aFeature);
468   }
469
470   std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
471   for (; aFeatIter != aFeatures.end(); aFeatIter++) {
472     SolverConstraintPtr aConstraint =
473         SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
474     if (!aConstraint)
475       continue;
476     aConstraint->setGroup(this);
477     aConstraint->setStorage(myStorage);
478     setTemporary(aConstraint);
479   }
480 }
481
482 // ============================================================================
483 //  Function: addWorkplane
484 //  Class:    SketchSolver_Group
485 //  Purpose:  create workplane for the group
486 // ============================================================================
487 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
488 {
489   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
490     return false;  // the workplane already exists or the function parameter is not Sketch
491
492   mySketch = theSketch;
493   updateWorkplane();
494   return true;
495 }
496
497 // ============================================================================
498 //  Function: updateWorkplane
499 //  Class:    SketchSolver_Group
500 //  Purpose:  update parameters of workplane
501 // ============================================================================
502 bool SketchSolver_Group::updateWorkplane()
503 {
504   if (!myStorage) // Create storage if not exists
505     myStorage = StoragePtr(new SketchSolver_Storage);
506   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
507
508   std::vector<Slvs_Entity> anEntities;
509   std::vector<Slvs_Param> aParams;
510   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
511     return false;
512
513   if (myWorkplaneID == SLVS_E_UNKNOWN) {
514     myWorkplaneID = anEntities.back().h;
515     // Add new workplane elements
516     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
517     for (; aParIter != aParams.end(); aParIter++) {
518       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
519       aParIter->group = SLVS_G_OUTOFGROUP;
520       aParIter->h = myStorage->addParameter(*aParIter);
521     }
522     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
523     for (; anEntIter != anEntities.end(); anEntIter++) {
524       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
525       anEntIter->group = SLVS_G_OUTOFGROUP;
526       anEntIter->wrkpl = myWorkplaneID;
527       for (int i = 0; i < 4; i++)
528         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
529           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
530       for (int i = 0; i < 4; i++)
531         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
532           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
533       anEntIter->h = myStorage->addEntity(*anEntIter);
534     }
535   } else {
536     // Update existent workplane
537     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
538     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
539     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
540     // Get parameters and update them
541     Slvs_hParam aWPParams[7] = {
542         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
543         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
544       };
545     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
546     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
547       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
548       aParam.val = aParIter->val;
549       myStorage->updateParameter(aParam);
550     }
551   }
552   return myWorkplaneID > 0;
553 }
554
555 // ============================================================================
556 //  Function: resolveConstraints
557 //  Class:    SketchSolver_Group
558 //  Purpose:  solve the set of constraints for the current group
559 // ============================================================================
560 bool SketchSolver_Group::resolveConstraints()
561 {
562   if (!myChangedConstraints.empty())
563     updateConstraints();
564
565   bool aResolved = false;
566   bool isGroupEmpty = isEmpty();
567   if (myStorage->isNeedToResolve() && !isGroupEmpty) {
568     myConstrSolver.setGroupID(myID);
569     myConstrSolver.calculateFailedConstraints(false);
570     myStorage->initializeSolver(myConstrSolver);
571
572     int aResult = SLVS_RESULT_OKAY;
573     try {
574       if (myStorage->hasDuplicatedConstraint())
575         aResult = SLVS_RESULT_INCONSISTENT;
576       else {
577         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
578         // and try to find the case without overconstraint
579         bool isLastChance = false;
580         int aNbTemp = myStorage->numberTemporary();
581         while (true) {
582           aResult = myConstrSolver.solve();
583           if (aResult == SLVS_RESULT_OKAY || isLastChance)
584             break;
585           if (aNbTemp <= 0) {
586             // try to update parameters and resolve once again
587             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
588             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
589               aConstrIt->second->update();
590             isLastChance = true;
591           } else
592             aNbTemp = myStorage->deleteTemporaryConstraint();
593           myConstrSolver.calculateFailedConstraints(true); // something failed => need to find it
594           myStorage->initializeSolver(myConstrSolver);
595         }
596       }
597     } catch (...) {
598 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
599       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
600       if (myPrevSolved) {
601         // the error message should be changed before sending the message
602         sendMessage(EVENT_SOLVER_FAILED);
603         myPrevSolved = false;
604       }
605       return false;
606     }
607     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
608       myFeatureStorage->blockEvents(true);
609       // First refresh parametric constraints to satisfy parameters
610       std::map<AttributePtr, SolverConstraintPtr>::iterator aParIter = myParametricConstraints.begin();
611       for (; aParIter != myParametricConstraints.end(); ++aParIter)
612         aParIter->second->refresh();
613       // Update all other constraints
614       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
615       for (; aConstrIter != myConstraints.end(); ++aConstrIter)
616         aConstrIter->second->refresh();
617       myFeatureStorage->blockEvents(false);
618       if (!myPrevSolved) {
619         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
620         // the error message should be changed before sending the message
621         sendMessage(EVENT_SOLVER_REPAIRED);
622         myPrevSolved = true;
623       }
624     } else if (!myConstraints.empty()) {
625 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
626       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
627       if (myPrevSolved) {
628         // the error message should be changed before sending the message
629         sendMessage(EVENT_SOLVER_FAILED);
630         myPrevSolved = false;
631       }
632     }
633
634     aResolved = true;
635   } else if (!isGroupEmpty) {
636     myFeatureStorage->blockEvents(true);
637     // Check there are constraints Fixed. If they exist, update parameters by stored values
638     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
639     for (; aCIt != myConstraints.end(); ++aCIt)
640       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
641         aCIt->second->refresh();
642         aResolved = true;
643       }
644      myFeatureStorage->blockEvents(false);
645   }
646   removeTemporaryConstraints();
647   myStorage->setNeedToResolve(false);
648   return aResolved;
649 }
650
651 // ============================================================================
652 //  Function: mergeGroups
653 //  Class:    SketchSolver_Group
654 //  Purpose:  append specified group to the current group
655 // ============================================================================
656 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
657 {
658   // If specified group is empty, no need to merge
659   if (theGroup.isEmpty())
660     return;
661   if (!myFeatureStorage)
662     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
663
664   std::set<ObjectPtr> aConstraints;
665   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
666   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
667     aConstraints.insert(aConstrIter->first);
668
669   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
670   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
671   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
672     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
673     if (!aConstr)
674       continue;
675     changeConstraint(aConstr);
676   }
677 }
678
679 // ============================================================================
680 //  Function: splitGroup
681 //  Class:    SketchSolver_Group
682 //  Purpose:  divide the group into several subgroups
683 // ============================================================================
684 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
685 {
686   // Obtain constraints, which should be separated
687   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
688   std::vector<ConstraintPtr> anUnusedConstraints;
689   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
690   for ( ; aCIter != myConstraints.end(); aCIter++) {
691     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
692     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
693     for (; anIter != aBaseConstraints.end(); anIter++)
694       if (aNewFeatStorage->isInteract(*anIter)) {
695         aNewFeatStorage->changeConstraint(*anIter);
696       } else
697         anUnusedConstraints.push_back(*anIter);
698   }
699
700   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
701   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
702   while (aUnuseIt != anUnusedConstraints.end()) {
703     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
704       aNewFeatStorage->changeConstraint(*aUnuseIt);
705       anUnusedConstraints.erase(aUnuseIt);
706       aUnuseIt = anUnusedConstraints.begin();
707       continue;
708     }
709     aUnuseIt++;
710   }
711
712   std::vector<SketchSolver_Group*>::iterator aCutsIter;
713   aUnuseIt = anUnusedConstraints.begin();
714   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
715     // Remove unused constraints
716     removeConstraint(*aUnuseIt);
717     // Try to append constraint to already existent group
718     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
719       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
720         (*aCutsIter)->changeConstraint(*aUnuseIt);
721         break;
722       }
723     if (aCutsIter == theCuts.end()) {
724       // Add new group
725       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
726       aGroup->changeConstraint(*aUnuseIt);
727       theCuts.push_back(aGroup);
728     }
729   }
730
731   // Update feature storage
732   myFeatureStorage = aNewFeatStorage;
733 }
734
735 // ============================================================================
736 //  Function: isConsistent
737 //  Class:    SketchSolver_Group
738 //  Purpose:  search removed entities and constraints
739 // ============================================================================
740 bool SketchSolver_Group::isConsistent()
741 {
742   if (!myFeatureStorage) // no one constraint is initialized yet
743     return true;
744
745   bool aResult = myFeatureStorage->isConsistent();
746   if (!aResult) {
747     // remove invalid entities
748     std::set<ConstraintPtr> anInvalidConstraints;
749     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
750     for (; aCIter != myConstraints.end(); ++aCIter) {
751       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
752         anInvalidConstraints.insert(aCIter->first);
753     }
754     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
755     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
756       removeConstraint(*aRemoveIt);
757   }
758   return aResult;
759 }
760
761 // ============================================================================
762 //  Function: removeTemporaryConstraints
763 //  Class:    SketchSolver_Group
764 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
765 //            resolving the set of constraints
766 // ============================================================================
767 void SketchSolver_Group::removeTemporaryConstraints()
768 {
769   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
770   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
771     (*aTmpIt)->remove();
772   myTempConstraints.clear();
773
774   while (myStorage->numberTemporary())
775     myStorage->deleteTemporaryConstraint();
776   // Clean lists of removed entities in the storage
777   std::set<Slvs_hParam> aRemPar;
778   std::set<Slvs_hEntity> aRemEnt;
779   std::set<Slvs_hConstraint> aRemCon;
780   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
781   myStorage->setNeedToResolve(false);
782 }
783
784 // ============================================================================
785 //  Function: removeConstraint
786 //  Class:    SketchSolver_Group
787 //  Purpose:  remove constraint and all unused entities
788 // ============================================================================
789 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
790 {
791   bool isFullyRemoved = true;
792   myFeatureStorage->removeConstraint(theConstraint);
793   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
794   for (; aCIter != myConstraints.end(); aCIter++)
795     if (aCIter->second->hasConstraint(theConstraint)) {
796       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
797         isFullyRemoved = false;
798       break;
799     }
800   if (aCIter == myConstraints.end())
801     return;
802
803   // Remove entities not used by constraints
804   myStorage->removeUnusedEntities();
805
806   if (isFullyRemoved)
807     myConstraints.erase(aCIter);
808   else if (aCIter != myConstraints.end() &&
809            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
810     // Update multicoincidence
811     std::list<ConstraintPtr> aMultiCoinc;
812     SolverConstraintPtr aCoincidence = aCIter->second;
813     while (aCIter != myConstraints.end()) {
814       if (aCIter->second != aCoincidence) {
815         ++aCIter;
816         continue;
817       }
818       if (aCIter->first != theConstraint)
819         aMultiCoinc.push_back(aCIter->first);
820       aCIter->second->remove(aCIter->first);
821       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
822       myConstraints.erase(aRemoveIt);
823     }
824
825     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
826     for (; anIt != aMultiCoinc.end(); ++anIt)
827       changeConstraint(*anIt);
828
829     notifyMultiConstraints();
830   }
831 }
832
833 // ============================================================================
834 //  Function: isComplexConstraint
835 //  Class:    SketchSolver_Group
836 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
837 // ============================================================================
838 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
839 {
840   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
841          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
842          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
843 }
844
845 // ============================================================================
846 //  Function: setTemporary
847 //  Class:    SketchSolver_Group
848 //  Purpose:  append given constraint to th group of temporary constraints
849 // ============================================================================
850 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
851 {
852   theConstraint->makeTemporary();
853   myTempConstraints.insert(theConstraint);
854 }
855
856
857 // ============================================================================
858 //  Function: checkFeatureValidity
859 //  Class:    SketchSolver_Group
860 //  Purpose:  verifies is the feature valid
861 // ============================================================================
862 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
863 {
864   if (!theFeature || !theFeature->data()->isValid())
865     return true;
866
867   SessionPtr aMgr = ModelAPI_Session::get();
868   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
869   return aFactory->validate(theFeature);
870 }
871
872 // ============================================================================
873 //  Function: notifyMultiConstraints
874 //  Class:    SketchSolver_Group
875 //  Purpose:  Update Multi-Translation/-Rotation constraints due to multi coincidence appears/disappears
876 // ============================================================================
877 void SketchSolver_Group::notifyMultiConstraints()
878 {
879   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
880   for (; aCIter != myConstraints.end(); ++aCIter) {
881     if (aCIter->first->getKind() == SketchPlugin_MultiRotation::ID() ||
882         aCIter->first->getKind() == SketchPlugin_MultiTranslation::ID()) {
883       std::shared_ptr<SketchSolver_ConstraintMulti> aMulti = 
884           std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIter->second);
885       aMulti->checkCoincidence();
886     }
887   }
888 }
889
890
891
892
893 // ===========   Auxiliary functions   ========================================
894 static double featureToVal(FeaturePtr theFeature)
895 {
896   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
897     return 0.0; // sketch
898   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
899   if (!aConstraint)
900     return 1.0; // features (arc, circle, line, point)
901
902   const std::string& anID = aConstraint->getKind();
903   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
904     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
905         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
906     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
907         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
908     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
909       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
910     return 2.5;
911   }
912   if (anID == SketchPlugin_ConstraintDistance::ID() ||
913       anID == SketchPlugin_ConstraintLength::ID() ||
914       anID == SketchPlugin_ConstraintRadius::ID())
915     return 3.0;
916   if (anID == SketchPlugin_ConstraintAngle::ID())
917     return 3.5;
918   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
919       anID == SketchPlugin_ConstraintVertical::ID() ||
920       anID == SketchPlugin_ConstraintParallel::ID() ||
921       anID == SketchPlugin_ConstraintPerpendicular::ID())
922     return 4.0;
923   if (anID == SketchPlugin_ConstraintEqual::ID())
924     return 5.0;
925   if (anID == SketchPlugin_ConstraintTangent::ID() ||
926       anID == SketchPlugin_ConstraintMirror::ID())
927     return 6.0;
928   if (anID == SketchPlugin_ConstraintRigid::ID())
929     return 7.0;
930   if (anID == SketchPlugin_MultiRotation::ID() ||
931       anID == SketchPlugin_MultiTranslation::ID())
932     return 8.0;
933
934   // all other constraints are placed between Equal and Tangent constraints
935   return 5.5;
936 }
937
938 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
939 {
940   return featureToVal(theFeature1) < featureToVal(theFeature2);
941 }
942
943 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
944 {
945   std::list<FeaturePtr> aResult;
946   std::list<FeaturePtr>::iterator aResIt;
947
948   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
949   for (; anObjIter != theObjects.end(); ++anObjIter) {
950     // Operate sketch itself and SketchPlugin features only.
951     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
952     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
953     if (!aFeature)
954       continue;
955     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
956         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
957     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
958         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
959       continue;
960
961     // Find the place where to insert a feature
962     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
963       if (isLess(aFeature, *aResIt))
964         break;
965     aResult.insert(aResIt, aFeature);
966   }
967
968   return aResult;
969 }
970