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