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