Salome HOME
Fix wrong unprompted update of entities on non-active sketches
[modules/shaper.git] / src / SketchSolver / SketchSolver_Manager.cpp
index 7b6bc263b0b772f6d6fff18e3c1aa1d15eb9683e..5867d6b94ed72ee786f611536ad14829f3363c8a 100644 (file)
@@ -8,6 +8,9 @@
 #include "SketchSolver_Error.h"
 
 #include <Events_Loop.h>
+
+#include <GeomDataAPI_Point2D.h>
+
 #include <ModelAPI_AttributeDouble.h>
 #include <ModelAPI_AttributeRefList.h>
 #include <ModelAPI_Data.h>
@@ -130,11 +133,16 @@ void SketchSolver_Manager::processEvent(
       for (aFeatIter = aFeatures.begin(); aFeatIter != aFeatures.end(); aFeatIter++) {
         std::shared_ptr<SketchPlugin_Feature> aSFeature = 
             std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
-        if (aSFeature) {
-          moveEntity(aSFeature);
+        if (aSFeature && moveEntity(aSFeature)) {
+          // Want to avoid recalculation of DoF too frequently.
+          // So, set the flag when the feature is really moved.
           hasProperFeature = true;
         }
       }
+      if (!hasProperFeature) // in this iteration it will compute nothing, so, no problem with recursion
+        // it is important that solver flushes signal updated after processing move signal as there is
+        // optimization that relies on this update, might be found by key "optimization"
+        myIsComputed = false;
     } else {
       std::list<FeaturePtr> aSketchFeatures = SketchSolver_Group::selectApplicableFeatures(aFeatures);
       std::list<FeaturePtr>::iterator aFeatIter = aSketchFeatures.begin();
@@ -178,6 +186,7 @@ void SketchSolver_Manager::processEvent(
         break;
 
     if (aFGrIter != aFeatureGroups.end()) {
+      hasProperFeature = true;
       std::list<SketchSolver_Group*> aGroupsToResolve;
       std::list<SketchSolver_Group*>::iterator aGroupIter = myGroups.begin();
       std::list<SketchSolver_Group*> aSeparatedGroups;
@@ -186,15 +195,14 @@ void SketchSolver_Manager::processEvent(
           delete *aGroupIter;
           std::list<SketchSolver_Group*>::iterator aRemoveIt = aGroupIter++;
           myGroups.erase(aRemoveIt);
-          hasProperFeature = true;
           continue;
         }
         if (!(*aGroupIter)->isConsistent()) {  // some constraints were removed, try to split the group
           (*aGroupIter)->splitGroup(aSeparatedGroups);
-          //if (!(*aGroupIter)->getWorkplane()->string(
-          //    SketchPlugin_Sketch::SOLVER_ERROR())->value().empty())
+          if (!(*aGroupIter)->getWorkplane()->string(
+              SketchPlugin_Sketch::SOLVER_ERROR())->value().empty() ||
+              (*aGroupIter)->isFailed())
             aGroupsToResolve.push_back(*aGroupIter);
-          hasProperFeature = true;
         }
         aGroupIter++;
       }
@@ -274,7 +282,7 @@ bool SketchSolver_Manager::changeWorkplane(CompositeFeaturePtr theSketch)
     }
     myGroups.push_back(aNewGroup);
   }
-  return aResult;
+  return aResult || isUpdated;
 }
 
 // ============================================================================
