]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_SelectionNaming.cpp
Salome HOME
Fix for selection by name with suffix
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_SelectionNaming.cpp
4 // Created:     11 Aug 2015
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_SelectionNaming.h"
8 #include "Model_Document.h"
9 #include "Model_Objects.h"
10 #include <ModelAPI_Feature.h>
11 #include <Events_InfoMessage.h>
12 #include <ModelAPI_Session.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_ResultBody.h>
17 #include <GeomAPI_Wire.h>
18
19 #include <TopoDS_Iterator.hxx>
20 #include <TopoDS.hxx>
21 #include <TopoDS_Compound.hxx>
22 #include <TopExp.hxx>
23 #include <TopExp_Explorer.hxx>
24 #include <TopTools_ListOfShape.hxx>
25 #include <TopTools_MapOfShape.hxx>
26 #include <TopTools_IndexedMapOfShape.hxx>
27 #include <TopTools_ListIteratorOfListOfShape.hxx>
28 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
29 #include <TopTools_MapIteratorOfMapOfShape.hxx>
30 #include <BRep_Builder.hxx>
31 #include <TNaming_Iterator.hxx>
32 #include <TNaming_Tool.hxx>
33 #include <TNaming_NamedShape.hxx>
34 #include <TNaming_Localizer.hxx>
35 #include <TDataStd_Name.hxx>
36 #include <TColStd_MapOfTransient.hxx>
37 #include <algorithm>
38 #include <stdexcept>
39
40 #ifdef DEB_NAMING
41 #include <BRepTools.hxx>
42 #endif
43
44 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
45 {
46   myLab = theSelectionLab;
47 }
48
49 std::string Model_SelectionNaming::getShapeName(
50   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
51   const bool theAddContextName)
52 {
53   std::string aName;
54   // check if the subShape is already in DF
55   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
56   Handle(TDataStd_Name) anAttr;
57   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
58     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
59       aName = TCollection_AsciiString(anAttr->Get()).ToCString();
60       // indexes are added to sub-shapes not primitives (primitives must not be located at the same label)
61       if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && theAddContextName) {
62         const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
63         static const std::string aPostFix("_");
64         TNaming_Iterator anItL(aNS);
65         for(int i = 1; anItL.More(); anItL.Next(), i++) {
66           if(anItL.NewShape() == theShape) {
67             aName += aPostFix;
68             aName += TCollection_AsciiString (i).ToCString();
69             break;
70           }
71         }
72       }
73       if (theAddContextName && aName.find("/") == std::string::npos) { // searching for the context object
74         for(TDF_Label anObjL = aNS->Label(); anObjL.Depth() > 4; anObjL = anObjL.Father()) {
75           int aDepth = anObjL.Depth();
76           if (aDepth == 5 || aDepth == 7) {
77             ObjectPtr anObj = theDoc->objects()->object(anObjL);
78             if (anObj) {
79               aName = anObj->data()->name() + "/" + aName;
80             }
81           }
82         }
83       }
84     }
85   }
86   return aName;
87 }
88
89 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
90 {
91   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
92   TopoDS_Compound aCmp;
93   BRep_Builder BB;
94   BB.MakeCompound(aCmp);
95   TopTools_ListIteratorOfListOfShape it(theAncestors);
96   for(;it.More();it.Next()) {
97     BB.Add(aCmp, it.Value());
98     theSMap.Add(it.Value());
99   }
100   int aNumber(0);
101   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
102   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
103   for (int i = 1; i <= aMap2.Extent(); i++) {
104     const TopoDS_Shape& aKey = aMap2.FindKey(i);
105     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
106     if(anAncestors.Extent() > 1) aNumber++;
107   }
108   if(aNumber > 1) return false;
109   return true;
110 }
111
112 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
113   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
114   const bool theAnotherDoc)
115 {
116   std::string aName("Undefined name");
117   if(!theContext.get() || theContext->shape()->isNull()) 
118     return !theDefaultName.empty() ? theDefaultName : aName;
119   
120   // if it is in result of another part
121   std::shared_ptr<Model_Document> aDoc = 
122     std::dynamic_pointer_cast<Model_Document>(theContext->document());
123   if (theContext->groupName() == ModelAPI_ResultPart::group()) {
124     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
125     int anIndex;
126     return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
127   }
128
129   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
130     // but if it is in another Part, add this part name
131     std::string aPartName;
132     if (theAnotherDoc)
133       aPartName = theContext->document()->kind() + "/"; // PartSet
134     return aPartName + theContext->data()->name();
135   }
136   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
137   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
138 #ifdef DEB_NAMING
139   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
140     BRepTools::Write(aSubShape, "Selection.brep");
141     BRepTools::Write(aContext, "Context.brep");
142   }
143 #endif
144
145   // add the result name to the name of the shape (it was in BodyBuilder, but did not work on Result rename)
146   bool isNeedContextName = theContext->shape().get() && !theContext->shape()->isEqual(theSubSh);
147
148   // check if the subShape is already in DF
149   aName = getShapeName(aDoc, aSubShape, isNeedContextName);
150   if(aName.empty() ) { // not in the document!
151     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
152     switch (aType) {
153     case TopAbs_FACE:
154       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged             
155       break;
156     case TopAbs_EDGE:
157       {
158         // name structure: F1 & F2 [& F3 & F4], where F1 & F2 the faces which gives the Edge in trivial case
159         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces      
160         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
161           aName = "Degenerated_Edge";
162           break;
163         }    
164         TopTools_IndexedDataMapOfShapeListOfShape aMap;
165         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
166         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
167         bool isTrivialCase(true);
168         if(aMap.Contains(aSubShape)) {
169           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
170           // check that it is not a trivial case (F1 & F2: aNumber = 1)
171           isTrivialCase = isTrivial(anAncestors, aSMap);                
172         } else 
173           break;
174         TopTools_ListOfShape aListOfNbs;
175         if(!isTrivialCase) { // find Neighbors
176           TNaming_Localizer aLocalizer;
177           TopTools_MapOfShape aMap3;
178           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
179           //int n = aMap3.Extent();
180           TopTools_MapIteratorOfMapOfShape it(aMap3);
181           for(;it.More();it.Next()) {
182             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
183             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
184             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
185             TopTools_ListIteratorOfListOfShape it2(aList);
186             for(;it2.More();it2.Next()) {
187               if(aSMap.Contains(it2.Value())) continue; // skip this Face
188               aListOfNbs.Append(it2.Value());
189             }
190           }
191         }  // else a trivial case
192
193         // build name of the sub-shape Edge
194         for(int i=1; i <= aSMap.Extent(); i++) {
195           const TopoDS_Shape& aFace = aSMap.FindKey(i);
196           std::string aFaceName = getShapeName(aDoc, aFace, isNeedContextName);
197           if(i == 1)
198             aName = aFaceName;
199           else 
200             aName += "&" + aFaceName;
201         }
202         TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
203         for (;itl.More();itl.Next()) {
204           std::string aFaceName = getShapeName(aDoc, itl.Value(), isNeedContextName);
205           aName += "&" + aFaceName;
206         }                 
207       }
208       break;
209
210     case TopAbs_VERTEX:
211       // name structure (Monifold Topology): 
212       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
213       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
214       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
215       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
216       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
217       //                   or compound of 2 open faces.
218       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
219       //                   two independent edges (wire or compound)
220       // implemented 2 first cases
221       {
222         TopTools_IndexedDataMapOfShapeListOfShape aMap;
223         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
224         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
225         TopTools_ListOfShape aList;
226         TopTools_MapOfShape aFMap;
227         // fix is below
228         TopTools_ListIteratorOfListOfShape itl2(aList2);
229         for (int i = 1;itl2.More();itl2.Next(),i++) {
230           if(aFMap.Add(itl2.Value()))
231             aList.Append(itl2.Value());
232         }
233         int n = aList.Extent();
234         bool isByFaces = n >= 3;
235         if(!isByFaces) { // open topology case or Compound case => via edges
236           TopTools_IndexedDataMapOfShapeListOfShape aMap;
237           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
238           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
239           if(aList22.Extent() >= 2)  { // regular solution
240
241             // bug! duplication; fix is below
242             aFMap.Clear();
243             TopTools_ListOfShape aListE;
244             TopTools_ListIteratorOfListOfShape itl2(aList22);
245             for (int i = 1;itl2.More();itl2.Next(),i++) {
246               if(aFMap.Add(itl2.Value()))
247                 aListE.Append(itl2.Value());
248             }
249             n = aListE.Extent();
250             TopTools_ListIteratorOfListOfShape itl(aListE);
251             for (int i = 1;itl.More();itl.Next(),i++) {
252               const TopoDS_Shape& anEdge = itl.Value();
253               std::string anEdgeName = getShapeName(aDoc, anEdge, isNeedContextName);
254               if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
255                 isByFaces = true;
256                 aName.clear();
257                 break;
258               }
259               if(i == 1)
260                 aName = anEdgeName;
261               else 
262                 aName += "&" + anEdgeName;
263             }
264           }//reg
265           else { // dangle vertex: if(aList22.Extent() == 1)
266             //it should be already in DF
267           }
268         } 
269         if (isByFaces) {
270           TopTools_ListIteratorOfListOfShape itl(aList);
271           for (int i = 1;itl.More();itl.Next(),i++) {
272             const TopoDS_Shape& aFace = itl.Value();
273             std::string aFaceName = getShapeName(aDoc, aFace, isNeedContextName);
274             if(i == 1)
275               aName = aFaceName;
276             else 
277               aName += "&" + aFaceName;
278           }
279         }
280       }
281       break;
282     }
283   }
284
285   return aName;
286 }
287
288 TopAbs_ShapeEnum translateType (const std::string& theType)
289 {
290   // map from the textual shape types to OCCT enumeration
291   static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
292
293   if(aShapeTypes.size() == 0) {
294     aShapeTypes["compound"]   = TopAbs_COMPOUND;
295     aShapeTypes["compounds"]  = TopAbs_COMPOUND;
296     aShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
297     aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
298     aShapeTypes["solid"]      = TopAbs_SOLID;
299     aShapeTypes["solids"]     = TopAbs_SOLID;
300     aShapeTypes["shell"]      = TopAbs_SHELL;
301     aShapeTypes["shells"]     = TopAbs_SHELL;
302     aShapeTypes["face"]       = TopAbs_FACE;
303     aShapeTypes["faces"]      = TopAbs_FACE;
304     aShapeTypes["wire"]       = TopAbs_WIRE;
305     aShapeTypes["wires"]      = TopAbs_WIRE;
306     aShapeTypes["edge"]       = TopAbs_EDGE;
307     aShapeTypes["edges"]      = TopAbs_EDGE;
308     aShapeTypes["vertex"]     = TopAbs_VERTEX;
309     aShapeTypes["vertices"]   = TopAbs_VERTEX;
310     aShapeTypes["COMPOUND"]   = TopAbs_COMPOUND;
311     aShapeTypes["COMPOUNDS"]  = TopAbs_COMPOUND;
312     aShapeTypes["COMPSOLID"]  = TopAbs_COMPSOLID;
313     aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
314     aShapeTypes["SOLID"]      = TopAbs_SOLID;
315     aShapeTypes["SOLIDS"]     = TopAbs_SOLID;
316     aShapeTypes["SHELL"]      = TopAbs_SHELL;
317     aShapeTypes["SHELLS"]     = TopAbs_SHELL;
318     aShapeTypes["FACE"]       = TopAbs_FACE;
319     aShapeTypes["FACES"]      = TopAbs_FACE;
320     aShapeTypes["WIRE"]       = TopAbs_WIRE;
321     aShapeTypes["WIRES"]      = TopAbs_WIRE;
322     aShapeTypes["EDGE"]       = TopAbs_EDGE;
323     aShapeTypes["EDGES"]      = TopAbs_EDGE;
324     aShapeTypes["VERTEX"]     = TopAbs_VERTEX;
325     aShapeTypes["VERTICES"]   = TopAbs_VERTEX;
326   }
327   if (aShapeTypes.find(theType) != aShapeTypes.end())
328     return aShapeTypes[theType];
329   Events_InfoMessage("Model_SelectionNaming", "Shape type defined in XML is not implemented!").send();
330   return TopAbs_SHAPE;
331 }
332
333 const TopoDS_Shape getShapeFromNS(
334   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
335 {
336   TopoDS_Shape aSelection;
337   std::string::size_type n = theSubShapeName.rfind('/');                        
338   if (n == std::string::npos) n = -1;
339   std::string aSubString = theSubShapeName.substr(n + 1);
340   n = aSubString.rfind('_');
341   int indx = 1;
342   if (n != std::string::npos) {// for primitives this is a first 
343     // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
344     Handle(TDataStd_Name) aName;
345     if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
346         aName->Get() != theSubShapeName.c_str()) {
347       aSubString = aSubString.substr(n+1);
348       indx = atoi(aSubString.c_str());
349     }
350   }
351
352   TNaming_Iterator anItL(theNS);
353   for(int i = 1; anItL.More(); anItL.Next(), i++) {
354     if (i == indx) {
355       return anItL.NewShape();
356     }
357   }
358   return aSelection;    
359 }
360
361 const TopoDS_Shape findFaceByName(
362   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
363 {
364   TopoDS_Shape aFace;
365   //std::string::size_type n, nb = theSubShapeName.rfind('/');                  
366   //if (nb == std::string::npos) nb = 0;
367   //std::string aSubString = theSubShapeName.substr(nb + 1);
368   std::string aSubString = theSubShapeName;
369
370   TDF_Label aLabel = theDoc->findNamingName(aSubString);
371   if (aLabel.IsNull()) { // try to remove additional artificial suffix
372     std::string::size_type n = aSubString.rfind('_');
373     if (n != std::string::npos) {
374       aSubString = aSubString.substr(0, n);
375        aLabel = theDoc->findNamingName(aSubString);
376     }
377   }
378   if(aLabel.IsNull()) return aFace;
379   Handle(TNaming_NamedShape) aNS;
380   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
381     aFace = getShapeFromNS(theSubShapeName, aNS);
382   }
383   return aFace;
384 }
385
386 size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
387 {
388   std::string aName = theSubShapeName;
389   std::string aLastName;
390   size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
391   while ((n2 = aName.find('&', n1)) != std::string::npos) {
392     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
393     theList.push_back(aName1);  
394     n1 = n2 + 1;
395     aLastName = aName.substr(n1);
396   }
397   if(!aLastName.empty())
398     theList.push_back(aLastName);
399   return theList.size();
400 }
401
402 const TopoDS_Shape findCommonShape(
403   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
404 {
405   TopoDS_Shape aShape;
406   std::vector<TopTools_MapOfShape> aVec;
407   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
408   if(theList.Extent() > 1) {
409     aVec.push_back(aMap1);
410     aVec.push_back(aMap2);
411   }
412   if(theList.Extent() > 2)
413     aVec.push_back(aMap3);
414   if(theList.Extent() == 4)
415     aVec.push_back(aMap4);
416
417   //fill maps
418   TopTools_ListIteratorOfListOfShape it(theList);
419   for(int i = 0;it.More();it.Next(),i++) {
420     const TopoDS_Shape& aFace = it.Value();             
421     if(i < 2) {
422       TopExp_Explorer anExp (aFace, theType);
423       for(;anExp.More();anExp.Next()) {
424         const TopoDS_Shape& anEdge = anExp.Current();
425         if (!anEdge.IsNull())
426           aVec[i].Add(anExp.Current());
427       }
428     } else {
429       TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
430       for(;anExp.More();anExp.Next()) {
431         const TopoDS_Shape& aVertex = anExp.Current();
432         if (!aVertex.IsNull())
433           aVec[i].Add(anExp.Current());
434       }
435     }
436   }
437   //trivial case: 2 faces
438   TopTools_ListOfShape aList;
439   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
440   for(;it2.More();it2.Next()) {
441     if(aVec[1].Contains(it2.Key())) {
442       aShape = it2.Key();
443       if(theList.Extent() == 2)
444         break;
445       else 
446         aList.Append(it2.Key());
447     }
448   }
449   if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors 
450     if(aVec[2].Extent() && aVec[3].Extent()) {
451       TopTools_ListIteratorOfListOfShape it(aList);
452       for(;it.More();it.Next()) {
453         const TopoDS_Shape& aCand = it.Value();
454         // not yet completelly implemented, to be rechecked
455         TopoDS_Vertex aV1, aV2;
456         TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
457         int aNum(0);
458         if(aVec[2].Contains(aV1)) aNum++;
459         else if(aVec[2].Contains(aV2)) aNum++;
460         if(aVec[3].Contains(aV1)) aNum++;
461         else if(aVec[3].Contains(aV2)) aNum++;
462         if(aNum == 2) {
463           aShape = aCand;
464           break;
465         }
466       }
467     }
468   }
469
470   if(aList.Extent() && aVec.size() == 3) {
471
472     TopTools_ListIteratorOfListOfShape it(aList);
473     for(;it.More();it.Next()) {
474       const TopoDS_Shape& aCand = it.Value();
475       if(aVec[2].Contains(aCand)) {
476         aShape = aCand;
477         break;
478       }
479     }
480   }
481   return aShape;
482 }
483
484 std::string getContextName(const std::string& theSubShapeName)
485 {
486   std::string aName;
487   std::string::size_type n = theSubShapeName.find('/');                 
488   if (n == std::string::npos) return theSubShapeName;
489   aName = theSubShapeName.substr(0, n);
490   return aName;
491 }
492
493 /// Parses naming name of sketch sub-elements: takes indices and orientation 
494 /// (if theOriented = true) from this name. Map theIDs constains indices -> 
495 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
496 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
497   const std::string& theName, const char* theShapeType, 
498   std::map<int, int>& theIDs, const bool theOriented = false)
499 {
500   // collect all IDs in the name
501   std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
502   const int aSubNum = theComp->numberOfSubs();
503   for(int a = 0; a < aSubNum; a++) {
504     FeaturePtr aSub = theComp->subFeature(a);
505     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
506     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
507     // there may be many shapes (circle and center)
508     for(; aRes != aResults.cend(); aRes++) {
509       ResultConstructionPtr aConstr = 
510         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
511       if (aConstr.get()) {
512         aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
513       }
514     }
515   }
516
517   size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
518   bool isShape = false; // anyway the first world must be 'Vertex'
519   do {
520     aLastNamePos = theName.find('-', aPrevPos);
521     std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
522     if (!isShape) {
523       if (anID != theShapeType)
524         return false;
525       isShape = true;
526     } else {
527       int anOrientation = 1; // default
528       if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
529         std::string::iterator aSymbol = anID.end() - 1;
530         if (*aSymbol == 'r') anOrientation = -1;
531         anID.erase(aSymbol); // remove last symbol
532       }
533       // check start/end symbols
534       std::string::iterator aBack = anID.end() - 1;
535       if (*aBack == 's') {
536         anOrientation *= 2;
537         anID.erase(aBack); // remove last symbol
538       } else if (*aBack == 'e') {
539         anOrientation *= 3;
540         anID.erase(aBack); // remove last symbol
541       }
542
543       if (aNames.find(anID) != aNames.end()) {
544         theIDs[aNames[anID]] = anOrientation;
545       }
546     }
547     aPrevPos = aLastNamePos + 1;
548   } while (aLastNamePos != std::string::npos);
549   return true;
550 }
551
552 /// produces theEdge orientation relatively to theContext face
553 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
554 {
555   if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
556     return 0;
557   if (theEdge.Orientation() == TopAbs_FORWARD) 
558     return 1;
559   if (theEdge.Orientation() == TopAbs_REVERSED) 
560     return -1;
561   return 0; // unknown
562 }
563
564 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
565   std::shared_ptr<ModelAPI_Result>& theConstr, 
566   NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
567 {
568   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
569   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
570   std::shared_ptr<GeomAPI_Shape> aResult;
571   ResultConstructionPtr aConstructionContext = 
572       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
573   if (!aConstructionContext.get())
574     return aResult;
575   for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
576     int aFound = 0, aNotFound = 0, aSameOrientation = 0;
577     TopoDS_Face aFace = 
578       TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
579     std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
580     if (theIsWire) {
581       for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
582         aFacesWires.push_back(aWires.Current());
583       }
584     } else {
585       aFacesWires.push_back(aFace);
586     }
587     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
588     for(; aFW != aFacesWires.end(); aFW++) {
589       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
590       TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
591       for(; anEdgesExp.More(); anEdgesExp.Next()) {
592         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
593         if (!anEdge.IsNull()) {
594           Standard_Real aFirst, aLast;
595           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
596           if (alreadyProcessed.Contains(aCurve))
597             continue;
598           alreadyProcessed.Add(aCurve);
599           if (theCurves.IsBound(aCurve)) {
600             aFound++;
601             int anOrient = theCurves.Find(aCurve);
602             if (anOrient != 0) {  // extra comparision score is orientation
603               if (edgeOrientation(aFace, anEdge) == anOrient)
604                 aSameOrientation++;
605             }
606           } else {
607             aNotFound++;
608           }
609         }
610       }
611       if (aFound + aNotFound != 0) {
612         if (aFound > aBestFound || 
613           (aFound == aBestFound && aSameOrientation > aBestOrient)) {
614             aBestFound = aFound;
615             aBestOrient = aSameOrientation;
616             if (theIsWire) {
617               std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
618               aWire->setImpl(new TopoDS_Shape(*aFW));
619               aResult = aWire;
620             } else {
621               aResult = aConstructionContext->face(aFaceIndex);
622             }
623         }
624       }
625     }
626   }
627   return aResult;
628 }
629
630 std::string Model_SelectionNaming::shortName(
631   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
632 {
633   std::string aName = theConstr->data()->name();
634   // remove "-", "/" and "&" command-symbols
635   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
636   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
637   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
638   // remove the last 's', 'e', 'f' and 'r' symbols: they are used as markers of start/end/forward/rewersed indicators
639   static const std::string aSyms("sefr");
640   std::string::iterator aSuffix = aName.end() - 1;
641   while(aSyms.find(*aSuffix) != std::string::npos) {
642     --aSuffix;
643   }
644   aName.erase(aSuffix + 1, aName.end());
645
646   if (theEdgeVertexPos == 1) {
647     aName += "s"; // start
648   } else if (theEdgeVertexPos == 2) {
649     aName += "e"; // end
650   }
651   return aName;
652 }
653
654 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
655 bool Model_SelectionNaming::selectSubShape(const std::string& theType, 
656   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
657   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
658 {
659   if(theSubShapeName.empty() || theType.empty()) return false;
660   TopAbs_ShapeEnum aType = translateType(theType);
661
662   // check that it was selected in another document
663   size_t aSlash = theSubShapeName.find("/");
664   std::string aSubShapeName = theSubShapeName;
665   std::shared_ptr<Model_Document> aDoc = theDoc;
666   if (aSlash != std::string::npos) {
667     std::string aDocName = theSubShapeName.substr(0, aSlash);
668     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
669     if (aDocName == aRootDoc->kind()) {
670       aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
671     } else {
672       for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
673         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
674             aRootDoc->object(ModelAPI_ResultPart::group(), a));
675         if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
676           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
677         }
678       }
679     }
680     if (aDoc != theDoc) { // so, the first word is the document name => reduce the string for the next manips
681       aSubShapeName = theSubShapeName.substr(aSlash + 1);
682     }
683   }
684
685   std::string aContName = getContextName(aSubShapeName);
686   if(aContName.empty()) return false;
687   ResultPtr aCont = aDoc->findByName(aContName);
688    // possible this is body where postfix is added to distinguish several shapes on the same label
689   int aSubShapeId = -1; // -1 means sub shape not found
690   // for result body the name wihtout "_" has higher priority than with it: it is always added
691   if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) && 
692        aContName == aSubShapeName) {
693     size_t aPostIndex = aContName.rfind('_');
694     if (aPostIndex != std::string::npos) {
695       std::string aSubContName = aContName.substr(0, aPostIndex);
696       ResultPtr aSubCont = aDoc->findByName(aSubContName);
697       if (aSubCont.get()) {
698         try {
699           std::string aNum = aContName.substr(aPostIndex + 1);
700           aSubShapeId = std::stoi(aNum);
701         } catch (std::invalid_argument&) {
702           aSubShapeId = -1;
703         }
704         if (aSubShapeId > 0) {
705           aContName = aSubContName;
706           aCont = aSubCont;
707         }
708       }
709     }
710   }
711
712
713   TopoDS_Shape aSelection;
714   switch (aType) 
715   {
716   case TopAbs_FACE:
717   case TopAbs_WIRE:
718     {
719       aSelection = findFaceByName(aSubShapeName, aDoc);
720     }
721     break;
722   case TopAbs_EDGE:
723     {  
724       const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
725       if(!aLabel.IsNull()) {
726         Handle(TNaming_NamedShape) aNS;
727         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
728           aSelection = getShapeFromNS(aSubShapeName, aNS);
729         }
730       }
731     }
732     break;
733   case TopAbs_VERTEX:
734     {
735       const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
736       if(!aLabel.IsNull()) {
737         Handle(TNaming_NamedShape) aNS;
738         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
739           aSelection = getShapeFromNS(aSubShapeName, aNS);
740         }
741       }
742     }
743     break;
744   case TopAbs_COMPOUND:
745   case TopAbs_COMPSOLID:
746   case TopAbs_SOLID:
747   case TopAbs_SHELL:
748   default: {//TopAbs_SHAPE
749     /// case when the whole sketch is selected, so, selection type is compound, but there is no value
750     if (aCont.get() && aCont->shape().get()) {
751       if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
752         theCont = aCont;
753         return true;
754       } else if (aSubShapeId > 0) { // try to find sub-shape by the index
755         TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
756         for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
757           anExp.Next();
758         }
759         if (anExp.More()) {
760           std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
761           aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
762           theShapeToBeSelected = aShapeToBeSelected;
763           theCont = aCont;
764           return true;
765         }
766       }
767     }
768     return false;
769     }
770   }
771   // another try to find edge or vertex by faces
772   std::list<std::string> aListofNames;
773   size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
774   if (aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) {
775     if(aN > 1 && (aN < 4 || (aType == TopAbs_EDGE && aN < 5))) { // 2 || 3 or 4 for EDGE
776       TopTools_ListOfShape aList;
777       std::list<std::string>::iterator it = aListofNames.begin();
778       for(; it != aListofNames.end(); it++){
779         const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
780         if(!aFace.IsNull())
781           aList.Append(aFace);          
782       }
783       aSelection = findCommonShape(aType, aList);
784     }
785   }
786   // in case of construction, there is no registered names for all sub-elements,
787   // even for the main element; so, trying to find them by name (without "&" intersections)
788   if (aN == 0) {
789     size_t aConstrNamePos = aSubShapeName.find("/");
790     bool isFullName = aConstrNamePos == std::string::npos;
791     std::string aContrName = aContName;
792     ResultPtr aConstr = aDoc->findByName(aContrName);
793     if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
794       theCont = aConstr;
795       if (isFullName) {
796         // For the full construction selection shape must be empty.
797         //theShapeToBeSelected = aConstr->shape();
798         return true;
799       }
800       // for sketch sub-elements selected
801       CompositeFeaturePtr aComposite = 
802         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
803       if (aComposite.get()) {
804         if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
805           // collect all IDs in the name
806           std::map<int, int> anIDs;
807           if (!parseSubIndices(aComposite, aSubShapeName, 
808               aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs))
809             return false;
810
811           const int aSubNum = aComposite->numberOfSubs();
812           for(int a = 0; a < aSubNum; a++) {
813             int aCompID = aComposite->subFeatureId(a);
814             if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
815               FeaturePtr aSub = aComposite->subFeature(a);
816               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
817               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
818               // there may be many shapes (circle and center)
819               for(; aRIt != aResults.cend(); aRIt++) {
820                 ResultConstructionPtr aRes = 
821                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
822                 if (aRes) {
823                   int anOrientation = abs(anIDs[aCompID]);
824                   TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
825                   if (anOrientation == 1) {
826                     if (aType == aShape.ShapeType()) {
827                       theShapeToBeSelected = aRes->shape();
828                       return true;
829                     }
830                   } else { // take first or second vertex of the edge
831                     TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
832                     TopExp_Explorer anExp(aShape, aType);
833                     for(; anExp.More() && anOrientation != 2; anOrientation--)
834                       anExp.Next();
835                     if (anExp.More()) {
836                       std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
837                       aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
838                       theShapeToBeSelected = aShapeToBeSelected;
839                       return true;
840                     }
841                   }
842                 }
843               }
844             }
845           }
846           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
847         } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
848           std::map<int, int> anIDs;
849           if (!parseSubIndices(aComposite, aSubShapeName, 
850               aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
851             return false;
852
853           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
854           const int aSubNum = aComposite->numberOfSubs();
855           for(int a = 0; a < aSubNum; a++) {
856             int aSubID = aComposite->subFeatureId(a);
857             if (anIDs.find(aSubID) != anIDs.end()) {
858               FeaturePtr aSub = aComposite->subFeature(a);
859               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
860               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
861               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
862                 ResultConstructionPtr aConstr = 
863                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
864                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
865                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
866                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
867                   if (!anEdge.IsNull()) {
868                     Standard_Real aFirst, aLast;
869                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
870                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
871                   }
872                 }
873               }
874             }
875           }
876           std::shared_ptr<GeomAPI_Shape> aFoundFW =
877             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
878           if (aFoundFW.get()) {
879             theShapeToBeSelected = aFoundFW;
880             return true;
881           }
882         } else if (aType == TopAbs_WIRE) { // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
883           std::map<int, int> anIDs;
884           if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
885             return false;
886
887           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
888           const int aSubNum = aComposite->numberOfSubs();
889           for(int a = 0; a < aSubNum; a++) {
890             int aSubID = aComposite->subFeatureId(a);
891             if (anIDs.find(aSubID) != anIDs.end()) {
892               FeaturePtr aSub = aComposite->subFeature(a);
893               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
894               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
895               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
896                 ResultConstructionPtr aConstr = 
897                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
898                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
899                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
900                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
901                   if (!anEdge.IsNull()) {
902                     Standard_Real aFirst, aLast;
903                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
904                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
905                   }
906                 }
907               }
908             }
909           }
910           std::shared_ptr<GeomAPI_Shape> aFoundFW = 
911             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
912           if (aFoundFW.get()) {
913             theShapeToBeSelected = aFoundFW;
914             return true;
915           }
916         }
917       }
918     }
919   }
920   if (!aSelection.IsNull()) {// Select it (must be after N=0 checking, since for simple constructions the shape must be null)
921     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
922     aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
923     theShapeToBeSelected = aShapeToBeSelected;
924     theCont = aCont;
925     return true;
926   }
927
928   return false;
929 }