Salome HOME
Support of all types of selection in python names import
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
index 6de12da8d0ad49553c9819a2ae402c9ae9bc86fa..78c167e9f4628d7147a77ef3a4a16119f14a3d92 100644 (file)
@@ -30,6 +30,7 @@
 #include <ModelAPI_CompositeFeature.h>
 #include <ModelAPI_ResultBody.h>
 #include <GeomAPI_Wire.h>
+#include <GeomAPI_Edge.h>
 
 #include <TopoDS_Iterator.hxx>
 #include <TopoDS.hxx>
 #include <TNaming_Tool.hxx>
 #include <TNaming_NamedShape.hxx>
 #include <TNaming_Localizer.hxx>
+#include <TNaming_SameShapeIterator.hxx>
 #include <TDataStd_Name.hxx>
 #include <TColStd_MapOfTransient.hxx>
+#include <Precision.hxx>
 #include <algorithm>
 #include <stdexcept>
 
@@ -61,6 +64,41 @@ Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
   myLab = theSelectionLab;
 }
 
+// searches named shape by the shape in the given document (identified by the label)
+// tries to find s shape nearest to the context-label
+static Handle(TNaming_NamedShape) shapeToNS(const TDF_Label theLabAccess,
+  const TopoDS_Shape& theShape, const TDF_Label& theContextLab)
+{
+  Handle(TNaming_NamedShape) aResult;
+  if (!TNaming_Tool::HasLabel(theLabAccess, theShape)) // no shape in the document
+    return aResult;
+  int aContextLabDepth = theContextLab.IsNull() ? 100 : theContextLab.Depth();
+  TNaming_SameShapeIterator aNSIter(theShape, theLabAccess);
+  for(; aNSIter.More(); aNSIter.Next()) {
+    TDF_Label aLabel = aNSIter.Label();
+    Handle(TNaming_NamedShape) aNS;
+    if (aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
+      if (aNS->Evolution() != TNaming_SELECTED && aNS->Evolution() != TNaming_DELETE) {
+        // check this is new shape in this named shape
+        bool aIsNew = false;
+        for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next())
+          if (!aNSIter.NewShape().IsNull() && aNSIter.NewShape().IsSame(theShape))
+            aIsNew = true;
+        if (!aIsNew)
+          continue;
+        // check this is the context-shape
+        while(aLabel.Depth() > aContextLabDepth)
+          aLabel = aLabel.Father();
+        if (aLabel.IsEqual(theContextLab))
+          return aNS;
+        if (aResult.IsNull()) // take the first, otherwise it will get shapes from results, etc
+          aResult = aNS; // keep some result anyway - if there are no context labels return any
+      }
+    }
+  }
+  return aResult;
+}
+
 std::string Model_SelectionNaming::getShapeName(
   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
   ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
@@ -70,13 +108,14 @@ std::string Model_SelectionNaming::getShapeName(
   // (it was in BodyBuilder, but did not work on Result rename)
   bool isNeedContextName = theContext->shape().get() != NULL;
   // check if the subShape is already in DF
-  Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
+  std::shared_ptr<Model_Data> aData =
+    std::dynamic_pointer_cast<Model_Data>(theContext->data());
+  TDF_Label aContextDataLab(aData.get() && aData->isValid() ? aData->label() : TDF_Label());
+  Handle(TNaming_NamedShape) aNS = shapeToNS(myLab, theShape, aContextDataLab);
   Handle(TDataStd_Name) anAttr;
   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
-      std::shared_ptr<Model_Data> aData =
-        std::dynamic_pointer_cast<Model_Data>(theContext->data());
-      if (isNeedContextName && aData && aData->label().IsEqual(aNS->Label())) {
+      if (isNeedContextName && aData && aContextDataLab.IsEqual(aNS->Label())) {
         // do nothing because this context name will be added later in this method
       } else {
         aName = TCollection_AsciiString(anAttr->Get()).ToCString();
@@ -104,10 +143,10 @@ std::string Model_SelectionNaming::getShapeName(
             !aNS->Label().IsDescendant(aContextData->label())) {
           isNeedContextName = false;
           TDF_Label aNSDataLab = aNS->Label();
-          while(aNSDataLab.Depth() != 7 && aNSDataLab.Depth() > 5)
+          if (aNSDataLab.Depth() % 2 == 0)
             aNSDataLab = aNSDataLab.Father();
           ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
-          if (!aNewContext.get() && aNSDataLab.Depth() == 7) {
+          while(!aNewContext.get() && aNSDataLab.Depth() > 5) {
             aNSDataLab = aNSDataLab.Father().Father();
             aNewContext = theDoc->objects()->object(aNSDataLab);
           }
@@ -219,6 +258,38 @@ const TopoDS_Shape findCommonShape(
   return aSharedShape;
 }
 
+std::string Model_SelectionNaming::vertexNameByEdges(TopoDS_Shape theContext, TopoDS_Shape theSub,
+  std::shared_ptr<Model_Document> theDoc, ResultPtr& theContextRes, const bool theAnotherDoc)
+{
+  std::string aResult;
+  TopTools_IndexedDataMapOfShapeListOfShape aMap;
+  TopExp::MapShapesAndAncestors(theContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
+  const TopTools_ListOfShape& aList22  = aMap.FindFromKey(theSub);
+  if(aList22.Extent() >= 2)  { // regular solution
+    TopTools_MapOfShape aFMap;
+    TopTools_ListOfShape aListE;
+    TopTools_ListIteratorOfListOfShape itl2(aList22);
+    for (int i = 1;itl2.More();itl2.Next(),i++) {
+      if(aFMap.Add(itl2.Value()))
+        aListE.Append(itl2.Value());
+    }
+    TopTools_ListIteratorOfListOfShape itl(aListE);
+    for (int i = 1;itl.More();itl.Next(),i++) {
+      const TopoDS_Shape& anEdge = itl.Value();
+      std::string anEdgeName = getShapeName(theDoc, anEdge, theContextRes, theAnotherDoc, false);
+      if (anEdgeName.empty()) { // edge is not in DS
+        aResult.clear();
+        return aResult;
+      }
+      if(i == 1)
+        aResult = anEdgeName;
+      else
+        aResult += "&" + anEdgeName;
+    }
+  }
+  return aResult;
+}
+
 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
   const bool theAnotherDoc)
@@ -288,7 +359,7 @@ std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
           }
         } else
           break;
-        TopTools_ListOfShape aListOfNbs;
+        TopTools_MapOfShape aNbs;
         if(!isTrivialCase) { // find Neighbors
           TNaming_Localizer aLocalizer;
           TopTools_MapOfShape aMap3;
@@ -302,25 +373,25 @@ std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
             TopTools_ListIteratorOfListOfShape it2(aList);
             for(;it2.More();it2.Next()) {
               if(aSMap.Contains(it2.Value())) continue; // skip this Face
-              aListOfNbs.Append(it2.Value());
+              aNbs.Add(it2.Value());
             }
           }
         }  // else a trivial case
 
         // build name of the sub-shape Edge
-        for(int i=1; i <= aSMap.Extent(); i++) {
-          const TopoDS_Shape& aFace = aSMap.FindKey(i);
+        // iterate faces of the context to get stable order, not map-order
+        TopTools_MapOfShape aStoredFaces; // to avoid duplicates
+        for(TopExp_Explorer aContExp(aContext, TopAbs_FACE); aContExp.More(); aContExp.Next()) {
+          const TopoDS_Shape& aFace = aContExp.Current();
+          if (aStoredFaces.Contains(aFace) || !(aSMap.Contains(aFace) || aNbs.Contains(aFace)))
+            continue;
+          aStoredFaces.Add(aFace);
           std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
-          if(i == 1)
+          if(aName.empty())
             aName = aFaceName;
           else
             aName += "&" + aFaceName;
         }
-        TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
-        for (;itl.More();itl.Next()) {
-          std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
-          aName += "&" + aFaceName;
-        }
       }
       break;
 
@@ -355,40 +426,28 @@ std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
           break;
         int n = aList.Extent();
         bool isByFaces = n >= 3;
+        if (isByFaces) { // check that by faces vertex is identified uniquly (2317)
+          TopoDS_Shape aVertex = findCommonShape(TopAbs_VERTEX, aList);
+          isByFaces = !aVertex.IsNull() && aVertex.ShapeType() == TopAbs_VERTEX;
+        }
+
         if(!isByFaces) { // open topology case or Compound case => via edges
-          TopTools_IndexedDataMapOfShapeListOfShape aMap;
-          TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
-          const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
-          if(aList22.Extent() >= 2)  { // regular solution
-
-            // bug! duplication; fix is below
-            aFMap.Clear();
-            TopTools_ListOfShape aListE;
-            TopTools_ListIteratorOfListOfShape itl2(aList22);
-            for (int i = 1;itl2.More();itl2.Next(),i++) {
-              if(aFMap.Add(itl2.Value()))
-                aListE.Append(itl2.Value());
-            }
-            n = aListE.Extent();
-            TopTools_ListIteratorOfListOfShape itl(aListE);
-            for (int i = 1;itl.More();itl.Next(),i++) {
-              const TopoDS_Shape& anEdge = itl.Value();
-              std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
-              if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
-                isByFaces = true;
-                aName.clear();
-                break;
+          aName = vertexNameByEdges(aContext, aSubShape, aDoc, theContext, theAnotherDoc);
+          isByFaces = aName.empty();
+          if (isByFaces) { // try to find a vertex in sketch faces
+            ResultConstructionPtr aConstr =
+              std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
+            if (aConstr.get() && aConstr->facesNum()) {
+              for(int aFace = aConstr->facesNum() - 1; isByFaces && aFace >= 0; aFace--) {
+                std::shared_ptr<GeomAPI_Face> aGFace = aConstr->face(aFace);
+                aName = vertexNameByEdges(aGFace->impl<TopoDS_Face>(), aSubShape,
+                  aDoc, theContext, theAnotherDoc);
+                isByFaces = aName.empty();
               }
-              if(i == 1)
-                aName = anEdgeName;
-              else
-                aName += "&" + anEdgeName;
             }
-          }//reg
-          else { // dangle vertex: if(aList22.Extent() == 1)
-            //it should be already in DF
           }
         }
+
         if (isByFaces) {
           TopTools_ListIteratorOfListOfShape itl(aList);
           for (int i = 1;itl.More();itl.Next(),i++) {
@@ -404,7 +463,6 @@ std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
       break;
     }
   }
-
   return aName;
 }
 
@@ -526,11 +584,11 @@ size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& t
 
 std::string getContextName(const std::string& theSubShapeName)
 {
-  std::string aName;
-  std::string::size_type n = theSubShapeName.find('/');
-  if (n == std::string::npos) return theSubShapeName;
-  aName = theSubShapeName.substr(0, n);
-  return aName;
+    std::string aName;
+    std::string::size_type n = theSubShapeName.find('/');
+    if (n == std::string::npos) return theSubShapeName;
+    aName = theSubShapeName.substr(0, n);
+    return aName;
 }
 
 /// Parses naming name of sketch sub-elements: takes indices and orientation
@@ -604,11 +662,70 @@ int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoD
   return 0; // unknown
 }
 
+int Model_CurvesHasher::HashCode(const Handle(Geom_Curve)& theCurve, const Standard_Integer Upper)
+{
+  double aFirstParam = theCurve->FirstParameter();
+  if (aFirstParam < -1.e+100 || aFirstParam > 1.e+100)
+    aFirstParam = 0;
+  double aLastParam = theCurve->LastParameter();
+  if (aLastParam < -1.e+100 || aLastParam > 1.e+100)
+    aLastParam = 2;
+  else aLastParam = (aLastParam + aFirstParam) / 2.; // to avoid in periodic same first and last
+
+  gp_XYZ aCoordSum = theCurve->Value(aFirstParam).XYZ() + theCurve->Value(aLastParam).XYZ();
+  return ::HashCode(aCoordSum.X() + aCoordSum.Y() / 123. + aCoordSum.Z() / 123456., Upper);
+}
+bool Model_CurvesHasher::IsEqual(const Handle(Geom_Curve)& theC1, const Handle(Geom_Curve)& theC2)
+{
+  if (theC1->DynamicType() != theC2->DynamicType())
+    return false;
+  double aFirstParam1 = theC1->FirstParameter();
+  if (aFirstParam1 < -1.e+100 || aFirstParam1 > 1.e+100)
+    aFirstParam1 = 0;
+  double aFirstParam2 = theC2->FirstParameter();
+  if (aFirstParam2 < -1.e+100 || aFirstParam2 > 1.e+100)
+    aFirstParam2 = 0;
+  if (fabs(aFirstParam1 - aFirstParam2) > 1.e-9)
+    return false;
+
+  double aLastParam1 = theC1->LastParameter();
+  if (aLastParam1 < -1.e+100 || aLastParam1 > 1.e+100)
+    aLastParam1 = 2.;
+  else aLastParam1 = (aLastParam1 + aFirstParam1) / 2.; // to avoid in periodic same first and last
+  double aLastParam2 = theC2->LastParameter();
+  if (aLastParam2 < -1.e+100 || aLastParam2 > 1.e+100)
+    aLastParam2 = 2.;
+  else aLastParam2 = (aLastParam2 + aFirstParam2) / 2.; // to avoid in periodic same first and last
+
+  if (fabs(aLastParam1 - aLastParam2) > 1.e-9)
+    return false;
+
+  return theC1->Value(aFirstParam1).IsEqual(theC2->Value(aFirstParam2), Precision::Confusion()) &&
+    theC1->Value(aLastParam1).IsEqual(theC2->Value(aLastParam2), Precision::Confusion());
+}
+
+int Model_EdgesHasher::HashCode(const TopoDS_Edge& theEdge, const Standard_Integer Upper)
+{
+  Standard_Real aFirst, aLast;
+  Handle(Geom_Curve) aCurve = BRep_Tool::Curve(theEdge, aFirst, aLast);
+  return Model_CurvesHasher::HashCode(aCurve, Upper);
+}
+
+bool Model_EdgesHasher::IsEqual(const TopoDS_Edge& theE1, const TopoDS_Edge& theE2)
+{
+  GeomEdgePtr aSh1(new GeomAPI_Edge);
+  aSh1->setImpl(new TopoDS_Shape(theE1));
+  GeomEdgePtr aSh2(new GeomAPI_Edge);
+  aSh2->setImpl(new TopoDS_Shape(theE2));
+  return aSh1->isEqual(aSh2);
+}
+
 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
   std::shared_ptr<ModelAPI_Result>& theConstr,
-  NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
+  NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher>& theCurves, const bool theIsWire)
 {
   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
+  int aBestNotFound = 1000000; // best number of not found edges (must be minimum)
   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
   std::shared_ptr<GeomAPI_Shape> aResult;
   ResultConstructionPtr aConstructionContext =
@@ -630,7 +747,7 @@ std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
     for(; aFW != aFacesWires.end(); aFW++) {
       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
-      TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
+      TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curves (841)
       for(; anEdgesExp.More(); anEdgesExp.Next()) {
         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
         if (!anEdge.IsNull()) {
@@ -651,18 +768,29 @@ std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
           }
         }
       }
+      if (theIsWire && aFound + aNotFound != 0) {
+        if (aBestNotFound > aNotFound || (aBestNotFound == aNotFound && aFound > aBestFound) ||
+          (aBestNotFound == aNotFound && aFound == aBestFound && aSameOrientation > aBestOrient)) {
+          aBestFound = aFound;
+          aBestOrient = aSameOrientation;
+          aBestNotFound = aNotFound;
+          std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
+          aWire->setImpl(new TopoDS_Shape(*aFW));
+          aResult = aWire;
+        }
+        aFound = 0;
+        aNotFound = 0;
+        aSameOrientation = 0;
+      }
+    }
+    if (!theIsWire) {
       if (aFound + aNotFound != 0) {
-        if (aFound > aBestFound ||
-          (aFound == aBestFound && aSameOrientation > aBestOrient)) {
-            aBestFound = aFound;
-            aBestOrient = aSameOrientation;
-            if (theIsWire) {
-              std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
-              aWire->setImpl(new TopoDS_Shape(*aFW));
-              aResult = aWire;
-            } else {
-              aResult = aConstructionContext->face(aFaceIndex);
-            }
+        if (aBestNotFound > aNotFound || (aBestNotFound == aNotFound && aFound > aBestFound) ||
+          (aBestNotFound == aNotFound && aFound == aBestFound && aSameOrientation > aBestOrient)) {
+          aBestFound = aFound;
+          aBestOrient = aSameOrientation;
+          aBestNotFound = aNotFound;
+          aResult = aConstructionContext->face(aFaceIndex);
         }
       }
     }
@@ -678,6 +806,8 @@ std::string Model_SelectionNaming::shortName(
   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
+  if (aName.empty())
+    return "";
   // remove the last 's', 'e', 'f' and 'r' symbols:
   // they are used as markers of start/end/forward/rewersed indicators
   static const std::string aSyms("sefr");
@@ -844,16 +974,28 @@ bool Model_SelectionNaming::selectSubShape(const std::string& theType,
             aFaceContext = aDoc->findByName(aContName, *it, anUniqueContext);
           }
         }
-        const TopoDS_Shape aFace = findFaceByName(*it, aDoc, aFaceContext, anUniqueContext);
+        TopoDS_Shape aFace = findFaceByName(*it, aDoc, aFaceContext, anUniqueContext);
+        if (aFace.IsNull() && aFaceContext.get() &&
+            aFaceContext->groupName() == ModelAPI_ResultConstruction::group() ) {
+          // search the construction sub-elements for the intersection if they are in the tree
+          size_t aSlash = it->find("/");
+          if (aSlash != std::string::npos) {
+            std::string aSubShapeName = it->substr(aSlash + 1);
+            aFace = findFaceByName(aSubShapeName, aDoc, aFaceContext, true);
+          }
+        }
         if(!aFace.IsNull())
           aList.Append(aFace);
       }
       aSelection = findCommonShape(aType, aList);
+      //if (aSelection.IsNull() && aType == TopAbs_EDGE) { // try to find selection by neighbours
+      //  aSelection = findCommonShapeByNB(aType, TopAbs_VERTEX, aList);
+      //}
     }
   }
   // in case of construction, there is no registered names for all sub-elements,
   // even for the main element; so, trying to find them by name (without "&" intersections)