@@ -361,23 +369,44 @@ bool SketchSolver_Manager::changeFeature(std::shared_ptr<SketchPlugin_Feature> t
 //  Function: moveEntity
 //  Purpose:  update element moved on the sketch, which is used by constraints
 // ============================================================================
-void SketchSolver_Manager::moveEntity(std::shared_ptr<SketchPlugin_Feature> theFeature)
+bool SketchSolver_Manager::moveEntity(std::shared_ptr<SketchPlugin_Feature> theFeature)
 {
   bool isMoved = false;
   std::list<SketchSolver_Group*>::iterator aGroupIt = myGroups.begin();
   for (; aGroupIt != myGroups.end(); aGroupIt++)
-    if (!(*aGroupIt)->isEmpty() && (*aGroupIt)->isInteract(theFeature)) {
-      (*aGroupIt)->moveFeature(theFeature);
-      isMoved = true;
-    }
+    if (!(*aGroupIt)->isEmpty() && (*aGroupIt)->isInteract(theFeature))
+      isMoved = (*aGroupIt)->moveFeature(theFeature) || isMoved;
 
   if (!isMoved && theFeature->getKind() == SketchPlugin_Arc::ID()) {
     // Workaround to move arc.
     // If the arc has not been constrained, we will push it into empty group and apply movement.
+    bool hasEmptyGroup = false;
     for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); aGroupIt++)
-      if ((*aGroupIt)->isEmpty())
-        (*aGroupIt)->moveFeature(theFeature);
+      if ((*aGroupIt)->isEmpty()) {
+        isMoved = (*aGroupIt)->moveFeature(theFeature) || isMoved;
+        hasEmptyGroup = true;
+      }
+    // There is no empty group, create it explicitly
+    if (!hasEmptyGroup) {
+      // find sketch containing the arc
+      CompositeFeaturePtr aWP;
+      const std::set<AttributePtr>& aRefs = theFeature->data()->refsToMe();
+      std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
+      for (; aRefIt != aRefs.end(); ++aRefIt) {
+        FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
+        if (anOwner && anOwner->getKind() == SketchPlugin_Sketch::ID()) {
+          aWP = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anOwner);
+          break;
+        }
+      }
+      if (aWP) {
+        SketchSolver_Group* aGroup = new SketchSolver_Group(aWP);
+        isMoved = aGroup->moveFeature(theFeature) || isMoved;
+        myGroups.push_back(aGroup);
+      }
+    }
   }
+  return isMoved;
 }
 
 // ============================================================================
@@ -452,6 +481,87 @@ bool SketchSolver_Manager::resolveConstraints(const std::list<SketchSolver_Group
   return needToUpdate;
 }
 
+
+// Obtain points and their copies for Mirror, Multi-Rotation and Multi-Translation constraints
+static void collectPointsAndCopies(FeaturePtr theConstraint, std::list<std::set<AttributePtr> >& thePoints)
+{
+  typedef std::list<std::string> strlist;
+  static strlist aPointAttributes(1, SketchPlugin_Point::COORD_ID());
+  static strlist aLineAttributes;
+  if (aLineAttributes.empty()) {
+    aLineAttributes.push_back(SketchPlugin_Line::START_ID());
+    aLineAttributes.push_back(SketchPlugin_Line::END_ID());
+  };
+  static strlist aCircleAttributes(1, SketchPlugin_Circle::CENTER_ID());
+  static strlist anArcAttributes;
+  if (anArcAttributes.empty()) {
+    anArcAttributes.push_back(SketchPlugin_Arc::CENTER_ID());
+    anArcAttributes.push_back(SketchPlugin_Arc::START_ID());
+    anArcAttributes.push_back(SketchPlugin_Arc::END_ID());
+  };
+
+  static std::map<std::string, strlist> aFeatureAttributes;
+  if (aFeatureAttributes.empty()) {
+    aFeatureAttributes[SketchPlugin_Point::ID()] = aPointAttributes;
+    aFeatureAttributes[SketchPlugin_Line::ID()] = aLineAttributes;
+    aFeatureAttributes[SketchPlugin_Circle::ID()] = aCircleAttributes;
+    aFeatureAttributes[SketchPlugin_Arc::ID()] = anArcAttributes;
+  }
+
+
+  std::set<AttributePtr> aPoints;
+  if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
+    AttributeRefListPtr aBaseRefList = theConstraint->reflist(SketchPlugin_Constraint::ENTITY_B());
+    AttributeRefListPtr aMirrRefList = theConstraint->reflist(SketchPlugin_Constraint::ENTITY_C());
+
+    std::list<ObjectPtr> aBaseList = aBaseRefList->list();
+    std::list<ObjectPtr> aMirrList = aMirrRefList->list();
+    std::list<ObjectPtr>::const_iterator aBIt, aMIt;
+    for (aBIt = aBaseList.begin(), aMIt = aMirrList.begin();
+         aBIt != aBaseList.end() && aMIt != aMirrList.end(); ++aBIt, ++aMIt) {
+      FeaturePtr aBaseFeature = ModelAPI_Feature::feature(*aBIt);
+      FeaturePtr aMirrFeature = ModelAPI_Feature::feature(*aMIt);
+
+      strlist anAttrList = aFeatureAttributes[aBaseFeature->getKind()];
+      strlist::iterator anIt = anAttrList.begin();
+      for (; anIt != anAttrList.end(); ++anIt) {
+        aPoints.clear();
+        aPoints.insert(aBaseFeature->attribute(*anIt));
+        aPoints.insert(aMirrFeature->attribute(*anIt));
+        thePoints.push_back(aPoints);
+      }
+    }
+  }
+  else { // the "Multi" constraints
+    std::string aNbObjName;
+    if (theConstraint->getKind() == SketchPlugin_MultiRotation::ID())
+      aNbObjName = SketchPlugin_MultiRotation::NUMBER_OF_OBJECTS_ID();
+    else
+      aNbObjName = SketchPlugin_MultiTranslation::NUMBER_OF_OBJECTS_ID();
+    int aNbCopies = theConstraint->integer(aNbObjName)->value();
+
+    AttributeRefListPtr aRefList = theConstraint->reflist(SketchPlugin_Constraint::ENTITY_B());
+    std::list<ObjectPtr> aFullList = aRefList->list();
+    std::list<ObjectPtr>::const_iterator anObjIt = aFullList.begin();
+    std::list<ObjectPtr>::const_iterator aCopyIt;
+    while (anObjIt != aFullList.end()) {
+      FeaturePtr aBaseFeature = ModelAPI_Feature::feature(*anObjIt);
+      strlist anAttrList = aFeatureAttributes[aBaseFeature->getKind()];
+      strlist::iterator anIt = anAttrList.begin();
+      for (; anIt != anAttrList.end(); ++anIt) {
+        aPoints.clear();
+        aCopyIt = anObjIt;
+        for (int i = 0; i < aNbCopies && aCopyIt != aFullList.end(); ++i, ++aCopyIt) {
+          FeaturePtr aFeature = ModelAPI_Feature::feature(*aCopyIt);
+          aPoints.insert(aFeature->attribute(*anIt));
+        }
+        thePoints.push_back(aPoints);
+      }
+      anObjIt = aCopyIt;
+    }
+  }
+}
+
 // ============================================================================
 //  Function: degreesOfFreedom
 //  Purpose:  calculate DoFs for each sketch
