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