-  if (aN < 2) {
+  if (aSelection.IsNull() && aN < 2) {
     size_t aConstrNamePos = aSubShapeName.find("/");
     bool isFullName = aConstrNamePos == std::string::npos;
     std::string anEmpty, aContrName = aContName;
@@ -940,7 +1082,7 @@ bool Model_SelectionNaming::selectSubShape(const std::string& theType,
             return false;
 
           // curves and orientations of edges
-          NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
+          NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher> allCurves;
           const int aSubNum = aComposite->numberOfSubs();
           for(int a = 0; a < aSubNum; a++) {
             int aSubID = aComposite->subFeatureId(a);
@@ -976,7 +1118,7 @@ bool Model_SelectionNaming::selectSubShape(const std::string& theType,
             return false;
 
            // curves and orientations of edges
-          NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
+          NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher> allCurves;
           const int aSubNum = aComposite->numberOfSubs();
           for(int a = 0; a < aSubNum; a++) {
             int aSubID = aComposite->subFeatureId(a);
@@ -1008,6 +1150,21 @@ bool Model_SelectionNaming::selectSubShape(const std::string& theType,
         }
       }
     }
+  } else if (aSelection.IsNull() && aN >= 2 && aType == TopAbs_VERTEX) {
+    // support of shape name as intersection separated by "&"
+    static std::string anEdgeType = "edge"; // for now it works only with su-edges
+    std::list<std::string>::iterator aSubNames = aListofNames.begin();
+    TopTools_ListOfShape aSubsList;
+    for(; aSubNames != aListofNames.end(); aSubNames++) {
+      std::string aSubName = *aSubNames;
+      std::shared_ptr<GeomAPI_Shape> aSubShapeFound;
+      std::shared_ptr<ModelAPI_Result> aContextFound;
+      if (selectSubShape(anEdgeType, aSubName, theDoc, aSubShapeFound, aContextFound)) {
+        if (aSubShapeFound.get())
+          aSubsList.Append(aSubShapeFound->impl<TopoDS_Shape>());
+      }
+    }
+    aSelection = findCommonShape(TopAbs_VERTEX, aSubsList);
   }
   if (!aSelection.IsNull()) {
     // Select it (must be after N=0 checking,