@@ -472,7 +582,6 @@ void SketchSolver_Manager::degreesOfFreedom()
     aDoFDelta[SketchPlugin_ConstraintEqual::ID()] = -1;
     aDoFDelta[SketchPlugin_ConstraintHorizontal::ID()] = -1;
     aDoFDelta[SketchPlugin_ConstraintLength::ID()] = -1;
-    aDoFDelta[SketchPlugin_ConstraintMiddle::ID()] = -1;
     aDoFDelta[SketchPlugin_ConstraintParallel::ID()] = -1;
     aDoFDelta[SketchPlugin_ConstraintPerpendicular::ID()] = -1;
     aDoFDelta[SketchPlugin_ConstraintRadius::ID()] = -1;
@@ -487,7 +596,15 @@ void SketchSolver_Manager::degreesOfFreedom()
   std::list<SketchSolver_Group*>::const_iterator aGroupIt = myGroups.begin();
   for (; aGroupIt != myGroups.end(); ++aGroupIt) {
     CompositeFeaturePtr aSketch = (*aGroupIt)->getWorkplane();
-    if (!aSketch->data()->isValid()) {
+    bool isSketchValid = aSketch->data() && aSketch->data()->isValid();
+
+    if (isSketchValid) {
+      std::shared_ptr<GeomDataAPI_Dir> aNormal =
+          std::dynamic_pointer_cast<GeomDataAPI_Dir>(aSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
+      isSketchValid = aNormal && aNormal->isInitialized();
+    }
+
+    if (!isSketchValid) {
       myDoF.erase(aSketch);
       continue;
     }
@@ -500,6 +617,9 @@ void SketchSolver_Manager::degreesOfFreedom()
       continue;
 
     std::set<AttributePtr> aCoincidentPoints;
+    std::set<AttributePtr> aFixedPoints;
+    std::map<AttributePtr, std::set<FeaturePtr> > aPointOnLine;
+    std::list<std::set<AttributePtr> > aPointsInMultiConstraints;
     int aDoF = 0;
     int aNbSubs = aSketch->numberOfSubs();
     for (int i = 0; i < aNbSubs; ++i) {
@@ -514,43 +634,142 @@ void SketchSolver_Manager::degreesOfFreedom()
       // DoF delta in specific cases
       if (aFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
         AttributePtr aCoincPoint[2] = {AttributePtr(), AttributePtr()};
+        FeaturePtr aCoincLine;
         for (int j = 0; j < 2; ++j) {
           AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
               aFeature->attribute(SketchPlugin_Constraint::ATTRIBUTE(j)));
           if (!aRefAttr)
             continue;
-          bool isPoint = !aRefAttr->isObject();
-          if (isPoint)
+          if (!aRefAttr->isObject())
             aCoincPoint[j] = aRefAttr->attr();
           else {
             FeaturePtr anAttr = ModelAPI_Feature::feature(aRefAttr->object());
-            isPoint = anAttr && anAttr->getKind() == SketchPlugin_Point::ID();
-            if (isPoint)
+            if (!anAttr)
+              continue;
+            if (anAttr->getKind() == SketchPlugin_Point::ID())
               aCoincPoint[j] = anAttr->attribute(SketchPlugin_Point::COORD_ID());
+            else if (anAttr->getKind() == SketchPlugin_Line::ID())
+              aCoincLine = anAttr;
           }
         }
         if (aCoincPoint[0] && aCoincPoint[1]) {
+          bool isDoFDecreased = false;
           // point-point coincidence
           if (aCoincidentPoints.find(aCoincPoint[0]) == aCoincidentPoints.end() ||
-              aCoincidentPoints.find(aCoincPoint[1]) == aCoincidentPoints.end())
+              aCoincidentPoints.find(aCoincPoint[1]) == aCoincidentPoints.end()) {
             aDoF -= 2;
-        } else 
+            isDoFDecreased = true;
+          }
+          // check the coincident point is used in "multi" constraints
+          std::list<std::set<AttributePtr> >::const_iterator
+              aPtIt = aPointsInMultiConstraints.begin();
+          bool isFound[2] = {false, false};
+          for (; aPtIt != aPointsInMultiConstraints.end(); ++aPtIt) {
+            if ((!isFound[0] && (isFound[0] = (aPtIt->find(aCoincPoint[0]) != aPtIt->end())))
+             || (!isFound[1] && (isFound[1] = (aPtIt->find(aCoincPoint[1]) != aPtIt->end()))))
+              aCoincidentPoints.insert(aPtIt->begin(), aPtIt->end());
+            if (isFound[0] && isFound[1])
+              break;
+          }
+          // check both points are fixed => not need to decrease DoF
+          bool isFixed[2] = { aFixedPoints.find(aCoincPoint[0]) != aFixedPoints.end(),
+                              aFixedPoints.find(aCoincPoint[1]) != aFixedPoints.end() };
+          if (isFixed[0] && isFixed[1] && isDoFDecreased)
+            aDoF += 2; // revert decrease of DoF
+          else if (isFixed[0] && !isFixed[1])
+            aFixedPoints.insert(aCoincPoint[1]);
+          else if (!isFixed[0] && isFixed[1])
+            aFixedPoints.insert(aCoincPoint[0]);
+        } else {
           aDoF -= 1;
+          if (aCoincPoint[0] && aCoincLine) {
+            // if the point is already coincident to a line (by middle point constraint), do not decrease DoF
+            std::map<AttributePtr, std::set<FeaturePtr> >::iterator
+                aPtFound = aPointOnLine.find(aCoincPoint[0]);
+            if (aPtFound != aPointOnLine.end() &&
+                aPtFound->second.find(aCoincLine) != aPtFound->second.end())
+              aDoF += 1; // restore value decreased above
+            else
+              aPointOnLine[aCoincPoint[0]].insert(aCoincLine);
+          }
+        }
         for (int j = 0; j < 2; ++j)
           if (aCoincPoint[j])
             aCoincidentPoints.insert(aCoincPoint[j]);
       }
+      else if (aFeature->getKind() == SketchPlugin_ConstraintMiddle::ID()) {
+        AttributePtr aPoint;
+        FeaturePtr aLine;
+        for (int j = 0; j < 2; ++j) {
+          AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
+              aFeature->attribute(SketchPlugin_Constraint::ATTRIBUTE(j)));
+          if (!aRefAttr)
+            continue;
+          if (aRefAttr->isObject())
+            aLine = ModelAPI_Feature::feature(aRefAttr->object());
+          else
+            aPoint = aRefAttr->attr();
+        }
+        if (aPoint && aLine) {
+          // if the point is already on the line, decrease 1 DoF, instead decrease 2 DoF
+          std::map<AttributePtr, std::set<FeaturePtr> >::iterator
+              aPtFound = aPointOnLine.find(aPoint);
+          if (aPtFound != aPointOnLine.end() &&
+              aPtFound->second.find(aLine) != aPtFound->second.end())
+            aDoF -= 1;
+          else {
+            aDoF -= 2;
+            aPointOnLine[aPoint].insert(aLine);
+          }
+        }
+      }
       else if (aFeature->getKind() == SketchPlugin_ConstraintRigid::ID()) {
         AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
             aFeature->attribute(SketchPlugin_Constraint::ENTITY_A()));
         assert(aRefAttr);
