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