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