-        if (!aRefAttr->isObject())
+        std::set<AttributePtr> aPoints;
+        if (!aRefAttr->isObject()) {
           aDoF -= 2; // attribute is a point
-        else {
+          aPoints.insert(aRefAttr->attr());
+        } else {
           FeaturePtr anAttr = ModelAPI_Feature::feature(aRefAttr->object());
-          assert(anAttr);
-          aDoF -= aDoFDelta[anAttr->getKind()];
+          if (anAttr)
+            aDoF -= aDoFDelta[anAttr->getKind()];
+          std::list<AttributePtr> aPtAttrs = anAttr->data()->attributes(GeomDataAPI_Point2D::typeId());
+          aPoints.insert(aPtAttrs.begin(), aPtAttrs.end());
+        }
+
+        // Check whether feature's points are already coincident with fixed points.
+        // In this case we need to revert decrease of DoF for these points.
+        // If the coordinates of fixed points are different, it will be processed by solver.
+        for (int k = 0; k < i; ++k) {
+          FeaturePtr aFeature = aSketch->subFeature(k);
+          if (aFeature->getKind() != SketchPlugin_ConstraintCoincidence::ID())
+            continue;
+          AttributePtr aCoincPoint[2] = {AttributePtr(), AttributePtr()};
+          for (int j = 0; j < 2; ++j) {
+            AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
+                aFeature->attribute(SketchPlugin_Constraint::ATTRIBUTE(j)));
+            if (!aRefAttr)
+              continue;
+            if (!aRefAttr->isObject())
+              aCoincPoint[j] = aRefAttr->attr();
+            else {
+              FeaturePtr anAttr = ModelAPI_Feature::feature(aRefAttr->object());
+              if (anAttr && anAttr->getKind() == SketchPlugin_Point::ID())
+                aCoincPoint[j] = anAttr->attribute(SketchPlugin_Point::COORD_ID());
+            }
+          }
+          if (aCoincPoint[0] && aCoincPoint[1]) {
+            if ((aFixedPoints.find(aCoincPoint[0]) != aFixedPoints.end() &&
+                 aPoints.find(aCoincPoint[1]) != aPoints.end()) ||
+                (aFixedPoints.find(aCoincPoint[1]) != aFixedPoints.end() &&
+                 aPoints.find(aCoincPoint[0]) != aPoints.end()))
+              aDoF += 2; // point already fixed
+          }
         }
+        // store fixed points
+        aFixedPoints.insert(aPoints.begin(), aPoints.end());
       }
       else if (aFeature->getKind() == SketchPlugin_ConstraintMirror::ID() ||
                aFeature->getKind() == SketchPlugin_MultiRotation::ID() ||
@@ -575,6 +794,8 @@ void SketchSolver_Manager::degreesOfFreedom()
           FeaturePtr aSub = ModelAPI_Feature::feature(*anObjIt);
           aDoF -= aDoFDelta[aSub->getKind()] * aNbCopies;
         }
+        // collect points and their copies for correct calculation of DoF for coincident points
+        collectPointsAndCopies(aFeature, aPointsInMultiConstraints);
       }
     }