]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Merge branch 'Dev_0.6.1' of newgeom:newgeom into Dev_0.6.1
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.h
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 <ModelAPI_Feature.h>
12 #include <ModelAPI_ResultBody.h>
13 #include <ModelAPI_ResultConstruction.h>
14 #include <ModelAPI_CompositeFeature.h>
15 #include <GeomAPI_Shape.h>
16 #include <GeomAPI_PlanarEdges.h>
17 #include <GeomAlgoAPI_SketchBuilder.h>
18 #include <Events_Error.h>
19
20 #include <TNaming_Selector.hxx>
21 #include <TNaming_NamedShape.hxx>
22 #include <TNaming_Tool.hxx>
23 #include <TNaming_Builder.hxx>
24 #include <TNaming_Localizer.hxx>
25 #include <TopoDS_Shape.hxx>
26 #include <TopoDS_Compound.hxx>
27 #include <TDataStd_IntPackedMap.hxx>
28 #include <TDataStd_Integer.hxx>
29 #include <TDataStd_UAttribute.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TopTools_MapOfShape.hxx>
32 #include <TopTools_IndexedMapOfShape.hxx>
33 #include <TopTools_MapIteratorOfMapOfShape.hxx>
34 #include <TopTools_ListOfShape.hxx>
35 #include <TopExp_Explorer.hxx>
36 #include <TDF_LabelMap.hxx>
37 #include <BRep_Tool.hxx>
38 #include <BRep_Builder.hxx>
39 #include <TopoDS_Edge.hxx>
40 #include <TopoDS.hxx>
41 #include <TopExp.hxx>
42 #include <TColStd_MapOfTransient.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
46 #include <gp_Pnt.hxx>
47 #include <Precision.hxx>
48 #include <TDF_ChildIterator.hxx>
49 #include <TDF_ChildIDIterator.hxx>
50 #include <TDataStd_Name.hxx>
51 #include <TopAbs_ShapeEnum.hxx>
52 #include <TopoDS_Iterator.hxx>
53 using namespace std;
54 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
55 /// (multiplied by the index of the edge)
56 static const int kSTART_VERTEX_DELTA = 1000000;
57 // identifier that there is simple reference: selection equals to context
58 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
59
60 // on this label is stored:
61 // TNaming_NamedShape - selected shape
62 // TNaming_Naming - topological selection information (for the body)
63 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
64 // TDataStd_Integer - type of the selected shape (for construction)
65 // TDF_Reference - from ReferenceAttribute, the context
66
67 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
68   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
69 {
70   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
71   bool isOldShape = 
72     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
73   if (isOldShape) return; // shape is the same, so context is also unchanged
74   // update the referenced object if needed
75   bool isOldContext = theContext == myRef.value();
76
77
78   if (!isOldContext)
79     myRef.setValue(theContext);
80
81   // do noth use naming if selected shape is result shape itself, but not sub-shape
82   TDF_Label aSelLab = selectionLabel();
83   if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
84     aSelLab.ForgetAllAttributes(true);
85     TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
86   } else {
87     aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
88     if (theContext->groupName() == ModelAPI_ResultBody::group())
89       selectBody(theContext, theSubShape);
90     else if (theContext->groupName() == ModelAPI_ResultConstruction::group())
91       selectConstruction(theContext, theSubShape);
92   }
93
94   std::string aSelName = namingName();
95   if(!aSelName.empty())
96           TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
97
98   myIsInitialized = true;
99   owner()->data()->sendAttributeUpdated(this);
100 }
101
102 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
103 {
104   std::shared_ptr<GeomAPI_Shape> aResult;
105   if (myIsInitialized) {
106     TDF_Label aSelLab = selectionLabel();
107     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
108       ResultPtr aContext = context();
109       if (!aContext.get()) 
110         return aResult; // empty result
111       return aContext->shape();
112     }
113
114     Handle(TNaming_NamedShape) aSelection;
115     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
116       TopoDS_Shape aSelShape = aSelection->Get();
117       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
118       aResult->setImpl(new TopoDS_Shape(aSelShape));
119     } else { // for simple construction element: just shape of this construction element
120       ResultConstructionPtr aConstr = 
121         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
122       if (aConstr) {
123         return aConstr->shape();
124       }
125     }
126   }
127   return aResult;
128 }
129
130 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
131   : myRef(theLabel)
132 {
133   myIsInitialized = myRef.isInitialized();
134 }
135
136 ResultPtr Model_AttributeSelection::context() {
137   return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
138 }
139
140
141 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
142 {
143   ModelAPI_AttributeSelection::setObject(theObject);
144   myRef.setObject(theObject);
145 }
146
147 TDF_LabelMap& Model_AttributeSelection::scope()
148 {
149   if (myScope.IsEmpty()) { // create a new scope if not yet done
150     // gets all labels with named shapes that are bofore this feature label (before in history)
151     TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
152       owner()->data())->label().Father();
153     int aFeatureID = aFeatureLab.Tag();
154     TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
155     for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
156       if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
157         break;
158       TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
159       for(; aNSIter.More(); aNSIter.Next()) {
160         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
161         if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
162           myScope.Add(aNS->Label());
163         }
164       }
165     }
166   }
167   return myScope;
168 }
169
170 bool Model_AttributeSelection::update()
171 {
172   ResultPtr aContext = context();
173   if (!aContext.get()) return false;
174   TDF_Label aSelLab = selectionLabel();
175   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
176     return aContext->shape() && !aContext->shape()->isNull();
177   }
178
179   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
180     // body: just a named shape, use selection mechanism from OCCT
181     TNaming_Selector aSelector(aSelLab);
182     bool aResult = aSelector.Solve(scope()) == Standard_True;
183     owner()->data()->sendAttributeUpdated(this);
184     return aResult;
185   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
186     // construction: identification by the results indexes, recompute faces and
187     // take the face that more close by the indexes
188     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr = 
189       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
190       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
191     if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
192       TDF_Label aLab = myRef.myRef->Label();
193       // getting a type of selected shape
194       Handle(TDataStd_Integer) aTypeAttr;
195       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
196         return false;
197       }
198       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
199       // selected indexes will be needed in each "if"
200       Handle(TDataStd_IntPackedMap) aSubIds;
201       std::shared_ptr<GeomAPI_Shape> aNewSelected;
202       bool aNoIndexes = 
203         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
204       // for now working only with composite features
205       FeaturePtr aContextFeature = aContext->document()->feature(aContext);
206       CompositeFeaturePtr aComposite = 
207         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
208       if (!aComposite || aComposite->numberOfSubs() == 0) {
209         return false;
210       }
211
212       if (aShapeType == TopAbs_FACE) {
213         // If this is a wire with plane defined thin it is a sketch-like object
214         std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
215         GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
216           aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
217         if (aFaces.empty()) // no faces, update can not work correctly
218           return false;
219         // if there is no edges indexes, any face can be used: take the first
220         std::shared_ptr<GeomAPI_Shape> aNewSelected;
221         if (aNoIndexes) {
222           aNewSelected = *(aFaces.begin());
223         } else { // searching for most looks-like initial face by the indexes
224           // prepare edges of the current resut for the fast searching
225           TColStd_MapOfTransient allCurves;
226           const int aSubNum = aComposite->numberOfSubs();
227           for(int a = 0; a < aSubNum; a++) {
228             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
229               FeaturePtr aSub = aComposite->subFeature(a);
230               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
231               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
232               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
233                 ResultConstructionPtr aConstr = 
234                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
235                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
236                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
237                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
238                   if (!anEdge.IsNull()) {
239                     Standard_Real aFirst, aLast;
240                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
241                     allCurves.Add(aCurve);
242                   }
243                 }
244               }
245             }
246           }
247           // iterate new result faces and searching for these edges
248           std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
249           double aBestFound = 0; // best percentage of found edges
250           for(; aFacesIter != aFaces.end(); aFacesIter++) {
251             int aFound = 0, aNotFound = 0;
252             TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
253             for(; anEdgesExp.More(); anEdgesExp.Next()) {
254               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
255               if (!anEdge.IsNull()) {
256                 Standard_Real aFirst, aLast;
257                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
258                 if (allCurves.Contains(aCurve)) {
259                   aFound++;
260                 } else {
261                   aNotFound++;
262                 }
263               }
264             }
265             if (aFound + aNotFound != 0) {
266               double aPercentage = double(aFound) / double(aFound + aNotFound);
267               if (aPercentage > aBestFound) {
268                 aBestFound = aPercentage;
269                 aNewSelected = *aFacesIter;
270               }
271             }
272           }
273         }
274         if (aNewSelected) { // store this new selection
275           selectConstruction(aContext, aNewSelected);
276           owner()->data()->sendAttributeUpdated(this);
277           return true;
278         }
279       } else if (aShapeType == TopAbs_EDGE) {
280         // just reselect the edge by the id
281         const int aSubNum = aComposite->numberOfSubs();
282         for(int a = 0; a < aSubNum; a++) {
283           // if aSubIds take any, the first appropriate
284           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
285             // found the appropriate feature
286             FeaturePtr aFeature = aComposite->subFeature(a);
287             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
288               aFeature->results().cbegin();
289             for(;aResIter != aFeature->results().cend(); aResIter++) {
290               ResultConstructionPtr aRes = 
291                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
292               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
293                 selectConstruction(aContext, aRes->shape());
294                 owner()->data()->sendAttributeUpdated(this);
295                 return true;
296               }
297             }
298           }
299         }
300       } else if (aShapeType == TopAbs_VERTEX) {
301         // just reselect the vertex by the id of edge
302         const int aSubNum = aComposite->numberOfSubs();
303         for(int a = 0; a < aSubNum; a++) {
304           // if aSubIds take any, the first appropriate
305           int aFeatureID = aComposite->subFeatureId(a);
306           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
307               aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
308               aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
309             // searching for deltas
310             int aVertexNum = 0;
311             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
312             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
313             // found the feature with appropriate edge
314             FeaturePtr aFeature = aComposite->subFeature(a);
315             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
316               aFeature->results().cbegin();
317             for(;aResIter != aFeature->results().cend(); aResIter++) {
318               ResultConstructionPtr aRes = 
319                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
320               if (aRes && aRes->shape()) {
321                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
322                   selectConstruction(aContext, aRes->shape());
323                   owner()->data()->sendAttributeUpdated(this);
324                   return true;
325                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
326                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
327                   int aVIndex = 1;
328                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
329                     if (aVIndex == aVertexNum) { // found!
330                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
331                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
332                       selectConstruction(aContext, aVertex);
333                       owner()->data()->sendAttributeUpdated(this);
334                       return true;
335                     }
336                     aVIndex++;
337                   }
338                 }
339               }
340             }
341           }
342         }
343       }
344     } else { // simple construction element: the selected is that needed
345       owner()->data()->sendAttributeUpdated(this);
346       return true;
347     }
348   }
349   return false; // unknown case
350 }
351
352
353 void Model_AttributeSelection::selectBody(
354     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
355 {
356   // perform the selection
357   TNaming_Selector aSel(selectionLabel());
358   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
359   TopoDS_Shape aContext;
360
361   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
362   if (aBody)
363     aContext = aBody->shape()->impl<TopoDS_Shape>();
364   else {
365     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
366     if (aConstr) {
367       aContext = aConstr->shape()->impl<TopoDS_Shape>();
368     } else {
369       Events_Error::send("A result with shape is expected");
370       return;
371     }
372   }
373   aSel.Select(aNewShape, aContext);
374 }
375
376 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
377 /// if theID is zero, 
378 static void registerSubShape(TDF_Label& theMainLabel, TopoDS_Shape theShape,
379   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
380   std::string theAdditionalName,
381   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
382 {
383   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
384   TNaming_Builder aBuilder(aLab);
385   aBuilder.Generated(theShape);
386   std::stringstream aName;
387   aName<<theContextFeature->name()<<"/";
388   if (!theAdditionalName.empty())
389     aName<<theAdditionalName<<"/";
390   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
391   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
392   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
393
394   if (theRefs.IsNull()) {
395     aName<<"_"<<theID;
396   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
397     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
398     for(; aRef.More(); aRef.Next()) {
399       aName<<"_"<<aRef.Key();
400     }
401   }
402
403   theDoc->addNamingName(aLab, aName.str());
404   TDataStd_Name::Set(aLab, aName.str().c_str());
405 }
406
407 void Model_AttributeSelection::selectConstruction(
408     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
409 {
410   std::shared_ptr<Model_Document> aMyDoc = 
411     std::dynamic_pointer_cast<Model_Document>(owner()->document());
412   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
413   CompositeFeaturePtr aComposite = 
414     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
415   if (!aComposite || aComposite->numberOfSubs() == 0) {
416     return; // saving of context is enough: result construction contains exactly the needed shape
417   }
418   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
419   TDF_Label aLab = myRef.myRef->Label();
420   // identify the reuslts of sub-object of the composite by edges
421   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
422   // save type of the selected shape in integer attribute
423   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
424   TDataStd_Integer::Set(aLab, (int)aShapeType);
425   gp_Pnt aVertexPos;
426   TColStd_MapOfTransient allCurves;
427   if (aShapeType == TopAbs_VERTEX) { // compare positions
428     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
429   } else { 
430     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
431       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
432       Standard_Real aFirst, aLast;
433       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
434       allCurves.Add(aCurve);
435     }
436   }
437   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
438   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
439   aRefs->Clear();
440   const int aSubNum = aComposite->numberOfSubs();
441   for(int a = 0; a < aSubNum; a++) {
442     FeaturePtr aSub = aComposite->subFeature(a);
443     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
444     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
445     // there may be many shapes (circle and center): register if at least one is in selection
446     for(; aRes != aResults.cend(); aRes++) {
447       ResultConstructionPtr aConstr = 
448         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
449       if (!aConstr->shape()) {
450         continue;
451       }
452       if (aShapeType == TopAbs_VERTEX) {
453         if (aConstr->shape()->isVertex()) { // compare vertices positions
454           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
455           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
456           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
457             aRefs->Add(aComposite->subFeatureId(a));
458           }
459         } else { // get first or last vertex of the edge: last is stored with negative sign
460           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
461           int aDelta = kSTART_VERTEX_DELTA;
462           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
463             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
464             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
465               aRefs->Add(aDelta + aComposite->subFeatureId(a));
466               break;
467             }
468             aDelta += kSTART_VERTEX_DELTA;
469           }
470         }
471       } else {
472         if (aConstr->shape()->isEdge()) {
473           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
474           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
475           if (!anEdge.IsNull()) {
476             Standard_Real aFirst, aLast;
477             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
478             if (allCurves.Contains(aCurve)) {
479               int anID = aComposite->subFeatureId(a);
480               aRefs->Add(anID);
481               if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
482                 // add edges to sub-label to support naming for edges selection
483                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
484                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
485                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
486                   Standard_Real aFirst, aLast;
487                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
488                   if (aFaceCurve == aCurve) {
489                     registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
490                   }
491                 }
492               } else { // put vertices of the selected edge to sub-labels
493                 // add edges to sub-label to support naming for edges selection
494                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
495                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
496                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
497                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
498
499                   std::stringstream anAdditionalName; 
500                   registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
501                     "");
502                 }
503               }
504             }
505           }
506         }
507       }
508     }
509   }
510   // store the selected as primitive
511   TNaming_Builder aBuilder(selectionLabel());
512   aBuilder.Generated(aSubShape);
513   registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
514 }
515
516 TDF_Label Model_AttributeSelection::selectionLabel()
517 {
518   return myRef.myRef->Label().FindChild(1);
519 }
520
521 #define FIX_BUG1 1
522 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape, 
523                                              const TDF_Label& theLabel)
524 {
525   std::string aName;
526   // check if the subShape is already in DF
527   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
528   Handle(TDataStd_Name) anAttr;
529   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
530         if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
531           aName = TCollection_AsciiString(anAttr->Get()).ToCString();
532           if(!aName.empty()) {      
533             const TDF_Label& aLabel = theDoc->findNamingName(aName);
534     /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
535                 if(!aLabel.IsEqual(aNS->Label())) {
536                   //aName.erase(); //something is wrong, to be checked!!!
537                   aName += "_SomethingWrong";
538                   return aName;
539                 }*/
540                 const TopoDS_Shape& aShape = aNS->Get();
541                 if(aShape.ShapeType() == TopAbs_COMPOUND) {
542                   std::string aPostFix("_");
543                   TopoDS_Iterator it(aShape);                   
544                   for (int i = 1;it.More();it.Next(), i++) {
545                     if(it.Value() == theShape) {
546                           aPostFix += TCollection_AsciiString (i).ToCString();
547                           aName    += aPostFix;
548                           break;
549                         }
550                         else continue;                                          
551                   }
552                 }
553           }     
554         }
555   }
556   return aName;
557 }
558
559 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
560 {
561 // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
562   TopoDS_Compound aCmp;
563   BRep_Builder BB;
564   BB.MakeCompound(aCmp);
565   TopTools_ListIteratorOfListOfShape it(theAncestors);
566   for(;it.More();it.Next()) {
567         BB.Add(aCmp, it.Value());
568         theSMap.Add(it.Value());
569   }
570   int aNumber(0);
571   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
572   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
573   for (int i = 1; i <= aMap2.Extent(); i++) {
574         const TopoDS_Shape& aKey = aMap2.FindKey(i);
575         const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
576         if(anAncestors.Extent() > 1) aNumber++;
577   }
578   if(aNumber > 1) return false;
579   return true;
580 }
581 std::string Model_AttributeSelection::namingName()
582 {
583   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
584   ResultPtr aCont = context();
585   std::string aName;
586   if(!aSubSh.get() || aSubSh->isNull() || !aCont.get() || aCont->shape()->isNull()) 
587     return aName;
588   TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
589   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
590   std::shared_ptr<Model_Document> aDoc = 
591     std::dynamic_pointer_cast<Model_Document>(aCont->document());
592
593   // check if the subShape is already in DF
594   aName = GetShapeName(aDoc, aSubShape, selectionLabel());
595   if(aName.empty() ) { // not in the document!
596     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
597         switch (aType) {
598           case TopAbs_FACE:
599       // the Face should be in DF. If it is not a case, it is an error ==> to be dbugged                
600                 break;
601           case TopAbs_EDGE:
602                   {
603                   // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
604                   // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
605                   TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
606                   TopTools_IndexedDataMapOfShapeListOfShape aMap;
607                   TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
608                   bool isTrivialCase(true);
609                   for (int i = 1; i <= aMap.Extent(); i++) {
610                         const TopoDS_Shape& aKey = aMap.FindKey(i);
611                         if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
612
613             const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
614                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
615                         isTrivialCase = isTrivial(anAncestors, aSMap);                  
616                         break;
617                   }
618
619                   TopTools_ListOfShape aListOfNbs;
620                   if(!isTrivialCase) { // find Neighbors
621                         TNaming_Localizer aLocalizer;
622                         TopTools_MapOfShape aMap3;
623                         aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
624                         //int n = aMap3.Extent();
625                         TopTools_MapIteratorOfMapOfShape it(aMap3);
626                         for(;it.More();it.Next()) {
627                           const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
628                           //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
629                           const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
630                           TopTools_ListIteratorOfListOfShape it2(aList);
631                           for(;it2.More();it2.Next()) {
632                                 if(aSMap.Contains(it2.Value())) continue; // skip this Face
633                                 aListOfNbs.Append(it2.Value());
634                           }
635                         }
636                   }  // else a trivial case
637                   
638                   // build name of the sub-shape Edge
639                   for(int i=1; i <= aSMap.Extent(); i++) {
640                         const TopoDS_Shape& aFace = aSMap.FindKey(i);
641                         std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
642                         if(i == 1)
643                           aName = aFaceName;
644                         else 
645                           aName += "|" + aFaceName;
646                   }
647                   TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
648                   for (;itl.More();itl.Next()) {
649                         std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
650                         aName += "|" + aFaceName;
651                   }               
652                   }
653                   break;
654
655           case TopAbs_VERTEX:
656                   // name structure (Monifold Topology): 
657                   // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
658                   // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
659                   //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
660                   // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
661                   //                   or compound of 2 open faces.
662                   // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
663                   //                   two independent edges (wire or compound)
664                   // implemented 2 first cases
665                   {
666                         TopTools_IndexedDataMapOfShapeListOfShape aMap;
667                     TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
668                         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
669                         TopTools_ListOfShape aList;
670                         TopTools_MapOfShape aFMap;
671 #ifdef FIX_BUG1
672                         //int n = aList2.Extent(); //bug!
673                         // fix is below
674                         TopTools_ListIteratorOfListOfShape itl2(aList2);
675                     for (int i = 1;itl2.More();itl2.Next(),i++) {
676                           if(aFMap.Add(itl2.Value()))
677                                 aList.Append(itl2.Value());
678                         }
679                         //n = aList.Extent();
680 #endif
681                         TopTools_ListIteratorOfListOfShape itl(aList);
682                     for (int i = 1;itl.More();itl.Next(),i++) {
683                           const TopoDS_Shape& aFace = itl.Value();
684                           std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
685                           if(i == 1)
686                             aName = aFaceName;
687                           else 
688                             aName += "|" + aFaceName;
689                         }
690                   }
691                   break;
692         }
693     // register name                    
694     // aDoc->addNamingName(selectionLabel(), aName);
695         // the selected sub-shape will not be shared and as result it will not require registration
696   }
697   return aName;
698 }
699
700 TopAbs_ShapeEnum translateType (const std::string& theType)
701 {
702   TCollection_AsciiString aStr(theType.c_str());
703   aStr.UpperCase();
704   if(aStr.IsEqual("COMP"))
705         return TopAbs_COMPOUND;
706   else if(aStr.IsEqual("COMS"))
707         return TopAbs_COMPSOLID;
708   else if(aStr.IsEqual("SOLD"))
709         return TopAbs_SOLID;
710   else if(aStr.IsEqual("SHEL"))
711         return TopAbs_SHELL;
712   else if(aStr.IsEqual("FACE"))
713         return TopAbs_FACE;
714   else if(aStr.IsEqual("WIRE"))
715         return TopAbs_WIRE;
716   else if(aStr.IsEqual("EDGE"))
717         return TopAbs_EDGE;
718   else if(aStr.IsEqual("VERT"))
719         return TopAbs_VERTEX;  
720
721   return TopAbs_SHAPE;
722 }
723
724 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
725 {
726   TopoDS_Shape aSelection;
727   std::string::size_type n = theSubShapeName.rfind('/');                        
728   if (n == std::string::npos) n = 1;
729         std::string aSubString = theSubShapeName.substr(n);
730         n = aSubString.rfind('_');
731         if (n == std::string::npos) return aSelection;
732         aSubString = aSubString.substr(n+1);
733         int indx = atoi(aSubString.c_str());
734         TopoDS_Iterator it(theCompound);                        
735         for (int i = 1;it.More();it.Next(), i++) {
736           if(i == indx) {                         
737             aSelection = it.Value();                      
738             break;
739           }
740           else continue;                                                
741         }
742   return aSelection;    
743 }
744
745 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
746 {
747   TopoDS_Shape aFace;
748   const TDF_Label& aLabel = theDoc->findNamingName(theSubShapeName);
749   if(aLabel.IsNull()) return aFace;
750   Handle(TNaming_NamedShape) aNS;
751   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
752         const TopoDS_Shape& aShape = aNS->Get();
753         if(!aShape.IsNull()) {
754           if(aShape.ShapeType() == TopAbs_COMPOUND) 
755             aFace = getShapeFromCompound(theSubShapeName, aShape);
756           else 
757                 aFace = aShape;   
758         }
759   }
760   return aFace;
761 }
762 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
763 {
764   if(theSubShapeName.empty() || theType.empty()) return;
765   TopAbs_ShapeEnum aType = translateType(theType);
766   ResultPtr aCont = context();
767   if(!aCont.get() || aCont->shape()->isNull()) return;
768   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
769   TopAbs_ShapeEnum aContType = aContext.ShapeType();
770   if(aType <= aContType) return; // not applicable
771
772   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aCont->document());
773   TopoDS_Shape aSelection;
774   switch (aType) 
775   {
776   case TopAbs_COMPOUND:
777     break;
778   case TopAbs_COMPSOLID:
779     break;
780   case TopAbs_SOLID:
781     break;
782   case TopAbs_SHELL:
783     break;
784   case TopAbs_FACE:
785     {
786           const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
787           if(!aSelection.IsNull()) {// Select it
788                 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
789         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
790                 setValue(aCont, aShapeToBeSelected);
791           }
792         }
793     break;
794   case TopAbs_WIRE:
795         break;
796   case TopAbs_EDGE:
797         {
798       TopTools_ListOfShape aList;
799           std::list<std::string> aListofNames;
800           //ParseEdgeName();
801
802         }
803     break;
804   case TopAbs_VERTEX:
805         break;
806   default: //TopAbs_SHAPE
807         return;
808   }
809
810 }