]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Merge branch 'master' of newgeom:newgeom
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // File:        Model_AttributeSelection.h
2 // Created:     2 Oct 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include "Model_AttributeSelection.h"
6 #include "Model_Application.h"
7 #include "Model_Events.h"
8 #include "Model_Data.h"
9 #include <ModelAPI_Feature.h>
10 #include <ModelAPI_ResultBody.h>
11 #include <ModelAPI_ResultConstruction.h>
12 #include <ModelAPI_CompositeFeature.h>
13 #include <GeomAPI_Shape.h>
14 #include <GeomAPI_PlanarEdges.h>
15 #include <GeomAlgoAPI_SketchBuilder.h>
16 #include <Events_Error.h>
17
18 #include <TNaming_Selector.hxx>
19 #include <TNaming_NamedShape.hxx>
20 #include <TNaming_Tool.hxx>
21 #include <TNaming_Builder.hxx>
22 #include <TopoDS_Shape.hxx>
23 #include <TDataStd_IntPackedMap.hxx>
24 #include <TDataStd_Integer.hxx>
25 #include <TopTools_MapOfShape.hxx>
26 #include <TopExp_Explorer.hxx>
27 #include <TDF_LabelMap.hxx>
28 #include <BRep_Tool.hxx>
29 #include <TopoDS_Edge.hxx>
30 #include <TopoDS.hxx>
31 #include <TColStd_MapOfTransient.hxx>
32 #include <gp_Pnt.hxx>
33 #include <Precision.hxx>
34
35 using namespace std;
36 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
37 /// (multiplied by the index of the edge)
38 static const int kSTART_VERTEX_DELTA = 1000000;
39
40 // on this label is stored:
41 // TNaming_NamedShape - selected shape
42 // TNaming_Naming - topological selection information (for the body)
43 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
44 // TDataStd_Integer - type of the selected shape (for construction)
45 // TDF_Reference - from ReferenceAttribute, the context
46
47 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
48   const boost::shared_ptr<GeomAPI_Shape>& theSubShape)
49 {
50   const boost::shared_ptr<GeomAPI_Shape>& anOldShape = value();
51   bool isOldShape = 
52     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
53   if (isOldShape) return; // shape is the same, so context is also unchanged
54   // update the referenced object if needed
55   bool isOldContext = theContext == myRef.value();
56   if (!isOldContext)
57     myRef.setValue(theContext);
58
59   if (theContext->groupName() == ModelAPI_ResultBody::group())
60     selectBody(theContext, theSubShape);
61   else if (theContext->groupName() == ModelAPI_ResultConstruction::group())
62     selectConstruction(theContext, theSubShape);
63
64   myIsInitialized = true;
65   owner()->data()->sendAttributeUpdated(this);
66 }
67
68 boost::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
69 {
70   boost::shared_ptr<GeomAPI_Shape> aResult;
71   if (myIsInitialized) {
72     Handle(TNaming_NamedShape) aSelection;
73     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
74       TopoDS_Shape aSelShape = aSelection->Get();
75       aResult = boost::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
76       aResult->setImpl(new TopoDS_Shape(aSelShape));
77     }
78   }
79   return aResult;
80 }
81
82 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
83   : myRef(theLabel)
84 {
85   myIsInitialized = myRef.isInitialized();
86 }
87
88 ResultPtr Model_AttributeSelection::context() {
89   return boost::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
90 }
91
92
93 void Model_AttributeSelection::setObject(const boost::shared_ptr<ModelAPI_Object>& theObject)
94 {
95   ModelAPI_AttributeSelection::setObject(theObject);
96   myRef.setObject(theObject);
97 }
98
99 bool Model_AttributeSelection::update()
100 {
101   ResultPtr aContext = context();
102   if (!aContext) return false;
103   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
104     // body: just a named shape, use selection mechanism from OCCT
105     TNaming_Selector aSelector(selectionLabel());
106     TDF_LabelMap aScope; // empty means the whole document
107     owner()->data()->sendAttributeUpdated(this);
108     return aSelector.Solve(aScope) == Standard_True;
109   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
110     // construction: identification by the results indexes, recompute faces and
111     // take the face that more close by the indexes
112     boost::shared_ptr<GeomAPI_PlanarEdges> aWirePtr = 
113       boost::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
114       boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
115     if (aWirePtr && aWirePtr->hasPlane()) {
116       boost::shared_ptr<Model_Data> aData = 
117         boost::dynamic_pointer_cast<Model_Data>(owner()->data());
118       TDF_Label aLab = aData->label();
119       // getting a type of selected shape
120       Handle(TDataStd_Integer) aTypeAttr;
121       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
122         return false;
123       }
124       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
125       // selected indexes will be needed in each "if"
126       Handle(TDataStd_IntPackedMap) aSubIds;
127       boost::shared_ptr<GeomAPI_Shape> aNewSelected;
128       bool aNoIndexes = 
129         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
130       // for now working only with composite features
131       FeaturePtr aContextFeature = owner()->document()->feature(aContext);
132       CompositeFeaturePtr aComposite = 
133         boost::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
134       if (!aComposite || aComposite->numberOfSubs() == 0) {
135         return false;
136       }
137
138       if (aShapeType == TopAbs_FACE) {
139         // If this is a wire with plane defined thin it is a sketch-like object
140         std::list<boost::shared_ptr<GeomAPI_Shape> > aFaces;
141         GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
142           aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
143         if (aFaces.empty()) // no faces, update can not work correctly
144           return false;
145         // if there is no edges indexes, any face can be used: take the first
146         boost::shared_ptr<GeomAPI_Shape> aNewSelected;
147         if (aNoIndexes) {
148           aNewSelected = *(aFaces.begin());
149         } else { // searching for most looks-like initial face by the indexes
150           // prepare edges of the current resut for the fast searching
151           TColStd_MapOfTransient allCurves;
152           const int aSubNum = aComposite->numberOfSubs();
153           for(int a = 0; a < aSubNum; a++) {
154             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
155               FeaturePtr aSub = aComposite->subFeature(a);
156               const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
157               std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
158               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
159                 ResultConstructionPtr aConstr = 
160                   boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
161                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
162                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
163                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
164                   if (!anEdge.IsNull()) {
165                     Standard_Real aFirst, aLast;
166                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
167                     allCurves.Add(aCurve);
168                   }
169                 }
170               }
171             }
172           }
173           // iterate new result faces and searching for these edges
174           std::list<boost::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
175           double aBestFound = 0; // best percentage of found edges
176           for(; aFacesIter != aFaces.end(); aFacesIter++) {
177             int aFound = 0, aNotFound = 0;
178             TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
179             for(; anEdgesExp.More(); anEdgesExp.Next()) {
180               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
181               if (!anEdge.IsNull()) {
182                 Standard_Real aFirst, aLast;
183                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
184                 if (allCurves.Contains(aCurve)) {
185                   aFound++;
186                 } else {
187                   aNotFound++;
188                 }
189               }
190             }
191             if (aFound + aNotFound != 0) {
192               double aPercentage = double(aFound) / double(aFound + aNotFound);
193               if (aPercentage > aBestFound) {
194                 aBestFound = aPercentage;
195                 aNewSelected = *aFacesIter;
196               }
197             }
198           }
199         }
200         if (aNewSelected) { // store this new selection
201           selectConstruction(aContext, aNewSelected);
202           owner()->data()->sendAttributeUpdated(this);
203           return true;
204         }
205       } else if (aShapeType == TopAbs_EDGE) {
206         // just reselect the edge by the id
207         const int aSubNum = aComposite->numberOfSubs();
208         for(int a = 0; a < aSubNum; a++) {
209           // if aSubIds take any, the first appropriate
210           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
211             // found the appropriate feature
212             FeaturePtr aFeature = aComposite->subFeature(a);
213             std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
214               aFeature->results().cbegin();
215             for(;aResIter != aFeature->results().cend(); aResIter++) {
216               ResultConstructionPtr aRes = 
217                 boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
218               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
219                 selectConstruction(aContext, aRes->shape());
220                 owner()->data()->sendAttributeUpdated(this);
221                 return true;
222               }
223             }
224           }
225         }
226       } else if (aShapeType == TopAbs_VERTEX) {
227         // just reselect the vertex by the id of edge
228         const int aSubNum = aComposite->numberOfSubs();
229         for(int a = 0; a < aSubNum; a++) {
230           // if aSubIds take any, the first appropriate
231           int aFeatureID = aComposite->subFeatureId(a);
232           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID)) {
233             // searching for deltas
234             int aVertexNum = 0;
235             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
236             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 2;
237             // found the feature with appropriate edge
238             FeaturePtr aFeature = aComposite->subFeature(a);
239             std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
240               aFeature->results().cbegin();
241             for(;aResIter != aFeature->results().cend(); aResIter++) {
242               ResultConstructionPtr aRes = 
243                 boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
244               if (aRes && aRes->shape()) {
245                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
246                   selectConstruction(aContext, aRes->shape());
247                   owner()->data()->sendAttributeUpdated(this);
248                   return true;
249                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
250                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
251                   int aVIndex = 1;
252                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
253                     if (aVIndex == aVertexNum) { // found!
254                       boost::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
255                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
256                       selectConstruction(aContext, aVertex);
257                       owner()->data()->sendAttributeUpdated(this);
258                       return true;
259                     }
260                     aVIndex++;
261                   }
262                 }
263               }
264             }
265           }
266         }
267       }
268     }
269   }
270   return false; // unknown case
271 }
272
273
274 void Model_AttributeSelection::selectBody(
275     const ResultPtr& theContext, const boost::shared_ptr<GeomAPI_Shape>& theSubShape)
276 {
277   // perform the selection
278   TNaming_Selector aSel(selectionLabel());
279   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
280   TopoDS_Shape aContext;
281
282   ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
283   if (aBody)
284     aContext = aBody->shape()->impl<TopoDS_Shape>();
285   else {
286     ResultConstructionPtr aConstr = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
287     if (aConstr) {
288       aContext = aConstr->shape()->impl<TopoDS_Shape>();
289     } else {
290       Events_Error::send("A result with shape is expected");
291       return;
292     }
293   }
294   aSel.Select(aNewShape, aContext);
295 }
296
297 void Model_AttributeSelection::selectConstruction(
298     const ResultPtr& theContext, const boost::shared_ptr<GeomAPI_Shape>& theSubShape)
299 {
300   FeaturePtr aContextFeature = owner()->document()->feature(theContext);
301   CompositeFeaturePtr aComposite = 
302     boost::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
303   if (!aComposite || aComposite->numberOfSubs() == 0) {
304     return; // saving of context is enough: result construction contains exactly the needed shape
305   }
306   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(owner()->data());
307   TDF_Label aLab = aData->label();
308   // identify the reuslts of sub-object of the composite by edges
309   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
310   // save type of the selected shape in integer attribute
311   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
312   TDataStd_Integer::Set(aLab, (int)aShapeType);
313   gp_Pnt aVertexPos;
314   TColStd_MapOfTransient allCurves;
315   if (aShapeType == TopAbs_VERTEX) { // compare positions
316     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
317   } else { 
318     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
319       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
320       Standard_Real aFirst, aLast;
321       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
322       allCurves.Add(aCurve);
323     }
324   }
325   // iterate and store the result ids of sub-elements
326   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
327   const int aSubNum = aComposite->numberOfSubs();
328   for(int a = 0; a < aSubNum; a++) {
329     FeaturePtr aSub = aComposite->subFeature(a);
330     const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
331     std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
332     // there may be many shapes (circle and center): register if at least one is in selection
333     for(; aRes != aResults.cend(); aRes++) {
334       ResultConstructionPtr aConstr = 
335         boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
336       if (!aConstr->shape()) {
337         continue;
338       }
339       if (aShapeType == TopAbs_VERTEX) {
340         if (aConstr->shape()->isVertex()) { // compare vertices positions
341           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
342           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
343           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
344             aRefs->Add(aComposite->subFeatureId(a));
345           }
346         } else { // get first or last vertex of the edge: last is stored with negative sign
347           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
348           int aDelta = kSTART_VERTEX_DELTA;
349           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
350             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
351             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
352               aRefs->Add(aComposite->subFeatureId(a));
353               aRefs->Add(aDelta + aComposite->subFeatureId(a));
354               break;
355             }
356             aDelta += kSTART_VERTEX_DELTA;
357           }
358         }
359       } else {
360         if (aConstr->shape()->isEdge()) {
361           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
362           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
363           if (!anEdge.IsNull()) {
364             Standard_Real aFirst, aLast;
365             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
366             if (allCurves.Contains(aCurve)) {
367               aRefs->Add(aComposite->subFeatureId(a));
368             }
369           }
370         }
371       }
372     }
373   }
374   // store the selected as primitive
375   TNaming_Builder aBuilder(selectionLabel());
376   aBuilder.Generated(aSubShape);
377 }
378
379 TDF_Label Model_AttributeSelection::selectionLabel()
380 {
381   return myRef.myRef->Label().FindChild(1);
382 }