]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
84d4c29741c0f72c2164c07bac7915cfb4d6e35b
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.cpp
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <ModelAPI_Feature.h>
14 #include <ModelAPI_ResultBody.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_ResultPart.h>
17 #include <ModelAPI_CompositeFeature.h>
18 #include <ModelAPI_Tools.h>
19 #include <GeomAPI_Shape.h>
20 #include <GeomAPI_PlanarEdges.h>
21 #include <Events_Error.h>
22
23 #include <TNaming_Selector.hxx>
24 #include <TNaming_NamedShape.hxx>
25 #include <TNaming_Tool.hxx>
26 #include <TNaming_Builder.hxx>
27 #include <TNaming_Localizer.hxx>
28 #include <TopoDS_Shape.hxx>
29 #include <TopoDS_Compound.hxx>
30 #include <TDataStd_IntPackedMap.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_UAttribute.hxx>
33 #include <TDataStd_Name.hxx>
34 #include <TopTools_MapOfShape.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_MapIteratorOfMapOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <NCollection_DataMap.hxx>
39 #include <TopExp_Explorer.hxx>
40 #include <TDF_LabelMap.hxx>
41 #include <BRep_Tool.hxx>
42 #include <BRep_Builder.hxx>
43 #include <TopoDS_Edge.hxx>
44 #include <TopoDS.hxx>
45 #include <TopExp.hxx>
46 #include <TColStd_MapOfTransient.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
50 #include <gp_Pnt.hxx>
51 #include <Precision.hxx>
52 #include <TDF_ChildIterator.hxx>
53 #include <TDF_ChildIDIterator.hxx>
54 #include <TDataStd_Name.hxx>
55 #include <TopAbs_ShapeEnum.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <TNaming_Iterator.hxx>
58 #include <BRep_Builder.hxx>
59 using namespace std;
60 //#define DEB_NAMING 1
61 #ifdef DEB_NAMING
62 #include <BRepTools.hxx>
63 #endif
64 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
65 /// (multiplied by the index of the edge)
66 static const int kSTART_VERTEX_DELTA = 1000000;
67 // identifier that there is simple reference: selection equals to context
68 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
69 // simple reference in the construction
70 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
71 // reference to Part sub-object
72 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
73 // selection is invalid after recomputation
74 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
75
76 // on this label is stored:
77 // TNaming_NamedShape - selected shape
78 // TNaming_Naming - topological selection information (for the body)
79 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
80 // TDataStd_Integer - type of the selected shape (for construction)
81 // TDF_Reference - from ReferenceAttribute, the context
82 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
83   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
84 {
85   if (theTemporarily) { // just keep the stored without DF update
86     myTmpContext = theContext;
87     myTmpSubShape = theSubShape;
88     owner()->data()->sendAttributeUpdated(this);
89     return;
90   } else {
91     myTmpContext.reset();
92     myTmpSubShape.reset();
93   }
94
95   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
96   bool isOldContext = theContext == myRef.value();
97   bool isOldShape = isOldContext &&
98     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
99   if (isOldShape) return; // shape is the same, so context is also unchanged
100   // update the referenced object if needed
101   if (!isOldContext) {
102     ResultCompSolidPtr anOwner = ModelAPI_Tools::compSolidOwner(theContext);
103     if (anOwner.get())
104       myRef.setValue(anOwner);
105     else
106       myRef.setValue(theContext);
107   }
108
109   // do noth use naming if selected shape is result shape itself, but not sub-shape
110   TDF_Label aSelLab = selectionLabel();
111   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
112   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
113   aSelLab.ForgetAttribute(kINVALID_SELECTION);
114
115   bool isDegeneratedEdge = false;
116   // do not use the degenerated edge as a shape, a null context and shape is used in the case
117   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
118     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
119     if (aSubShape.ShapeType() == TopAbs_EDGE)
120       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
121   }
122   if (!theContext.get() || isDegeneratedEdge) {
123     // to keep the reference attribute label
124     TDF_Label aRefLab = myRef.myRef->Label();
125     aSelLab.ForgetAllAttributes(true);
126     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
127     return;
128   }
129   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
130     // do not select the whole shape for body:it is already must be in the data framework
131     // equal and null selected objects mean the same: object is equal to context,
132     if (theContext->shape().get() && 
133         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
134       aSelLab.ForgetAllAttributes(true);
135       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
136     } else {
137       selectBody(theContext, theSubShape);
138     }
139   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
140     if (!theSubShape.get()) {
141       // to sub, so the whole result is selected
142       aSelLab.ForgetAllAttributes(true);
143       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
144       ResultConstructionPtr aConstruction = 
145         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
146       if (aConstruction->isInfinite()) {
147         // For correct naming selection, put the shape into the naming structure.
148         // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
149         TNaming_Builder aBuilder(aSelLab);
150         aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
151         std::shared_ptr<Model_Document> aMyDoc = 
152           std::dynamic_pointer_cast<Model_Document>(owner()->document());
153         std::string aName = theContext->data()->name();
154         aMyDoc->addNamingName(aSelLab, aName);
155         TDataStd_Name::Set(aSelLab, aName.c_str());
156       } else {  // for sketch the naming is needed in DS
157         BRep_Builder aCompoundBuilder;
158         TopoDS_Compound aComp;
159         aCompoundBuilder.MakeCompound(aComp);
160         for(int a = 0; a < aConstruction->facesNum(); a++) {
161           TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
162           aCompoundBuilder.Add(aComp, aFace);
163         }
164         std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
165         aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
166         selectConstruction(theContext, aShape);
167       }
168     } else {
169       selectConstruction(theContext, theSubShape);
170     }
171   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
172     aSelLab.ForgetAllAttributes(true);
173     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
174     selectPart(theContext, theSubShape);
175   }
176   //the attribute initialized state should be changed by sendAttributeUpdated only
177   //myIsInitialized = true;
178
179   owner()->data()->sendAttributeUpdated(this);
180
181   std::string aSelName = namingName();
182   if(!aSelName.empty())
183     TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
184 }
185
186 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
187 {
188   if (myTmpContext.get() || myTmpSubShape.get()) {
189     return myTmpSubShape;
190   }
191
192   std::shared_ptr<GeomAPI_Shape> aResult;
193   TDF_Label aSelLab = selectionLabel();
194   if (aSelLab.IsAttribute(kINVALID_SELECTION))
195     return aResult;
196
197   if (myRef.isInitialized()) {
198     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
199       ResultPtr aContext = context();
200       if (!aContext.get()) 
201         return aResult; // empty result
202       return aContext->shape();
203     }
204     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
205         return aResult; // empty result
206     }
207     if (aSelLab.IsAttribute(kPART_REF_ID)) {
208       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
209       if (!aPart.get() || !aPart->isActivated())
210         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
211       Handle(TDataStd_Integer) anIndex;
212       if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
213         if (anIndex->Get()) { // special selection attribute was created, use it
214           return aPart->selectionValue(anIndex->Get());
215         } else { // face with name is already in the data model, so try to take it by name
216           Handle(TDataStd_Name) aName;
217           if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
218             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
219             std::size_t aPartEnd = aSubShapeName.find('/');
220             if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
221               string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
222               int anIndex;
223               std::string aType; // to reuse already existing selection the type is not needed
224               return aPart->shapeInPart(aNameInPart, aType, anIndex);
225             }
226           }
227         }
228       }
229     }
230
231     Handle(TNaming_NamedShape) aSelection;
232     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
233       TopoDS_Shape aSelShape = aSelection->Get();
234       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
235       aResult->setImpl(new TopoDS_Shape(aSelShape));
236     } else { // for simple construction element: just shape of this construction element
237       ResultConstructionPtr aConstr = 
238         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
239       if (aConstr) {
240         return aConstr->shape();
241       }
242     }
243   }
244   return aResult;
245 }
246
247 bool Model_AttributeSelection::isInvalid()
248 {
249   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
250 }
251
252 bool Model_AttributeSelection::isInitialized()
253 {
254   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checkings if it is initialized
255     std::shared_ptr<GeomAPI_Shape> aResult;
256     if (myRef.isInitialized()) {
257       TDF_Label aSelLab = selectionLabel();
258       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
259         ResultPtr aContext = context();
260         return aContext.get() != NULL;
261       }
262       if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
263           return true;
264       }
265
266       Handle(TNaming_NamedShape) aSelection;
267       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
268         return !aSelection->Get().IsNull();
269       } else { // for simple construction element: just shape of this construction element
270         ResultConstructionPtr aConstr = 
271           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
272         if (aConstr.get()) {
273           return aConstr->shape().get() != NULL;
274         }
275       }
276     }
277   }
278   return false;
279 }
280
281 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
282   : myRef(theLabel)
283 {
284   myIsInitialized = myRef.isInitialized();
285 }
286
287 void Model_AttributeSelection::setID(const std::string theID)
288 {
289   myRef.setID(theID);
290   ModelAPI_AttributeSelection::setID(theID);
291 }
292
293 ResultPtr Model_AttributeSelection::context() {
294   if (myTmpContext.get() || myTmpSubShape.get()) {
295     return myTmpContext;
296   }
297
298   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
299   // for parts there could be same-data result, so take the last enabled
300   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
301     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
302     for(int a = aSize - 1; a >= 0; a--) {
303       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
304       if (aPart.get() && aPart->data() == aResult->data()) {
305         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
306         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
307         // check that this result is not this-feature result (it is forbidden t oselect itself)
308         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
309           return aPartResult;
310         }
311       }
312     }
313   }
314   return aResult;
315 }
316
317
318 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
319 {
320   ModelAPI_AttributeSelection::setObject(theObject);
321   myRef.setObject(theObject);
322 }
323
324 TDF_LabelMap& Model_AttributeSelection::scope()
325 {
326   if (myScope.IsEmpty()) { // create a new scope if not yet done
327     // gets all featueres with named shapes that are bofore this feature label (before in history)
328     DocumentPtr aMyDoc = owner()->document();
329     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
330     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
331     bool aMePassed = false;
332     CompositeFeaturePtr aComposite = 
333       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
334     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
335     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
336     if (aFeature.get()) {
337       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
338       if (aCompositeOwner.get()) {
339          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
340       }
341     }
342     // for group Scope is not limitet: this is always up to date objects
343     bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
344     for(; aFIter != allFeatures.end(); aFIter++) {
345       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
346         aMePassed = true;
347         continue;
348       }
349       if (isGroup) aMePassed = false;
350       bool isInScope = !aMePassed;
351       if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
352         if (aComposite->isSub(*aFIter))
353           isInScope = true;
354       }
355       // remove the composite-owner of this feature (sketch in extrusion-cut)
356       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
357         isInScope = false;
358
359       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
360         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
361           (*aFIter)->data())->label().Father();
362         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
363         for(; aNSIter.More(); aNSIter.Next()) {
364           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
365           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
366             myScope.Add(aNS->Label());
367           }
368         }
369       }
370     }
371   }
372   return myScope;
373 }
374
375 /// produces theEdge orientation relatively to theContext face
376 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
377 {
378   if (theContext.ShapeType() != TopAbs_FACE)
379     return 0;
380   TopoDS_Face aContext = TopoDS::Face(theContext);
381   if (theEdge.Orientation() == TopAbs_FORWARD) 
382     return 1;
383   if (theEdge.Orientation() == TopAbs_REVERSED) 
384     return -1;
385   return 0; // unknown
386 }
387
388 /// Sets the invalid flag if flag is false, or removes it if "true"
389 /// Returns theFlag
390 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
391   if (theFlag) {
392     theLab.ForgetAttribute(kINVALID_SELECTION);
393   } else {
394     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
395   }
396   return theFlag;
397 }
398
399 bool Model_AttributeSelection::update()
400 {
401   TDF_Label aSelLab = selectionLabel();
402   ResultPtr aContext = context();
403   if (!aContext.get()) 
404     return setInvalidIfFalse(aSelLab, false);
405   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
406     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
407   }
408   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
409     // if there is a sketch, the sketch-naming must be updated
410     ResultConstructionPtr aConstruction = 
411       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
412     if (!aConstruction->isInfinite()) {
413       BRep_Builder aCompoundBuilder;
414       TopoDS_Compound aComp;
415       aCompoundBuilder.MakeCompound(aComp);
416       for(int a = 0; a < aConstruction->facesNum(); a++) {
417         TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
418         aCompoundBuilder.Add(aComp, aFace);
419       }
420       std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
421       aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
422       selectConstruction(aContext, aShape);
423     }
424     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
425   }
426
427   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
428     std::shared_ptr<GeomAPI_Shape> aNoSelection;
429     return setInvalidIfFalse(aSelLab, selectPart(aContext, aNoSelection, true));
430   }
431
432   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
433     // body: just a named shape, use selection mechanism from OCCT
434     TNaming_Selector aSelector(aSelLab);
435     bool aResult = aSelector.Solve(scope()) == Standard_True;
436     owner()->data()->sendAttributeUpdated(this);
437     return setInvalidIfFalse(aSelLab, aResult);
438   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
439     // construction: identification by the results indexes, recompute faces and
440     // take the face that more close by the indexes
441     ResultConstructionPtr aConstructionContext = 
442       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
443     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
444     // sketch sub-element
445     if (aConstructionContext && 
446         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
447     {
448       TDF_Label aLab = myRef.myRef->Label();
449       // getting a type of selected shape
450       Handle(TDataStd_Integer) aTypeAttr;
451       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
452         return setInvalidIfFalse(aSelLab, false);
453       }
454       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
455       // selected indexes will be needed in each "if"
456       Handle(TDataStd_IntPackedMap) aSubIds;
457       std::shared_ptr<GeomAPI_Shape> aNewSelected;
458       bool aNoIndexes = 
459         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
460       // for now working only with composite features
461       CompositeFeaturePtr aComposite = 
462         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
463       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
464         return setInvalidIfFalse(aSelLab, false);
465       }
466
467       if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
468         // If this is a wire with plane defined thin it is a sketch-like object
469         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
470           return setInvalidIfFalse(aSelLab, false);
471         // if there is no edges indexes, any face can be used: take the first
472         std::shared_ptr<GeomAPI_Shape> aNewSelected;
473         if (aNoIndexes) {
474           aNewSelected = aConstructionContext->face(0);
475         } else { // searching for most looks-like initial face by the indexes
476           // prepare edges of the current resut for the fast searching
477           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
478           const int aSubNum = aComposite->numberOfSubs();
479           for(int a = 0; a < aSubNum; a++) {
480             int aSubID = aComposite->subFeatureId(a);
481             if (aSubIds->Contains(aSubID)) {
482               FeaturePtr aSub = aComposite->subFeature(a);
483               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
484               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
485               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
486                 ResultConstructionPtr aConstr = 
487                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
488                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
489                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
490                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
491                   if (!anEdge.IsNull()) {
492                     Standard_Real aFirst, aLast;
493                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
494                     // searching for orientation information
495                     int anOrient = 0;
496                     Handle(TDataStd_Integer) anInt;
497                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
498                       anOrient = anInt->Get();
499                     }
500                     allCurves.Bind(aCurve, anOrient);
501                   }
502                 }
503               }
504             }
505           }
506           int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
507           int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
508           for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
509             int aFound = 0, aNotFound = 0, aSameOrientation = 0;
510             TopoDS_Face aFace = 
511               TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
512             TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
513             TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
514             for(; anEdgesExp.More(); anEdgesExp.Next()) {
515               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
516               if (!anEdge.IsNull()) {
517                 Standard_Real aFirst, aLast;
518                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
519                 if (alreadyProcessed.Contains(aCurve))
520                   continue;
521                 alreadyProcessed.Add(aCurve);
522                 if (allCurves.IsBound(aCurve)) {
523                   aFound++;
524                   int anOrient = allCurves.Find(aCurve);
525                   if (anOrient != 0) {  // extra comparision score is orientation
526                     if (edgeOrientation(aFace, anEdge) == anOrient)
527                       aSameOrientation++;
528                   }
529                 } else {
530                   aNotFound++;
531                 }
532               }
533             }
534             if (aFound + aNotFound != 0) {
535               if (aFound > aBestFound || 
536                   (aFound == aBestFound && aSameOrientation > aBestOrient)) {
537                 aBestFound = aFound;
538                 aBestOrient = aSameOrientation;
539                 aNewSelected = aConstructionContext->face(aFaceIndex);
540               }
541             }
542           }
543         }
544         if (aNewSelected) { // store this new selection
545           selectConstruction(aContext, aNewSelected);
546           owner()->data()->sendAttributeUpdated(this);
547           return setInvalidIfFalse(aSelLab, true);
548         } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
549           TNaming_Builder anEmptyBuilder(selectionLabel());
550           return setInvalidIfFalse(aSelLab, false);
551         }
552       } else if (aShapeType == TopAbs_EDGE) {
553         // just reselect the edge by the id
554         const int aSubNum = aComposite->numberOfSubs();
555         for(int a = 0; a < aSubNum; a++) {
556           // if aSubIds take any, the first appropriate
557           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
558             // found the appropriate feature
559             FeaturePtr aFeature = aComposite->subFeature(a);
560             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
561               aFeature->results().cbegin();
562             for(;aResIter != aFeature->results().cend(); aResIter++) {
563               ResultConstructionPtr aRes = 
564                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
565               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
566                 selectConstruction(aContext, aRes->shape());
567                 owner()->data()->sendAttributeUpdated(this);
568                 return setInvalidIfFalse(aSelLab, true);
569               }
570             }
571           }
572         }
573       } else if (aShapeType == TopAbs_VERTEX) {
574         // just reselect the vertex by the id of edge
575         const int aSubNum = aComposite->numberOfSubs();
576         for(int a = 0; a < aSubNum; a++) {
577           // if aSubIds take any, the first appropriate
578           int aFeatureID = aComposite->subFeatureId(a);
579           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
580             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
581             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
582               // searching for deltas
583               int aVertexNum = 0;
584               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
585               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
586               // found the feature with appropriate edge
587               FeaturePtr aFeature = aComposite->subFeature(a);
588               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
589                 aFeature->results().cbegin();
590               for(;aResIter != aFeature->results().cend(); aResIter++) {
591                 ResultConstructionPtr aRes = 
592                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
593                 if (aRes && aRes->shape()) {
594                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
595                     selectConstruction(aContext, aRes->shape());
596                     owner()->data()->sendAttributeUpdated(this);
597                     return setInvalidIfFalse(aSelLab, true);
598                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
599                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
600                     int aVIndex = 1;
601                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
602                       if (aVIndex == aVertexNum) { // found!
603                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
604                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
605                         selectConstruction(aContext, aVertex);
606                         owner()->data()->sendAttributeUpdated(this);
607                         return setInvalidIfFalse(aSelLab, true);
608                       }
609                       aVIndex++;
610                     }
611                   }
612                 }
613               }
614           }
615         }
616       }
617     } else { // simple construction element: the selected is that needed
618       selectConstruction(aContext, aContext->shape());
619       owner()->data()->sendAttributeUpdated(this);
620       return setInvalidIfFalse(aSelLab, true);
621     }
622   }
623   return setInvalidIfFalse(aSelLab, false); // unknown case
624 }
625
626
627 void Model_AttributeSelection::selectBody(
628   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
629 {
630   // perform the selection
631   TNaming_Selector aSel(selectionLabel());
632   TopoDS_Shape aContext;
633
634   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
635   if (aBody) {
636     aContext = aBody->shape()->impl<TopoDS_Shape>();
637   } else {
638     ResultPtr aResult = 
639       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
640     if (aResult) {
641       aContext = aResult->shape()->impl<TopoDS_Shape>();
642     } else {
643       Events_Error::send("A result with shape is expected");
644       return;
645     }
646   }
647   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
648   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
649   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
650   if (aFeatureOwner.get())
651     aFeatureOwner->eraseResults();
652   if (!aContext.IsNull()) {
653     aSel.Select(aNewShape, aContext); 
654   }
655 }
656
657 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
658 /// if theID is zero, 
659 /// theOrientation is additional information about the positioning of edge relatively to face
660 ///    it is stored in the integer attribute of the edge sub-label: 
661 ///    -1 is out, 1 is in, 0 is not needed
662 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
663   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
664   std::string theAdditionalName, std::map<int, int>& theOrientations,
665   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
666   const int theOrientation = 0)
667 {
668   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
669   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
670     TDataStd_Integer::Set(aLab, theOrientation);
671   }
672   TNaming_Builder aBuilder(aLab);
673   aBuilder.Generated(theShape);
674   std::stringstream aName;
675   aName<<theContextFeature->name()<<"/";
676   if (!theAdditionalName.empty())
677     aName<<theAdditionalName<<"/";
678   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
679   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
680   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
681
682   if (theRefs.IsNull()) {
683     aName<<theID;
684     if (theOrientation == 1)
685       aName<<"f";
686     else if (theOrientation == -1)
687       aName<<"r";
688   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
689     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
690     for(; aRef.More(); aRef.Next()) {
691       aName<<"-"<<aRef.Key();
692       if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
693         if (theOrientations[aRef.Key()] == 1)
694           aName<<"f";
695         else if (theOrientations[aRef.Key()] == -1)
696           aName<<"r";
697       }
698     }
699   }
700
701   theDoc->addNamingName(aLab, aName.str());
702   TDataStd_Name::Set(aLab, aName.str().c_str());
703 }
704
705 void Model_AttributeSelection::selectConstruction(
706   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
707 {
708   std::shared_ptr<Model_Document> aMyDoc = 
709     std::dynamic_pointer_cast<Model_Document>(owner()->document());
710   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
711   CompositeFeaturePtr aComposite = 
712     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
713   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
714   if (!aComposite || aComposite->numberOfSubs() == 0) {
715     // saving of context is enough: result construction contains exactly the needed shape
716     TNaming_Builder aBuilder(selectionLabel());
717     aBuilder.Generated(aSubShape);
718     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
719     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
720     return;
721   }
722   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
723   TDF_Label aLab = myRef.myRef->Label();
724   // identify the reuslts of sub-object of the composite by edges
725   // save type of the selected shape in integer attribute
726   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
727   TDataStd_Integer::Set(aLab, (int)aShapeType);
728   gp_Pnt aVertexPos;
729   TColStd_MapOfTransient allCurves;
730   if (aShapeType == TopAbs_VERTEX) { // compare positions
731     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
732   } else { 
733     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
734       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
735       Standard_Real aFirst, aLast;
736       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
737       allCurves.Add(aCurve);
738     }
739   }
740   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
741   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
742   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
743   aRefs->Clear();
744   const int aSubNum = aComposite->numberOfSubs();
745   for(int a = 0; a < aSubNum; a++) {
746     FeaturePtr aSub = aComposite->subFeature(a);
747     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
748     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
749     // there may be many shapes (circle and center): register if at least one is in selection
750     for(; aRes != aResults.cend(); aRes++) {
751       ResultConstructionPtr aConstr = 
752         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
753       if (!aConstr->shape()) {
754         continue;
755       }
756       if (aShapeType == TopAbs_VERTEX) {
757         if (aConstr->shape()->isVertex()) { // compare vertices positions
758           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
759           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
760           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
761             aRefs->Add(aComposite->subFeatureId(a));
762           }
763         } else { // get first or last vertex of the edge: last is stored with negative sign
764           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
765           int aDelta = kSTART_VERTEX_DELTA;
766           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
767             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
768             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
769               aRefs->Add(aDelta + aComposite->subFeatureId(a));
770               break;
771             }
772             aDelta += kSTART_VERTEX_DELTA;
773           }
774         }
775       } else {
776         if (aConstr->shape()->isEdge()) {
777           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
778           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
779           if (!anEdge.IsNull()) {
780             Standard_Real aFirst, aLast;
781             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
782             if (allCurves.Contains(aCurve)) {
783               int anID = aComposite->subFeatureId(a);
784               aRefs->Add(anID);
785               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
786                 // add edges to sub-label to support naming for edges selection
787                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
788                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
789                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
790                   Standard_Real aFirst, aLast;
791                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
792                   if (aFaceCurve == aCurve) {
793                     int anOrient = edgeOrientation(aSubShape, anEdge);
794                     anOrientations[anID] = anOrient;
795                     registerSubShape(
796                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
797                       Handle(TDataStd_IntPackedMap)(), anOrient);
798                   }
799                 }
800               } else { // put vertices of the selected edge to sub-labels
801                 // add edges to sub-label to support naming for edges selection
802                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
803                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
804                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
805                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
806
807                   std::stringstream anAdditionalName; 
808                   registerSubShape(
809                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
810                 }
811               }
812             }
813           }
814         }
815       }
816     }
817   }
818   // store the selected as primitive
819   TNaming_Builder aBuilder(selectionLabel());
820   aBuilder.Generated(aSubShape);
821     registerSubShape(
822       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs); 
823 }
824
825 bool Model_AttributeSelection::selectPart(
826   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
827   const bool theUpdate)
828 {
829   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
830   if (!aPart.get() || !aPart->isActivated())
831     return true; // postponed naming
832   if (theUpdate) {
833     Handle(TDataStd_Integer) anIndex;
834     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
835       if (anIndex->Get() > 0) {
836         // update the selection by index
837         return aPart->updateInPart(anIndex->Get());
838       } else {
839         return true; // nothing to do, referencing just by name
840       }
841     }
842     return true; // nothing to do, referencing just by name
843   }
844   // store the shape (in case part is not loaded it should be usefull
845   TopoDS_Shape aShape;
846   std::string aName = theContext->data()->name();
847   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
848     aShape = theContext->shape()->impl<TopoDS_Shape>();
849   } else {
850     aShape = theSubShape->impl<TopoDS_Shape>();
851     int anIndex;
852     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
853     TDataStd_Integer::Set(selectionLabel(), anIndex);
854   }
855   TNaming_Builder aBuilder(selectionLabel());
856   aBuilder.Select(aShape, aShape);
857   // identify by name in the part
858   TDataStd_Name::Set(selectionLabel(), aName.c_str());
859   return !aName.empty();
860 }
861
862 TDF_Label Model_AttributeSelection::selectionLabel()
863 {
864   return myRef.myRef->Label().FindChild(1);
865 }
866
867 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
868 {
869   std::string aName("");
870   if(!this->isInitialized())
871     return !theDefaultName.empty() ? theDefaultName : aName;
872   Handle(TDataStd_Name) anAtt;
873   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
874     aName = TCollection_AsciiString(anAtt->Get()).ToCString();
875     return aName;
876   }
877
878   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
879   ResultPtr aCont = context();
880
881   Model_SelectionNaming aSelNaming(selectionLabel());
882   return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
883 }
884
885 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
886 void Model_AttributeSelection::selectSubShape(
887   const std::string& theType, const std::string& theSubShapeName)
888 {
889   if(theSubShapeName.empty() || theType.empty()) return;
890
891   // check this is Part-name: 2 delimiters in the name
892   std::size_t aPartEnd = theSubShapeName.find('/');
893   if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
894     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
895     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
896     if (aFound.get()) { // found such part, so asking it for the name
897       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
898       string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
899       int anIndex;
900       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
901       if (aSelected.get()) {
902         setValue(aPart, aSelected);
903         TDataStd_Integer::Set(selectionLabel(), anIndex);
904         return;
905       }
906     }
907   }
908
909   Model_SelectionNaming aSelNaming(selectionLabel());
910   std::shared_ptr<Model_Document> aDoc = 
911     std::dynamic_pointer_cast<Model_Document>(owner()->document());
912   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
913   ResultPtr aCont;
914   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
915     setValue(aCont, aShapeToBeSelected);
916   }
917 }
918
919 int Model_AttributeSelection::Id()
920 {
921   int anID = 0;
922   std::shared_ptr<GeomAPI_Shape> aSelection = value();
923   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
924   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
925   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
926   // searching for the latest main shape
927   if (aSelection && !aSelection->isNull() &&
928     aContext   && !aContext->isNull())
929   {
930     std::shared_ptr<Model_Document> aDoc =
931       std::dynamic_pointer_cast<Model_Document>(context()->document());
932     if (aDoc.get()) {
933       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
934       if (!aNS.IsNull()) {
935         aMainShape = TNaming_Tool::CurrentShape(aNS);
936       }
937     }
938
939     TopTools_IndexedMapOfShape aSubShapesMap;
940     TopExp::MapShapes(aMainShape, aSubShapesMap);
941     anID = aSubShapesMap.FindIndex(aSubShape);
942   }
943   return anID;
944 }