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