Salome HOME
9daf02c95f81b037869662d39efbfbda868c848d
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "Model_SelectionNaming.h"
22 #include "Model_Document.h"
23 #include "Model_Objects.h"
24 #include "Model_Data.h"
25 #include <ModelAPI_Feature.h>
26 #include <Events_InfoMessage.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_ResultPart.h>
29 #include <ModelAPI_ResultConstruction.h>
30 #include <ModelAPI_CompositeFeature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <GeomAPI_Wire.h>
33 #include <GeomAPI_Edge.h>
34
35 #include <TopoDS_Iterator.hxx>
36 #include <TopoDS.hxx>
37 #include <TopoDS_Compound.hxx>
38 #include <TopExp.hxx>
39 #include <TopExp_Explorer.hxx>
40 #include <TopTools_ListOfShape.hxx>
41 #include <TopTools_MapOfShape.hxx>
42 #include <TopTools_IndexedMapOfShape.hxx>
43 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_MapIteratorOfMapOfShape.hxx>
46 #include <BRep_Builder.hxx>
47 #include <TNaming_Iterator.hxx>
48 #include <TNaming_Tool.hxx>
49 #include <TNaming_NamedShape.hxx>
50 #include <TNaming_Localizer.hxx>
51 #include <TNaming_SameShapeIterator.hxx>
52 #include <TDataStd_Name.hxx>
53 #include <TColStd_MapOfTransient.hxx>
54 #include <Precision.hxx>
55 #include <algorithm>
56 #include <stdexcept>
57
58 #ifdef DEB_NAMING
59 #include <BRepTools.hxx>
60 #endif
61
62 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
63 {
64   myLab = theSelectionLab;
65 }
66
67 // searches named shape by the shape in the given document (identified by the label)
68 // tries to find s shape nearest to the context-label
69 static Handle(TNaming_NamedShape) shapeToNS(const TDF_Label theLabAccess,
70   const TopoDS_Shape& theShape, const TDF_Label& theContextLab)
71 {
72   Handle(TNaming_NamedShape) aResult;
73   if (!TNaming_Tool::HasLabel(theLabAccess, theShape)) // no shape in the document
74     return aResult;
75   int aContextLabDepth = theContextLab.IsNull() ? 100 : theContextLab.Depth();
76   TNaming_SameShapeIterator aNSIter(theShape, theLabAccess);
77   for(; aNSIter.More(); aNSIter.Next()) {
78     TDF_Label aLabel = aNSIter.Label();
79     Handle(TNaming_NamedShape) aNS;
80     if (aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
81       if (aNS->Evolution() != TNaming_SELECTED && aNS->Evolution() != TNaming_DELETE) {
82         // check this is new shape in this named shape
83         bool aIsNew = false;
84         for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next())
85           if (!aNSIter.NewShape().IsNull() && aNSIter.NewShape().IsSame(theShape))
86             aIsNew = true;
87         if (!aIsNew)
88           continue;
89         // check this is the context-shape
90         while(aLabel.Depth() > aContextLabDepth)
91           aLabel = aLabel.Father();
92         if (aLabel.IsEqual(theContextLab))
93           return aNS;
94         if (aResult.IsNull()) // take the first, otherwise it will get shapes from results, etc
95           aResult = aNS; // keep some result anyway - if there are no context labels return any
96       }
97     }
98   }
99   return aResult;
100 }
101
102 std::string Model_SelectionNaming::getShapeName(
103   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
104   ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
105 {
106   std::string aName;
107   // add the result name to the name of the shape
108   // (it was in BodyBuilder, but did not work on Result rename)
109   bool isNeedContextName = theContext->shape().get() != NULL;
110   // check if the subShape is already in DF
111   std::shared_ptr<Model_Data> aData =
112     std::dynamic_pointer_cast<Model_Data>(theContext->data());
113   TDF_Label aContextDataLab(aData.get() && aData->isValid() ? aData->label() : TDF_Label());
114   Handle(TNaming_NamedShape) aNS = shapeToNS(myLab, theShape, aContextDataLab);
115   Handle(TDataStd_Name) anAttr;
116   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
117     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
118       if (isNeedContextName && aData && aContextDataLab.IsEqual(aNS->Label())) {
119         // do nothing because this context name will be added later in this method
120       } else {
121         aName = TCollection_AsciiString(anAttr->Get()).ToCString();
122         // indexes are added to sub-shapes not primitives
123         // (primitives must not be located at the same label)
124         if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && isNeedContextName) {
125           const TDF_Label& aLabel = aNS->Label();
126           static const std::string aPostFix("_");
127           TNaming_Iterator anItL(aNS);
128           for(int i = 1; anItL.More(); anItL.Next(), i++) {
129             // in #1766 IsEqual produced no index of the face
130             if(anItL.NewShape().IsSame(theShape)) {
131               aName += aPostFix;
132               aName += TCollection_AsciiString (i).ToCString();
133               break;
134             }
135           }
136         }
137         // if a shape is under another context, use this name, not theContext
138         std::shared_ptr<Model_Data> aContextData =
139           std::dynamic_pointer_cast<Model_Data>(theContext->data());
140         // for constructions the naming is in arguments and has no evolution, so, apply this only
141         // for bodies
142         if (isNeedContextName && theContext->groupName() == ModelAPI_ResultBody::group() &&
143             !aNS->Label().IsDescendant(aContextData->label())) {
144           isNeedContextName = false;
145           TDF_Label aNSDataLab = aNS->Label();
146           if (aNSDataLab.Depth() % 2 == 0)
147             aNSDataLab = aNSDataLab.Father();
148           ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
149           while(!aNewContext.get() && aNSDataLab.Depth() > 5) {
150             aNSDataLab = aNSDataLab.Father().Father();
151             aNewContext = theDoc->objects()->object(aNSDataLab);
152           }
153           if (aNewContext.get()) {
154             // this is to avoid duplicated names of results problem
155             std::string aContextName = aNewContext->data()->name();
156             // myLab corresponds to the current time
157             TDF_Label aCurrentLab = myLab;
158             while(aCurrentLab.Depth() > 3)
159               aCurrentLab = aCurrentLab.Father();
160
161             int aNumInHistoryNames =
162               theDoc->numberOfNameInHistory(aNewContext, aCurrentLab);
163             while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
164               aContextName = "_" + aContextName;
165               aNumInHistoryNames--;
166             }
167
168             aName = aContextName + "/" + aName;
169           }
170         }
171       }
172     }
173   }
174
175   // Name is empty and this is full context, it just add the whole context name that must be added
176   bool isEmptyName = aName.empty();
177   if (isNeedContextName && (!isEmptyName || theWholeContext)) {
178     aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
179     if (theAnotherDoc)
180       aName = theContext->document()->kind() + "/" + aName; // PartSet
181   }
182   return aName;
183 }
184
185 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
186 {
187   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
188   TopoDS_Compound aCmp;
189   BRep_Builder BB;
190   BB.MakeCompound(aCmp);
191   TopTools_ListIteratorOfListOfShape it(theAncestors);
192   for(;it.More();it.Next()) {
193     if (theSMap.Contains(it.Value()))
194       continue;
195     BB.Add(aCmp, it.Value());
196     theSMap.Add(it.Value());
197   }
198   int aNumber(0);
199   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
200   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
201   for (int i = 1; i <= aMap2.Extent(); i++) {
202     const TopoDS_Shape& aKey = aMap2.FindKey(i);
203     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
204     if(anAncestors.Extent() > 1) aNumber++;
205   }
206   if(aNumber > 1) return false;
207   return true;
208 }
209
210 const TopoDS_Shape findCommonShape(
211   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
212 {
213   if(theList.Extent() < 1) {
214     return TopoDS_Shape();
215   } else if (theList.Extent() == 1) { // check that sub-shape is bounded by this alone shape
216     TopTools_MapOfShape aSubsInShape;
217     TopExp_Explorer anExp(theList.First(), theType);
218     for(; anExp.More(); anExp.Next()) {
219       if (aSubsInShape.Contains(anExp.Current())) { // found duplicate
220         return anExp.Current();
221       }
222       aSubsInShape.Add(anExp.Current());
223     }
224   }
225
226   // Store in maps sub-shapes from each face.
227   std::vector<TopTools_MapOfShape> aVec;
228   for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) {
229     const TopoDS_Shape aFace = anIt.Value();
230     TopTools_MapOfShape aMap;
231     for(TopExp_Explorer anExp(aFace, theType); anExp.More(); anExp.Next()) {
232       const TopoDS_Shape& aSubShape = anExp.Current();
233       aMap.Add(anExp.Current());
234     }
235     aVec.push_back(aMap);
236   }
237
238   // Find sub-shape shared between all faces.
239   TopoDS_Shape aSharedShape;
240   for(TopTools_MapIteratorOfMapOfShape anIt(aVec[0]); anIt.More(); anIt.Next()) {
241     const TopoDS_Shape& aSubShape = anIt.Value();
242     int aSharedNb = 1;
243     for(int anIndex = 1; anIndex < aVec.size(); ++anIndex) {
244       if(aVec[anIndex].Contains(aSubShape)) {
245         ++aSharedNb;
246       }
247     }
248     if(aSharedNb == theList.Extent()) {
249       if(aSharedShape.IsNull()) {
250         aSharedShape = aSubShape;
251       } else {
252         // More than one shape shared between all faces, return null shape in this case.
253         return TopoDS_Shape();
254       }
255     }
256   }
257
258   return aSharedShape;
259 }
260
261 // searches theType shape that contains theConnectionType sub-shapes in each shape from the List,
262 // so, implements the neighbours searching
263 /*
264 const TopoDS_Shape findCommonShapeByNB(const TopAbs_ShapeEnum theType,
265   const TopAbs_ShapeEnum theConnectionType, const TopTools_ListOfShape& theList)
266 {
267 TopTools_MapOfShape aCheckedShapes; // already checked shapes of type theType
268   TopoDS_Shape aResult; // theType result shape
269   for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) { // iterate all
270     for(TopExp_Explorer anExp(anIt.ChangeValue(), theType); anExp.More(); anExp.Next()) {
271       if (aCheckedShapes.Contains(anExp.Current()))
272         continue; // already checked
273       aCheckedShapes.Add(anExp.Current());
274       TopTools_MapOfShape aConnectors; // all connectors of the checked theType shape
275       for(TopExp_Explorer aCExp(anExp.Current(), theConnectionType); aCExp.More(); aCExp.Next()) {
276         aConnectors.Add(aCExp.Current());
277       }
278       // check that all shapes from the List contain the connector sub-shapes
279       bool aFound = true;
280       for(TopTools_ListIteratorOfListOfShape anIt2(theList); anIt2.More() && aFound; anIt2.Next()) {
281         if (anIt2.Value().IsSame(anIt.Value()))
282           continue;
283         aFound = false;
284         for(TopExp_Explorer anE(anIt2.ChangeValue(), theConnectionType); anE.More(); anE.Next()) {
285           if (aConnectors.Contains(anE.Current())) {
286             aFound = true;
287             break;
288           }
289         }
290       }
291       if (aFound) {
292         if (!aResult.IsNull()) // more than one result
293           return TopoDS_Shape();
294         aResult = anExp.Current();
295       }
296     }
297   }
298   return aResult;
299 }*/
300
301 std::string Model_SelectionNaming::vertexNameByEdges(TopoDS_Shape theContext, TopoDS_Shape theSub,
302   std::shared_ptr<Model_Document> theDoc, ResultPtr& theContextRes, const bool theAnotherDoc)
303 {
304   std::string aResult;
305   TopTools_IndexedDataMapOfShapeListOfShape aMap;
306   TopExp::MapShapesAndAncestors(theContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
307   const TopTools_ListOfShape& aList22  = aMap.FindFromKey(theSub);
308   if(aList22.Extent() >= 2)  { // regular solution
309     TopTools_MapOfShape aFMap;
310     TopTools_ListOfShape aListE;
311     TopTools_ListIteratorOfListOfShape itl2(aList22);
312     for (int i = 1;itl2.More();itl2.Next(),i++) {
313       if(aFMap.Add(itl2.Value()))
314         aListE.Append(itl2.Value());
315     }
316     TopTools_ListIteratorOfListOfShape itl(aListE);
317     for (int i = 1;itl.More();itl.Next(),i++) {
318       const TopoDS_Shape& anEdge = itl.Value();
319       std::string anEdgeName = getShapeName(theDoc, anEdge, theContextRes, theAnotherDoc, false);
320       if (anEdgeName.empty()) { // edge is not in DS
321         aResult.clear();
322         return aResult;
323       }
324       if(i == 1)
325         aResult = anEdgeName;
326       else
327         aResult += "&" + anEdgeName;
328     }
329   }
330   return aResult;
331 }
332
333 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
334   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
335   const bool theAnotherDoc)
336 {
337   std::string aName("Undefined name");
338   if(!theContext.get()
339       || !theContext->shape().get()
340       || theContext->shape()->isNull()) {
341     return !theDefaultName.empty() ? theDefaultName : aName;
342   }
343
344   // if it is in result of another part
345   std::shared_ptr<Model_Document> aDoc =
346     std::dynamic_pointer_cast<Model_Document>(theContext->document());
347   if (theContext->groupName() == ModelAPI_ResultPart::group()) {
348     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
349     int anIndex;
350     if (theSubSh.get())
351       return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
352     else
353       return aPart->data()->name();
354   }
355
356   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
357     // but if it is in another Part, add this part name
358     std::string aPartName;
359     if (theAnotherDoc)
360       aPartName = theContext->document()->kind() + "/"; // PartSet
361     return aPartName + theContext->data()->name();
362   }
363   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
364   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
365 #ifdef DEB_NAMING
366   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
367     BRepTools::Write(aSubShape, "Selection.brep");
368     BRepTools::Write(aContext, "Context.brep");
369   }
370 #endif
371   aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
372     theContext->shape()->isEqual(theSubSh));
373
374   if(aName.empty() ) { // not in the document!
375     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
376     switch (aType) {
377     case TopAbs_FACE:
378       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
379       break;
380     case TopAbs_EDGE:
381       {
382         // name structure: F1 & F2 [& F3 & F4],
383         // where F1 & F2 the faces which gives the Edge in trivial case
384         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
385         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
386           aName = "Degenerated_Edge";
387           break;
388         }
389         TopTools_IndexedDataMapOfShapeListOfShape aMap;
390         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
391         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
392         bool isTrivialCase(true);
393         if(aMap.Contains(aSubShape)) {
394           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
395           // check that it is not a trivial case (F1 & F2: aNumber = 1)
396           isTrivialCase = isTrivial(anAncestors, aSMap);
397           if (!isTrivialCase) { // another try: check that common shape can be processed anyway
398             isTrivialCase = !findCommonShape(TopAbs_EDGE, anAncestors).IsNull();
399           }
400         } else
401           break;
402         TopTools_MapOfShape aNbs;
403         if(!isTrivialCase) { // find Neighbors
404           TNaming_Localizer aLocalizer;
405           TopTools_MapOfShape aMap3;
406           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
407           //int n = aMap3.Extent();
408           TopTools_MapIteratorOfMapOfShape it(aMap3);
409           for(;it.More();it.Next()) {
410             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
411             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
412             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
413             TopTools_ListIteratorOfListOfShape it2(aList);
414             for(;it2.More();it2.Next()) {
415               if(aSMap.Contains(it2.Value())) continue; // skip this Face
416               aNbs.Add(it2.Value());
417             }
418           }
419         }  // else a trivial case
420
421         // build name of the sub-shape Edge
422         // iterate faces of the context to get stable order, not map-order
423         TopTools_MapOfShape aStoredFaces; // to avoid duplicates
424         for(TopExp_Explorer aContExp(aContext, TopAbs_FACE); aContExp.More(); aContExp.Next()) {
425           const TopoDS_Shape& aFace = aContExp.Current();
426           if (aStoredFaces.Contains(aFace) || !(aSMap.Contains(aFace) || aNbs.Contains(aFace)))
427             continue;
428           aStoredFaces.Add(aFace);
429           std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
430           if(aName.empty())
431             aName = aFaceName;
432           else
433             aName += "&" + aFaceName;
434         }
435       }
436       break;
437
438     case TopAbs_VERTEX:
439       // name structure (Monifold Topology):
440       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
441       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
442       //                               but it should be kept as is to obtain safe recomputation
443       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
444       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
445       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
446       //                   or compound of 2 open faces.
447       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of
448       //                   two independent edges (wire or compound)
449       // implemented 2 first cases
450       {
451         TopTools_IndexedDataMapOfShapeListOfShape aMap;
452         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
453         TopTools_ListOfShape aList;
454         TopTools_MapOfShape aFMap;
455         // simetimes when group is moved in history, naming may be badly updated, so
456         // avoid crash in FindFromKey (issue 1842)
457         if (aMap.Contains(aSubShape)) {
458           const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
459           // fix is below
460           TopTools_ListIteratorOfListOfShape itl2(aList2);
461           for (int i = 1;itl2.More();itl2.Next(),i++) {
462             if(aFMap.Add(itl2.Value()))
463               aList.Append(itl2.Value());
464           }
465         } else
466           break;
467         int n = aList.Extent();
468         bool isByFaces = n >= 3;
469         if (isByFaces) { // check that by faces vertex is identified uniquly (2317)
470           TopoDS_Shape aVertex = findCommonShape(TopAbs_VERTEX, aList);
471           isByFaces = !aVertex.IsNull() && aVertex.ShapeType() == TopAbs_VERTEX;
472         }
473
474         if(!isByFaces) { // open topology case or Compound case => via edges
475           aName = vertexNameByEdges(aContext, aSubShape, aDoc, theContext, theAnotherDoc);
476           isByFaces = aName.empty();
477           if (isByFaces) { // try to find a vertex in sketch faces
478             ResultConstructionPtr aConstr =
479               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
480             if (aConstr.get() && aConstr->facesNum()) {
481               for(int aFace = aConstr->facesNum() - 1; isByFaces && aFace >= 0; aFace--) {
482                 std::shared_ptr<GeomAPI_Face> aGFace = aConstr->face(aFace);
483                 aName = vertexNameByEdges(aGFace->impl<TopoDS_Face>(), aSubShape,
484                   aDoc, theContext, theAnotherDoc);
485                 isByFaces = aName.empty();
486               }
487             }
488           }
489         }
490
491         if (isByFaces) {
492           TopTools_ListIteratorOfListOfShape itl(aList);
493           for (int i = 1;itl.More();itl.Next(),i++) {
494             const TopoDS_Shape& aFace = itl.Value();
495             std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
496             if(i == 1)
497               aName = aFaceName;
498             else
499               aName += "&" + aFaceName;
500           }
501         }
502       }
503       break;
504     }
505   }
506   return aName;
507 }
508
509 TopAbs_ShapeEnum translateType (const std::string& theType)
510 {
511   // map from the textual shape types to OCCT enumeration
512   static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
513
514   if(aShapeTypes.size() == 0) {
515     aShapeTypes["compound"]   = TopAbs_COMPOUND;
516     aShapeTypes["compounds"]  = TopAbs_COMPOUND;
517     aShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
518     aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
519     aShapeTypes["solid"]      = TopAbs_SOLID;
520     aShapeTypes["solids"]     = TopAbs_SOLID;
521     aShapeTypes["shell"]      = TopAbs_SHELL;
522     aShapeTypes["shells"]     = TopAbs_SHELL;
523     aShapeTypes["face"]       = TopAbs_FACE;
524     aShapeTypes["faces"]      = TopAbs_FACE;
525     aShapeTypes["wire"]       = TopAbs_WIRE;
526     aShapeTypes["wires"]      = TopAbs_WIRE;
527     aShapeTypes["edge"]       = TopAbs_EDGE;
528     aShapeTypes["edges"]      = TopAbs_EDGE;
529     aShapeTypes["vertex"]     = TopAbs_VERTEX;
530     aShapeTypes["vertices"]   = TopAbs_VERTEX;
531     aShapeTypes["COMPOUND"]   = TopAbs_COMPOUND;
532     aShapeTypes["COMPOUNDS"]  = TopAbs_COMPOUND;
533     aShapeTypes["COMPSOLID"]  = TopAbs_COMPSOLID;
534     aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
535     aShapeTypes["SOLID"]      = TopAbs_SOLID;
536     aShapeTypes["SOLIDS"]     = TopAbs_SOLID;
537     aShapeTypes["SHELL"]      = TopAbs_SHELL;
538     aShapeTypes["SHELLS"]     = TopAbs_SHELL;
539     aShapeTypes["FACE"]       = TopAbs_FACE;
540     aShapeTypes["FACES"]      = TopAbs_FACE;
541     aShapeTypes["WIRE"]       = TopAbs_WIRE;
542     aShapeTypes["WIRES"]      = TopAbs_WIRE;
543     aShapeTypes["EDGE"]       = TopAbs_EDGE;
544     aShapeTypes["EDGES"]      = TopAbs_EDGE;
545     aShapeTypes["VERTEX"]     = TopAbs_VERTEX;
546     aShapeTypes["VERTICES"]   = TopAbs_VERTEX;
547   }
548   if (aShapeTypes.find(theType) != aShapeTypes.end())
549     return aShapeTypes[theType];
550   Events_InfoMessage("Model_SelectionNaming",
551     "Shape type defined in XML is not implemented!").send();
552   return TopAbs_SHAPE;
553 }
554
555 const TopoDS_Shape getShapeFromNS(
556   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
557 {
558   TopoDS_Shape aSelection;
559   std::string::size_type n = theSubShapeName.rfind('/');
560   if (n == std::string::npos) n = -1;
561   std::string aSubString = theSubShapeName.substr(n + 1);
562   n = aSubString.rfind('_');
563   int indx = 1;
564   if (n != std::string::npos) {// for primitives this is a first
565     // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
566     Handle(TDataStd_Name) aName;
567     if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
568         aName->Get() != aSubString.c_str()) {
569       aSubString = aSubString.substr(n+1);
570       indx = atoi(aSubString.c_str());
571     }
572   }
573
574   TNaming_Iterator anItL(theNS);
575   for(int i = 1; anItL.More(); anItL.Next(), i++) {
576     if (i == indx) {
577       return anItL.NewShape();
578     }
579   }
580   return aSelection;
581 }
582
583 const TopoDS_Shape findFaceByName(
584   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
585   const ResultPtr theDetectedContext, bool theContextIsUnique)
586 {
587   TopoDS_Shape aFace;
588   std::string aSubString = theSubShapeName;
589
590   static const ResultPtr anEmpty;
591   TDF_Label aLabel = theDoc->findNamingName(aSubString,
592     theContextIsUnique ? theDetectedContext : anEmpty);
593   if (aLabel.IsNull()) { // try to remove additional artificial suffix
594     std::string::size_type n = aSubString.rfind('_');
595     if (n != std::string::npos) {
596       aSubString = aSubString.substr(0, n);
597       aLabel = theDoc->findNamingName(aSubString,
598         theContextIsUnique ? theDetectedContext : anEmpty);
599     }
600   }
601   if(aLabel.IsNull()) return aFace;
602   Handle(TNaming_NamedShape) aNS;
603   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
604     aFace = getShapeFromNS(theSubShapeName, aNS);
605   }
606   return aFace;
607 }
608
609 size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
610 {
611   std::string aName = theSubShapeName;
612   std::string aLastName = aName;
613   size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
614   while ((n2 = aName.find('&', n1)) != std::string::npos) {
615     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
616     theList.push_back(aName1);
617     n1 = n2 + 1;
618     aLastName = aName.substr(n1);
619   }
620   if(!aLastName.empty())
621     theList.push_back(aLastName);
622   return theList.size();
623 }
624
625 std::string getContextName(const std::string& theSubShapeName)
626 {
627   std::string aName;
628   std::string::size_type n = theSubShapeName.find('/');
629   if (n == std::string::npos) return theSubShapeName;
630   aName = theSubShapeName.substr(0, n);
631   return aName;
632 }
633
634 /// Parses naming name of sketch sub-elements: takes indices and orientation
635 /// (if theOriented = true) from this name. Map theIDs constains indices ->
636 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
637 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
638   const std::string& theName, const char* theShapeType,
639   std::map<int, int>& theIDs, const bool theOriented = false)
640 {
641   // collect all IDs in the name
642   std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
643   const int aSubNum = theComp->numberOfSubs();
644   for(int a = 0; a < aSubNum; a++) {
645     FeaturePtr aSub = theComp->subFeature(a);
646     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
647     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
648     // there may be many shapes (circle and center)
649     for(; aRes != aResults.cend(); aRes++) {
650       ResultConstructionPtr aConstr =
651         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
652       if (aConstr.get()) {
653         aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
654       }
655     }
656   }
657
658   size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
659   bool isShape = false; // anyway the first world must be 'Vertex'
660   do {
661     aLastNamePos = theName.find('-', aPrevPos);
662     std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
663     if (!isShape) {
664       if (anID != theShapeType)
665         return false;
666       isShape = true;
667     } else {
668       int anOrientation = 1; // default
669       if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
670         std::string::iterator aSymbol = anID.end() - 1;
671         if (*aSymbol == 'r') anOrientation = -1;
672         anID.erase(aSymbol); // remove last symbol
673       }
674       // check start/end symbols
675       std::string::iterator aBack = anID.end() - 1;
676       if (*aBack == 's') {
677         anOrientation *= 2;
678         anID.erase(aBack); // remove last symbol
679       } else if (*aBack == 'e') {
680         anOrientation *= 3;
681         anID.erase(aBack); // remove last symbol
682       }
683
684       if (aNames.find(anID) != aNames.end()) {
685         theIDs[aNames[anID]] = anOrientation;
686       }
687     }
688     aPrevPos = aLastNamePos + 1;
689   } while (aLastNamePos != std::string::npos);
690   return true;
691 }
692
693 /// produces theEdge orientation relatively to theContext face
694 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
695 {
696   if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
697     return 0;
698   if (theEdge.Orientation() == TopAbs_FORWARD)
699     return 1;
700   if (theEdge.Orientation() == TopAbs_REVERSED)
701     return -1;
702   return 0; // unknown
703 }
704
705 int Model_CurvesHasher::HashCode(const Handle(Geom_Curve)& theCurve, const Standard_Integer Upper)
706 {
707   double aFirstParam = theCurve->FirstParameter();
708   if (aFirstParam < -1.e+100 || aFirstParam > 1.e+100)
709     aFirstParam = 0;
710   double aLastParam = theCurve->LastParameter();
711   if (aLastParam < -1.e+100 || aLastParam > 1.e+100)
712     aLastParam = 2;
713   else aLastParam = (aLastParam + aFirstParam) / 2.; // to avoid in periodic same first and last
714
715   gp_XYZ aCoordSum = theCurve->Value(aFirstParam).XYZ() + theCurve->Value(aLastParam).XYZ();
716   return ::HashCode(aCoordSum.X() + aCoordSum.Y() / 123. + aCoordSum.Z() / 123456., Upper);
717 }
718 bool Model_CurvesHasher::IsEqual(const Handle(Geom_Curve)& theC1, const Handle(Geom_Curve)& theC2)
719 {
720   if (theC1->DynamicType() != theC2->DynamicType())
721     return false;
722   double aFirstParam1 = theC1->FirstParameter();
723   if (aFirstParam1 < -1.e+100 || aFirstParam1 > 1.e+100)
724     aFirstParam1 = 0;
725   double aFirstParam2 = theC2->FirstParameter();
726   if (aFirstParam2 < -1.e+100 || aFirstParam2 > 1.e+100)
727     aFirstParam2 = 0;
728   if (fabs(aFirstParam1 - aFirstParam2) > 1.e-9)
729     return false;
730
731   double aLastParam1 = theC1->LastParameter();
732   if (aLastParam1 < -1.e+100 || aLastParam1 > 1.e+100)
733     aLastParam1 = 2.;
734   else aLastParam1 = (aLastParam1 + aFirstParam1) / 2.; // to avoid in periodic same first and last
735   double aLastParam2 = theC2->LastParameter();
736   if (aLastParam2 < -1.e+100 || aLastParam2 > 1.e+100)
737     aLastParam2 = 2.;
738   else aLastParam2 = (aLastParam2 + aFirstParam2) / 2.; // to avoid in periodic same first and last
739
740   if (fabs(aLastParam1 - aLastParam2) > 1.e-9)
741     return false;
742
743   return theC1->Value(aFirstParam1).IsEqual(theC2->Value(aFirstParam2), Precision::Confusion()) &&
744     theC1->Value(aLastParam1).IsEqual(theC2->Value(aLastParam2), Precision::Confusion());
745 }
746
747 int Model_EdgesHasher::HashCode(const TopoDS_Edge& theEdge, const Standard_Integer Upper)
748 {
749   Standard_Real aFirst, aLast;
750   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(theEdge, aFirst, aLast);
751   return Model_CurvesHasher::HashCode(aCurve, Upper);
752 }
753
754 bool Model_EdgesHasher::IsEqual(const TopoDS_Edge& theE1, const TopoDS_Edge& theE2)
755 {
756   GeomEdgePtr aSh1(new GeomAPI_Edge);
757   aSh1->setImpl(new TopoDS_Shape(theE1));
758   GeomEdgePtr aSh2(new GeomAPI_Edge);
759   aSh2->setImpl(new TopoDS_Shape(theE2));
760   return aSh1->isEqual(aSh2);
761 }
762
763 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
764   std::shared_ptr<ModelAPI_Result>& theConstr,
765   NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher>& theCurves, const bool theIsWire)
766 {
767   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
768   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
769   std::shared_ptr<GeomAPI_Shape> aResult;
770   ResultConstructionPtr aConstructionContext =
771       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
772   if (!aConstructionContext.get())
773     return aResult;
774   for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
775     int aFound = 0, aNotFound = 0, aSameOrientation = 0;
776     TopoDS_Face aFace =
777       TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
778     std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
779     if (theIsWire) {
780       for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
781         aFacesWires.push_back(aWires.Current());
782       }
783     } else {
784       aFacesWires.push_back(aFace);
785     }
786     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
787     for(; aFW != aFacesWires.end(); aFW++) {
788       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
789       TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curves (841)
790       for(; anEdgesExp.More(); anEdgesExp.Next()) {
791         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
792         if (!anEdge.IsNull()) {
793           Standard_Real aFirst, aLast;
794           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
795           if (alreadyProcessed.Contains(aCurve))
796             continue;
797           alreadyProcessed.Add(aCurve);
798           if (theCurves.IsBound(aCurve)) {
799             aFound++;
800             int anOrient = theCurves.Find(aCurve);
801             if (anOrient != 0) {  // extra comparision score is orientation
802               if (edgeOrientation(aFace, anEdge) == anOrient)
803                 aSameOrientation++;
804             }
805           } else {
806             aNotFound++;
807           }
808         }
809       }
810       if (aFound + aNotFound != 0) {
811         if (aFound > aBestFound ||
812           (aFound == aBestFound && aSameOrientation > aBestOrient)) {
813             aBestFound = aFound;
814             aBestOrient = aSameOrientation;
815             if (theIsWire) {
816               std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
817               aWire->setImpl(new TopoDS_Shape(*aFW));
818               aResult = aWire;
819             } else {
820               aResult = aConstructionContext->face(aFaceIndex);
821             }
822         }
823       }
824     }
825   }
826   return aResult;
827 }
828
829 std::string Model_SelectionNaming::shortName(
830   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
831 {
832   std::string aName = theConstr->data()->name();
833   // remove "-", "/" and "&" command-symbols
834   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
835   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
836   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
837   // remove the last 's', 'e', 'f' and 'r' symbols:
838   // they are used as markers of start/end/forward/rewersed indicators
839   static const std::string aSyms("sefr");
840   std::string::iterator aSuffix = aName.end() - 1;
841   while(aSyms.find(*aSuffix) != std::string::npos) {
842     --aSuffix;
843   }
844   aName.erase(aSuffix + 1, aName.end());
845
846   if (theEdgeVertexPos == 1) {
847     aName += "s"; // start
848   } else if (theEdgeVertexPos == 2) {
849     aName += "e"; // end
850   }
851   return aName;
852 }
853
854 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
855 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
856   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
857   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
858 {
859   if(theSubShapeName.empty() || theType.empty()) return false;
860   TopAbs_ShapeEnum aType = translateType(theType);
861
862   // check that it was selected in another document
863   size_t aSlash = theSubShapeName.find("/");
864   std::string aSubShapeName = theSubShapeName;
865   std::shared_ptr<Model_Document> aDoc = theDoc;
866   if (aSlash != std::string::npos) {
867     std::string aDocName = theSubShapeName.substr(0, aSlash);
868     ResultPartPtr aFoundPart;
869     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
870     if (aDocName == aRootDoc->kind()) {
871       aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
872     } else {
873       for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
874         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
875             aRootDoc->object(ModelAPI_ResultPart::group(), a));
876         if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
877           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
878           aFoundPart = aPart;
879           break;
880         }
881       }
882     }
883     if (aDoc != theDoc) {
884       // so, the first word is the document name => reduce the string for the next manips
885       aSubShapeName = theSubShapeName.substr(aSlash + 1);
886       if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
887         theCont = aFoundPart;
888         return true;
889       }
890     }
891   }
892
893   std::string aContName = getContextName(aSubShapeName);
894   if(aContName.empty()) return false;
895   bool anUniqueContext = false;
896   ResultPtr aCont = aDoc->findByName(aContName, aSubShapeName, anUniqueContext);
897    // possible this is body where postfix is added to distinguish several shapes on the same label
898   int aSubShapeId = -1; // -1 means sub shape not found
899   // for result body the name wihtout "_" has higher priority than with it: it is always added
900   if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
901        aContName == aSubShapeName) {
902     size_t aPostIndex = aContName.rfind('_');
903     if (aPostIndex != std::string::npos) {
904       std::string anEmpty, aSubContName = aContName.substr(0, aPostIndex);
905       ResultPtr aSubCont = aDoc->findByName(aSubContName, anEmpty, anUniqueContext);
906       if (aSubCont.get()) {
907         try {
908           std::string aNum = aContName.substr(aPostIndex + 1);
909           aSubShapeId = std::stoi(aNum);
910         } catch (std::invalid_argument&) {
911           aSubShapeId = -1;
912         }
913         if (aSubShapeId > 0) {
914           aContName = aSubContName;
915           aCont = aSubCont;
916         }
917       }
918     }
919   }
920
921
922   static const ResultPtr anEmpty;
923   TopoDS_Shape aSelection;
924   switch (aType)
925   {
926   case TopAbs_FACE:
927   case TopAbs_WIRE:
928     {
929       aSelection = findFaceByName(aSubShapeName, aDoc, aCont, anUniqueContext);
930     }
931     break;
932   case TopAbs_EDGE:
933     {
934       const TDF_Label& aLabel =
935         aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
936       if(!aLabel.IsNull()) {
937         Handle(TNaming_NamedShape) aNS;
938         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
939           aSelection = getShapeFromNS(aSubShapeName, aNS);
940         }
941       }
942     }
943     break;
944   case TopAbs_VERTEX:
945     {
946       const TDF_Label& aLabel =
947         aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
948       if(!aLabel.IsNull()) {
949         Handle(TNaming_NamedShape) aNS;
950         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
951           aSelection = getShapeFromNS(aSubShapeName, aNS);
952         }
953       }
954     }
955     break;
956   case TopAbs_COMPOUND:
957   case TopAbs_COMPSOLID:
958   case TopAbs_SOLID:
959   case TopAbs_SHELL:
960   default: {//TopAbs_SHAPE
961     /// case when the whole sketch is selected, so,
962     /// selection type is compound, but there is no value
963     if (aCont.get() && aCont->shape().get()) {
964       if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
965         theCont = aCont;
966         return true;
967       } else if (aSubShapeId > 0) { // try to find sub-shape by the index
968         TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
969         for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
970           anExp.Next();
971         }
972         if (anExp.More()) {
973           std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
974           aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
975           theShapeToBeSelected = aShapeToBeSelected;
976           theCont = aCont;
977           return true;
978         }
979       }
980     }
981     return false;
982     }
983   }
984   if (!aSelection.IsNull() &&
985       aSelection.ShapeType() != aType && aSelection.ShapeType() != TopAbs_COMPOUND)
986       aSelection.Nullify(); // to avoid selection of face instead of edge that is described by face
987   // another try to find edge or vertex by faces
988   std::list<std::string> aListofNames;
989   size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
990   if ((aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) ||
991       (!aSelection.IsNull() && aSelection.ShapeType() != aType)) { // edge by one face as example
992     if(aN >= 1) {
993       TopTools_ListOfShape aList;
994       std::list<std::string>::iterator it = aListofNames.begin();
995       for(; it != aListofNames.end(); it++) {
996         ResultPtr aFaceContext = aCont;
997         if (it != aListofNames.begin()) { // there may be other context for different sub-faces
998           std::string aContName = getContextName(*it);
999           if(!aContName.empty()) {
1000             aFaceContext = aDoc->findByName(aContName, *it, anUniqueContext);
1001           }
1002         }
1003         TopoDS_Shape aFace = findFaceByName(*it, aDoc, aFaceContext, anUniqueContext);
1004         if (aFace.IsNull() && aFaceContext.get() &&
1005             aFaceContext->groupName() == ModelAPI_ResultConstruction::group() ) {
1006           // search the construction sub-elements for the intersection if they are in the tree
1007           size_t aSlash = it->find("/");
1008           if (aSlash != std::string::npos) {
1009             std::string aSubShapeName = it->substr(aSlash + 1);
1010             aFace = findFaceByName(aSubShapeName, aDoc, aFaceContext, true);
1011           }
1012         }
1013         if(!aFace.IsNull())
1014           aList.Append(aFace);
1015       }
1016       aSelection = findCommonShape(aType, aList);
1017       //if (aSelection.IsNull() && aType == TopAbs_EDGE) { // try to find selection by neighbours
1018       //  aSelection = findCommonShapeByNB(aType, TopAbs_VERTEX, aList);
1019       //}
1020     }
1021   }
1022   // in case of construction, there is no registered names for all sub-elements,
1023   // even for the main element; so, trying to find them by name (without "&" intersections)
1024   if (aSelection.IsNull() && aN < 2) {
1025     size_t aConstrNamePos = aSubShapeName.find("/");
1026     bool isFullName = aConstrNamePos == std::string::npos;
1027     std::string anEmpty, aContrName = aContName;
1028     ResultPtr aConstr = aDoc->findByName(aContrName, anEmpty, anUniqueContext);
1029     if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
1030       theCont = aConstr;
1031       if (isFullName) {
1032         // For the full construction selection shape must be empty.
1033         //theShapeToBeSelected = aConstr->shape();
1034         return true;
1035       }
1036       // for sketch sub-elements selected
1037       CompositeFeaturePtr aComposite =
1038         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
1039       if (aComposite.get()) {
1040         if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
1041           // collect all IDs in the name
1042           bool isVertexByEdge = false;
1043           std::map<int, int> anIDs;
1044           if (!parseSubIndices(aComposite, aSubShapeName,
1045               aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs)) {
1046             // there is a case when vertex is identified by one circle-edge (2253)
1047             if (aType == TopAbs_VERTEX &&
1048                 parseSubIndices(aComposite, aSubShapeName, "Edge", anIDs))
1049               isVertexByEdge = true;
1050             else
1051               return false;
1052           }
1053
1054           const int aSubNum = aComposite->numberOfSubs();
1055           for(int a = 0; a < aSubNum; a++) {
1056             int aCompID = aComposite->subFeatureId(a);
1057             if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
1058               FeaturePtr aSub = aComposite->subFeature(a);
1059               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1060               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
1061               // there may be many shapes (circle and center)
1062               for(; aRIt != aResults.cend(); aRIt++) {
1063                 ResultConstructionPtr aRes =
1064                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
1065                 if (aRes) {
1066                   int anOrientation = abs(anIDs[aCompID]);
1067                   TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
1068                   if (anOrientation == 1) {
1069                     if (!isVertexByEdge && aType == aShape.ShapeType()) {
1070                       theShapeToBeSelected = aRes->shape();
1071                       return true;
1072                     } else if (isVertexByEdge && aType != aShape.ShapeType()) {
1073                       // check that there is only one vertex produces by and circular edge
1074                       TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
1075                       TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
1076                       if (anExp.More())
1077                         aShape = anExp.Current();
1078                       anExp.Next();
1079                       if (!anExp.More() || anExp.Current().IsSame(aShape)) {
1080                         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1081                         aShapeToBeSelected->setImpl(new TopoDS_Shape(aShape));
1082                         theShapeToBeSelected = aShapeToBeSelected;
1083                         return true;
1084                       }
1085                     }
1086                   } else { // take first or second vertex of the edge
1087                     TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
1088                     if (aShape.ShapeType() == TopAbs_VERTEX) continue;
1089                     TopExp_Explorer anExp(aShape, aType);
1090                     for(; anExp.More() && anOrientation != 2; anOrientation--)
1091                       anExp.Next();
1092                     if (anExp.More()) {
1093                       std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1094                       aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
1095                       theShapeToBeSelected = aShapeToBeSelected;
1096                       return true;
1097                     }
1098                   }
1099                 }
1100               }
1101             }
1102           }
1103           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
1104         } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
1105           std::map<int, int> anIDs;
1106           if (!parseSubIndices(aComposite, aSubShapeName,
1107               aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
1108             return false;
1109
1110           // curves and orientations of edges
1111           NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher> allCurves;
1112           const int aSubNum = aComposite->numberOfSubs();
1113           for(int a = 0; a < aSubNum; a++) {
1114             int aSubID = aComposite->subFeatureId(a);
1115             if (anIDs.find(aSubID) != anIDs.end()) {
1116               FeaturePtr aSub = aComposite->subFeature(a);
1117               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1118               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
1119               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
1120                 ResultConstructionPtr aConstr =
1121                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1122                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
1123                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
1124                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
1125                   if (!anEdge.IsNull()) {
1126                     Standard_Real aFirst, aLast;
1127                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1128                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1129                   }
1130                 }
1131               }
1132             }
1133           }
1134           std::shared_ptr<GeomAPI_Shape> aFoundFW =
1135             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1136           if (aFoundFW.get()) {
1137             theShapeToBeSelected = aFoundFW;
1138             return true;
1139           }
1140         } else if (aType == TopAbs_WIRE) {
1141           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
1142           std::map<int, int> anIDs;
1143           if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
1144             return false;
1145
1146            // curves and orientations of edges
1147           NCollection_DataMap<Handle(Geom_Curve), int, Model_CurvesHasher> allCurves;
1148           const int aSubNum = aComposite->numberOfSubs();
1149           for(int a = 0; a < aSubNum; a++) {
1150             int aSubID = aComposite->subFeatureId(a);
1151             if (anIDs.find(aSubID) != anIDs.end()) {
1152               FeaturePtr aSub = aComposite->subFeature(a);
1153               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1154               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
1155               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
1156                 ResultConstructionPtr aConstr =
1157                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1158                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
1159                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
1160                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
1161                   if (!anEdge.IsNull()) {
1162                     Standard_Real aFirst, aLast;
1163                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1164                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1165                   }
1166                 }
1167               }
1168             }
1169           }
1170           std::shared_ptr<GeomAPI_Shape> aFoundFW =
1171             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1172           if (aFoundFW.get()) {
1173             theShapeToBeSelected = aFoundFW;
1174             return true;
1175           }
1176         }
1177       }
1178     }
1179   } else if (aSelection.IsNull() && aN >= 2 && aType == TopAbs_VERTEX) {
1180     // support of shape name as intersection separated by "&"
1181     static std::string anEdgeType = "edge"; // for now it works only with su-edges
1182     std::list<std::string>::iterator aSubNames = aListofNames.begin();
1183     TopTools_ListOfShape aSubsList;
1184     for(; aSubNames != aListofNames.end(); aSubNames++) {
1185       std::string aSubName = *aSubNames;
1186       std::shared_ptr<GeomAPI_Shape> aSubShapeFound;
1187       std::shared_ptr<ModelAPI_Result> aContextFound;
1188       if (selectSubShape(anEdgeType, aSubName, theDoc, aSubShapeFound, aContextFound)) {
1189         if (aSubShapeFound.get())
1190           aSubsList.Append(aSubShapeFound->impl<TopoDS_Shape>());
1191       }
1192     }
1193     aSelection = findCommonShape(TopAbs_VERTEX, aSubsList);
1194   }
1195   if (!aSelection.IsNull()) {
1196     // Select it (must be after N=0 checking,
1197     // since for simple constructions the shape must be null)
1198     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1199     aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1200     theShapeToBeSelected = aShapeToBeSelected;
1201     theCont = aCont;
1202     return true;
1203   }
1204
1205   return false;
1206 }