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