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