Salome HOME
Merge branch 'BR_internationalization'
[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_Constraint.h>
10 #include <SketchSolver_ConstraintCoincidence.h>
11 #include <SketchSolver_ConstraintMulti.h>
12 #include <SketchSolver_Error.h>
13 #include <SketchSolver_Manager.h>
14
15 #include <Events_InfoMessage.h>
16 #include <Events_Loop.h>
17 #include <ModelAPI_AttributeString.h>
18 #include <ModelAPI_Events.h>
19 #include <ModelAPI_Session.h>
20 #include <ModelAPI_Validator.h>
21
22 #include <SketchPlugin_Arc.h>
23 #include <SketchPlugin_ConstraintAngle.h>
24 #include <SketchPlugin_ConstraintCoincidence.h>
25 #include <SketchPlugin_ConstraintDistance.h>
26 #include <SketchPlugin_ConstraintEqual.h>
27 #include <SketchPlugin_ConstraintHorizontal.h>
28 #include <SketchPlugin_ConstraintLength.h>
29 #include <SketchPlugin_ConstraintFillet.h>
30 #include <SketchPlugin_ConstraintMirror.h>
31 #include <SketchPlugin_ConstraintParallel.h>
32 #include <SketchPlugin_ConstraintPerpendicular.h>
33 #include <SketchPlugin_ConstraintRadius.h>
34 #include <SketchPlugin_ConstraintRigid.h>
35 #include <SketchPlugin_ConstraintTangent.h>
36 #include <SketchPlugin_ConstraintVertical.h>
37 #include <SketchPlugin_MultiRotation.h>
38 #include <SketchPlugin_MultiTranslation.h>
39
40 #include <math.h>
41 #include <assert.h>
42
43
44 /// \brief This class is used to give unique index to the groups
45 class GroupIndexer
46 {
47 public:
48   /// \brief Return vacant index
49   static GroupID NEW_GROUP() { return ++myGroupIndex; }
50   /// \brief Removes the index
51   static void REMOVE_GROUP(const GroupID& theIndex) {
52     if (myGroupIndex == theIndex)
53       myGroupIndex--;
54   }
55
56 private:
57   GroupIndexer() {};
58
59   static GroupID myGroupIndex; ///< index of the group
60 };
61
62 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
63
64
65 static void sendMessage(const char* theMessageName)
66 {
67   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
68       new Events_Message(Events_Loop::eventByName(theMessageName)));
69   Events_Loop::loop()->send(aMessage);
70 }
71
72 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
73 {
74   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
75       std::shared_ptr<ModelAPI_SolverFailedMessage>(
76       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
77   aMessage->setObjects(theConflicting);
78   Events_Loop::loop()->send(aMessage);
79 }
80
81
82
83 // ========================================================
84 // =========  SketchSolver_Group  ===============
85 // ========================================================
86
87 SketchSolver_Group::SketchSolver_Group(
88     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
89     : myID(GroupIndexer::NEW_GROUP()),
90       myPrevResult(STATUS_UNKNOWN)
91 {
92   // Initialize workplane
93   myWorkplaneID = EID_UNKNOWN;
94   addWorkplane(theWorkplane);
95 }
96
97 SketchSolver_Group::~SketchSolver_Group()
98 {
99   myConstraints.clear();
100   GroupIndexer::REMOVE_GROUP(myID);
101   // send the message that there is no more conflicting constraints
102   if (!myConflictingConstraints.empty()) {
103     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
104     myConflictingConstraints.clear();
105   }
106 }
107
108 // ============================================================================
109 //  Function: isBaseWorkplane
110 //  Class:    SketchSolver_Group
111 //  Purpose:  verify the group is based on the given workplane
112 // ============================================================================
113 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
114 {
115   return theWorkplane == mySketch;
116 }
117
118 // ============================================================================
119 //  Function: isInteract
120 //  Class:    SketchSolver_Group
121 //  Purpose:  verify are there any entities in the group used by given constraint
122 // ============================================================================
123 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
124 {
125   // Empty group interacts with everything
126   if (isEmpty())
127     return true;
128   // Check interaction with the storage
129   bool isInteracted = myStorage->isInteract(theFeature);
130   ConstraintConstraintMap::const_iterator anIt = myConstraints.begin();
131   for (; !isInteracted && anIt != myConstraints.end(); ++anIt)
132     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
133         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
134       isInteracted = anIt->second->isUsed(theFeature);
135   return isInteracted;
136 }
137
138 // ============================================================================
139 //  Function: changeConstraint
140 //  Class:    SketchSolver_Group
141 //  Purpose:  create/update the constraint in the group
142 // ============================================================================
143 bool SketchSolver_Group::changeConstraint(
144     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
145 {
146   // There is no workplane yet, something wrong
147   if (myWorkplaneID == EID_UNKNOWN)
148     return false;
149
150   if (!theConstraint || !theConstraint->data())
151     return false;
152
153   if (!checkFeatureValidity(theConstraint))
154     return false;
155
156   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
157   myStorage->blockEvents(true);
158
159   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
160   if (isNewConstraint) {
161     // Add constraint to the current group
162     SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
163     if (!aConstraint)
164       return false;
165     aConstraint->process(myStorage, getId(), getWorkplaneId());
166     if (!aConstraint->error().empty()) {
167       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
168         return false; // some attribute are not initialized yet, don't show message
169       Events_InfoMessage("SketchSolver_Group", aConstraint->error(), this).send();
170     }
171     myConstraints[theConstraint] = aConstraint;
172
173     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID())
174       notifyCoincidenceChanged(myConstraints[theConstraint]);
175   }
176   else
177     myConstraints[theConstraint]->update();
178
179   // Fix mirror line
180   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
181     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
182         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
183     if (aRefAttr && aRefAttr->isObject()) {
184       std::shared_ptr<SketchPlugin_Feature> aFeature =
185           std::dynamic_pointer_cast<SketchPlugin_Feature>(
186           ModelAPI_Feature::feature(aRefAttr->object()));
187       if (aFeature) {
188         SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
189         if (aConstraint) {
190           aConstraint->process(myStorage, getId(), getWorkplaneId());
191           setTemporary(aConstraint);
192         }
193       }
194     }
195   }
196   return true;
197 }
198
199 // Update constraints if they contain specific feature
200 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
201 {
202   ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
203   for (; aCIt != theConstraints.end(); ++aCIt) {
204     SketchSolver_ConstraintType aType = aCIt->second->getType();
205     if ((aType == CONSTRAINT_MULTI_ROTATION ||
206          aType == CONSTRAINT_MULTI_TRANSLATION)
207         && aCIt->second->isUsed(theFeature))
208       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
209     else if ((aType == CONSTRAINT_TANGENT_CIRCLE_LINE ||
210               aType == CONSTRAINT_SYMMETRIC || aType == CONSTRAINT_ANGLE)
211              && aCIt->second->isUsed(theFeature))
212       aCIt->second->update();
213   }
214 }
215
216 // Recalculate slave features of the Multi constraints
217 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints)
218 {
219   ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
220   for (; aCIt != theConstraints.end(); ++aCIt) {
221     SketchSolver_ConstraintType aType = aCIt->second->getType();
222     if ((aType == CONSTRAINT_MULTI_ROTATION ||
223          aType == CONSTRAINT_MULTI_TRANSLATION))
224       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
225   }
226 }
227
228 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
229 {
230   if (!checkFeatureValidity(theFeature))
231     return false;
232
233   bool isBlocked = myStorage->isEventsBlocked();
234   if (!isBlocked)
235     myStorage->blockEvents(true);
236
237   myStorage->refresh(true);
238   bool isUpdated = myStorage->update(theFeature);
239
240   updateMultiConstraints(myConstraints, theFeature);
241
242   // events were not blocked before, the feature has not been updated,
243   // so it is necessary to revert blocking
244   if (!isUpdated && !isBlocked)
245     myStorage->blockEvents(false);
246   return isUpdated;
247 }
248
249 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
250 {
251   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
252
253   // Firstly, revert changes in the fixed entities
254   myStorage->blockEvents(true);
255   myStorage->refresh(true);
256
257   // Then, create temporary Fixed constraint
258   SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
259   if (!aConstraint)
260     return;
261   aConstraint->process(myStorage, getId(), getWorkplaneId());
262   if (aConstraint->error().empty())
263     setTemporary(aConstraint);
264
265   // Secondly, search attributes of the feature in the list of the Multi constraints and update them
266   updateMultiConstraints(myConstraints, theFeature);
267
268   // Workaround to process arcs.
269   // When move unconstrained arc, add temporary constraint to fix radius.
270   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
271     bool hasDup = myStorage->hasDuplicatedConstraint();
272     SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
273     if (aFixedRadius) {
274       aFixedRadius->process(myStorage, getId(), getWorkplaneId());
275       hasDup = myStorage->hasDuplicatedConstraint() && !hasDup;
276       if (aFixedRadius->error().empty() && !hasDup)
277         setTemporary(aFixedRadius);
278       else
279         aFixedRadius->remove();
280     }
281   }
282 }
283
284 // ============================================================================
285 //  Function: addWorkplane
286 //  Class:    SketchSolver_Group
287 //  Purpose:  create workplane for the group
288 // ============================================================================
289 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
290 {
291   if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
292     return false;  // the workplane already exists or the function parameter is not Sketch
293
294   mySketch = theSketch;
295   if (!updateWorkplane()) {
296     mySketch = CompositeFeaturePtr();
297     return false;
298   }
299   return true;
300 }
301
302 // ============================================================================
303 //  Function: updateWorkplane
304 //  Class:    SketchSolver_Group
305 //  Purpose:  update parameters of workplane
306 // ============================================================================
307 bool SketchSolver_Group::updateWorkplane()
308 {
309   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
310   if (!myStorage) // Create storage if not exists
311     myStorage = aBuilder->createStorage(getId());
312
313   // sketch should be unchanged, set it out of current group
314   bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
315   if (isUpdated) {
316     EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
317     myWorkplaneID = anEntity->id();
318   }
319   return isUpdated;
320 }
321
322 // ============================================================================
323 //  Function: resolveConstraints
324 //  Class:    SketchSolver_Group
325 //  Purpose:  solve the set of constraints for the current group
326 // ============================================================================
327 bool SketchSolver_Group::resolveConstraints()
328 {
329   bool aResolved = false;
330   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
331   if (myStorage->isNeedToResolve() &&
332       (!isGroupEmpty || !myConflictingConstraints.empty() || myPrevResult == STATUS_FAILED)) {
333     if (!mySketchSolver)
334       mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
335
336     mySketchSolver->setGroup(myID);
337     mySketchSolver->calculateFailedConstraints(false);
338     myStorage->initializeSolver(mySketchSolver);
339     mySketchSolver->prepare();
340
341     SketchSolver_SolveStatus aResult = STATUS_OK;
342     try {
343       if (myStorage->hasDuplicatedConstraint())
344         aResult = STATUS_INCONSISTENT;
345       else if (!isGroupEmpty) {
346         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
347         // and try to find the case without overconstraint
348         bool isLastChance = false;
349         while (true) {
350           aResult = mySketchSolver->solve();
351           if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
352             break;
353 ////          // try to update parameters and resolve once again
354 ////          ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
355 ////          for (; aConstrIt != myConstraints.end(); ++aConstrIt)
356 ////            aConstrIt->second->update();
357           isLastChance = true;
358
359           removeTemporaryConstraints();
360           mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
361           myStorage->initializeSolver(mySketchSolver);
362         }
363       }
364     } catch (...) {
365 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
366       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
367       if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
368         // the error message should be changed before sending the message
369         sendMessage(EVENT_SOLVER_FAILED);
370         myPrevResult = STATUS_FAILED;
371       }
372       mySketchSolver->undo();
373       return false;
374     }
375     if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
376       myStorage->refresh();
377       updateMultiConstraints(myConstraints);
378       if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
379         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
380         std::set<ObjectPtr> aConflicting = myConflictingConstraints;
381         myConflictingConstraints.clear();
382         myPrevResult = STATUS_OK;
383         // the error message should be changed before sending the message
384         sendMessage(EVENT_SOLVER_REPAIRED, aConflicting);
385       }
386     } else {
387       mySketchSolver->undo();
388       if (!myConstraints.empty()) {
389         // the error message should be changed before sending the message
390         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
391         if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
392           // Obtain list of conflicting constraints
393           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
394
395           if (myConflictingConstraints.empty())
396             sendMessage(EVENT_SOLVER_FAILED, aConflicting);
397           else {
398             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
399             for (; anIt != aConflicting.end(); ++anIt)
400               myConflictingConstraints.erase(*anIt);
401             if (!myConflictingConstraints.empty()) {
402               // some constraints does not conflict, send corresponding message
403               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
404             }
405           }
406           myConflictingConstraints = aConflicting;
407           myPrevResult = aResult;
408         }
409       }
410     }
411
412     aResolved = true;
413   } else if (!isGroupEmpty) {
414     // Check there are constraints Fixed. If they exist, update parameters by stored values
415     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
416     for (; aCIt != myConstraints.end(); ++aCIt)
417       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
418         aResolved = true;
419         break;
420       }
421     if (aCIt != myConstraints.end())
422       myStorage->refresh();
423   }
424   removeTemporaryConstraints();
425   myStorage->blockEvents(false);
426   myStorage->setNeedToResolve(false);
427   return aResolved;
428 }
429
430 // ============================================================================
431 //  Function: mergeGroups
432 //  Class:    SketchSolver_Group
433 //  Purpose:  append specified group to the current group
434 // ============================================================================
435 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
436 {
437   // If specified group is empty, no need to merge
438   if (theGroup.isEmpty())
439     return;
440
441   std::set<ObjectPtr> aConstraints;
442   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
443   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
444     aConstraints.insert(aConstrIter->first);
445
446   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
447   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
448   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
449     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
450     if (!aConstr)
451       continue;
452     changeConstraint(aConstr);
453   }
454 }
455
456 // ============================================================================
457 //  Function: splitGroup
458 //  Class:    SketchSolver_Group
459 //  Purpose:  divide the group into several subgroups
460 // ============================================================================
461 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
462 {
463   // New storage will be used in trimmed way to store the list of constraint interacted together.
464   StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
465   std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
466
467   // Obtain constraints, which should be separated
468   std::list<ConstraintPtr> anUnusedConstraints;
469   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
470   for ( ; aCIter != myConstraints.end(); aCIter++) {
471     if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
472       aNewStorage->addConstraint(aCIter->first, aDummyVec);
473     else
474       anUnusedConstraints.push_back(aCIter->first);
475   }
476
477   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
478   std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
479   while (aUnuseIt != anUnusedConstraints.end()) {
480     if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
481       aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
482       anUnusedConstraints.erase(aUnuseIt);
483       aUnuseIt = anUnusedConstraints.begin();
484       continue;
485     }
486     aUnuseIt++;
487   }
488
489   std::list<SketchSolver_Group*>::iterator aCutsIter;
490   // Remove unused constraints
491   for (aUnuseIt = anUnusedConstraints.begin(); aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt)
492     removeConstraint(*aUnuseIt);
493
494   SketchSolver_Group* aBaseGroup;
495   for (aUnuseIt = anUnusedConstraints.begin(); aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
496     aBaseGroup = 0;
497     aCutsIter = theCuts.begin();
498     // Try to append constraint to the current group
499     if (isInteract(*aUnuseIt)) {
500       changeConstraint(*aUnuseIt);
501       aBaseGroup = this;
502     } else {
503       // Try to append constraint to already existent group
504       for (; aCutsIter != theCuts.end(); ++aCutsIter)
505         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
506           (*aCutsIter)->changeConstraint(*aUnuseIt);
507           break;
508         }
509     }
510
511     if (aCutsIter == theCuts.end() && !aBaseGroup) {
512       // Add new group
513       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
514       aGroup->changeConstraint(*aUnuseIt);
515       theCuts.push_back(aGroup);
516     } else {
517       if (!aBaseGroup)
518         aBaseGroup = *aCutsIter++;
519       // Find other groups interacting with constraint
520       for (; aCutsIter != theCuts.end(); ++aCutsIter)
521         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
522           aBaseGroup->mergeGroups(**aCutsIter);
523           std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
524           theCuts.erase(aRemoveIt);
525         }
526     }
527   }
528 }
529
530 // ============================================================================
531 //  Function: isConsistent
532 //  Class:    SketchSolver_Group
533 //  Purpose:  search removed entities and constraints
534 // ============================================================================
535 bool SketchSolver_Group::isConsistent()
536 {
537   if (isEmpty()) // no one constraint is initialized yet
538     return true;
539
540   // Check the features and constraint is the storage are valid
541   bool aResult = myStorage->isConsistent();
542   if (aResult) {
543     // additional check of consistency of the Fixed constraint,
544     // because they are not added to the storage
545     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
546     for (; aCIter != myConstraints.end(); ++aCIter)
547       if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
548          (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
549         aResult = false;
550         break;
551       }
552   }
553   if (!aResult) {
554     // remove invalid constraints
555     std::set<ConstraintPtr> anInvalidConstraints;
556     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
557     for (; aCIter != myConstraints.end(); ++aCIter) {
558       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
559         anInvalidConstraints.insert(aCIter->first);
560     }
561     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
562     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
563       removeConstraint(*aRemoveIt);
564     // remove invalid features
565     myStorage->removeInvalidEntities();
566   }
567   return aResult;
568 }
569
570 // ============================================================================
571 //  Function: removeTemporaryConstraints
572 //  Class:    SketchSolver_Group
573 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
574 //            resolving the set of constraints
575 // ============================================================================
576 void SketchSolver_Group::removeTemporaryConstraints()
577 {
578   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
579   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
580     (*aTmpIt)->remove();
581
582   if (!myTempConstraints.empty())
583     myStorage->verifyFixed();
584   myStorage->setNeedToResolve(false);
585   myTempConstraints.clear();
586 }
587
588 // ============================================================================
589 //  Function: removeConstraint
590 //  Class:    SketchSolver_Group
591 //  Purpose:  remove constraint and all unused entities
592 // ============================================================================
593 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
594 {
595   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
596   for (; aCIter != myConstraints.end(); aCIter++)
597     if (aCIter->first == theConstraint) {
598       aCIter->second->remove(); // the constraint is not fully removed
599       if (aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID())
600         notifyCoincidenceChanged(aCIter->second);
601       break;
602     }
603   if (aCIter != myConstraints.end())
604     myConstraints.erase(aCIter);
605 }
606
607 // ============================================================================
608 //  Function: setTemporary
609 //  Class:    SketchSolver_Group
610 //  Purpose:  append given constraint to the group of temporary constraints
611 // ============================================================================
612 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
613 {
614   myTempConstraints.insert(theConstraint);
615 }
616
617
618 // ============================================================================
619 //  Function: checkFeatureValidity
620 //  Class:    SketchSolver_Group
621 //  Purpose:  verifies is the feature valid
622 // ============================================================================
623 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
624 {
625   if (!theFeature || !theFeature->data()->isValid())
626     return true;
627
628   SessionPtr aMgr = ModelAPI_Session::get();
629   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
630   return aFactory->validate(theFeature);
631 }
632
633
634
635
636 // ===========   Auxiliary functions   ========================================
637 static double featureToVal(FeaturePtr theFeature)
638 {
639   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
640     return 0.0; // sketch
641   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
642   if (!aConstraint)
643     return 1.0; // features (arc, circle, line, point)
644
645   const std::string& anID = aConstraint->getKind();
646   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
647     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
648         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
649     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
650         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
651     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
652       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
653     return 2.5;
654   }
655   if (anID == SketchPlugin_ConstraintDistance::ID() ||
656       anID == SketchPlugin_ConstraintLength::ID() ||
657       anID == SketchPlugin_ConstraintRadius::ID())
658     return 3.0;
659   if (anID == SketchPlugin_ConstraintAngle::ID())
660     return 3.5;
661   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
662       anID == SketchPlugin_ConstraintVertical::ID() ||
663       anID == SketchPlugin_ConstraintParallel::ID() ||
664       anID == SketchPlugin_ConstraintPerpendicular::ID())
665     return 4.0;
666   if (anID == SketchPlugin_ConstraintEqual::ID())
667     return 5.0;
668   if (anID == SketchPlugin_ConstraintTangent::ID() ||
669       anID == SketchPlugin_ConstraintMirror::ID())
670     return 6.0;
671   if (anID == SketchPlugin_ConstraintRigid::ID())
672     return 7.0;
673   if (anID == SketchPlugin_MultiRotation::ID() ||
674       anID == SketchPlugin_MultiTranslation::ID())
675     return 8.0;
676
677   // all other constraints are placed between Equal and Tangent constraints
678   return 5.5;
679 }
680
681 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
682 {
683   return featureToVal(theFeature1) < featureToVal(theFeature2);
684 }
685
686 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
687 {
688   std::list<FeaturePtr> aResult;
689   std::list<FeaturePtr>::iterator aResIt;
690
691   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
692   for (; anObjIter != theObjects.end(); ++anObjIter) {
693     // Operate sketch itself and SketchPlugin features only.
694     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
695     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
696     if (!aFeature)
697       continue;
698     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
699         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
700     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
701         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
702       continue;
703
704     // Find the place where to insert a feature
705     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
706       if (isLess(aFeature, *aResIt))
707         break;
708     aResult.insert(aResIt, aFeature);
709   }
710
711   return aResult;
712 }
713
714 void SketchSolver_Group::notifyCoincidenceChanged(SolverConstraintPtr theCoincidence)
715 {
716   const std::list<EntityWrapperPtr>& aCoincident = theCoincidence->attributes();
717   EntityWrapperPtr anAttr1 = aCoincident.front();
718   EntityWrapperPtr anAttr2 = aCoincident.back();
719
720   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
721   for (; anIt != myConstraints.end(); ++anIt)
722     anIt->second->notifyCoincidenceChanged(anAttr1, anAttr2);
723 }