Salome HOME
Merge remote-tracking branch 'remotes/origin/2018_Lot1_Tasks'
[modules/shaper.git] / src / Model / Model_ResultConstruction.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_ResultConstruction.h>
22
23 #include <Model_Data.h>
24 #include <ModelAPI_CompositeFeature.h>
25 #include <Model_SelectionNaming.h>
26 #include <ModelAPI_Events.h>
27 #include <Config_PropManager.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_Shape.h>
30 #include <GeomAlgoAPI_SketchBuilder.h>
31 #include <Events_Loop.h>
32
33 #include <TDF_Reference.hxx>
34 #include <TDF_ChildIterator.hxx>
35 #include <TNaming_NamedShape.hxx>
36 #include <TNaming_Builder.hxx>
37 #include <TDataStd_Integer.hxx>
38 #include <TDataStd_IntPackedMap.hxx>
39 #include <TDataStd_Name.hxx>
40 #include <TDataStd_UAttribute.hxx>
41 #include <TColStd_MapOfTransient.hxx>
42 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
43 #include <BRep_Tool.hxx>
44 #include <BRep_Builder.hxx>
45 #include <TopoDS.hxx>
46 #include <TopoDS_Shape.hxx>
47 #include <TopoDS_Edge.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopExp_Explorer.hxx>
50 #include <TNaming_Tool.hxx>
51 #include <Precision.hxx>
52
53 // identifier that it is full result selected, but in external document (for internal index is 0)
54 Standard_GUID kFULL_RESULT_ID("ee87e529-da6f-46af-be25-5e0fefde52f7");
55
56
57 void Model_ResultConstruction::colorConfigInfo(std::string& theSection, std::string& theName,
58                                        std::string& theDefault)
59 {
60   theSection = "Visualization";
61   theName = "result_construction_color";
62   theDefault = DEFAULT_COLOR();
63 }
64
65 void Model_ResultConstruction::setShape(std::shared_ptr<GeomAPI_Shape> theShape)
66 {
67   if (myShape != theShape) {
68     if (!theShape.get() || !theShape->isEqual(myShape)) {
69         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
70         ModelAPI_EventCreator::get()->sendUpdated(data()->owner(), anEvent);
71     }
72     myShape = theShape;
73     if (theShape.get()) {
74       myFacesUpToDate = false;
75       myFaces.clear();
76     }
77   }
78 }
79
80 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape()
81 {
82   return myShape;
83 }
84
85 Model_ResultConstruction::Model_ResultConstruction()
86 {
87   myIsInHistory = true;
88   myIsInfinite = false;
89   myFacesUpToDate = false;
90 }
91
92 void Model_ResultConstruction::setIsInHistory(const bool isInHistory)
93 {
94   myIsInHistory = isInHistory;
95 }
96
97 int Model_ResultConstruction::facesNum()
98 {
99   if (!myFacesUpToDate) {
100     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
101       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(myShape);
102     if (aWirePtr.get()) {
103       std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
104       GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
105         aWirePtr->norm(), aWirePtr, aFaces);
106       std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFIter = aFaces.begin();
107       for(; aFIter != aFaces.end(); aFIter++) {
108         std::shared_ptr<GeomAPI_Face> aFace(new GeomAPI_Face(*aFIter));
109         if (aFace.get() && !aFace->isNull())
110           myFaces.push_back(aFace);
111       }
112     }
113     myFacesUpToDate = true;
114   }
115   return int(myFaces.size());
116 }
117
118 std::shared_ptr<GeomAPI_Face> Model_ResultConstruction::face(const int theIndex)
119 {
120   return myFaces[theIndex];
121 }
122
123 bool Model_ResultConstruction::isInfinite()
124 {
125   return myIsInfinite;
126 }
127
128 void Model_ResultConstruction::setInfinite(const bool theInfinite)
129 {
130   myIsInfinite = theInfinite;
131 }
132
133 void Model_ResultConstruction::setIsConcealed(const bool theValue)
134 {
135   // do nothing: the construction element is never consealed
136 }
137
138 static const int kSTART_VERTEX_DELTA = 1000000;
139
140 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape, std::string theFullName,
141   const int theID, std::shared_ptr<Model_Document> theDoc,
142   bool theSelectionMode)
143 {
144   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
145   TNaming_Builder aBuilder(aLab);
146   // wire never happens as sub, it must be generated to be found
147   // by SelectionNaming TNaming_Tool::NamedShape
148   if (theSelectionMode && theShape.ShapeType() != TopAbs_WIRE)
149     aBuilder.Select(theShape, theShape);
150   else
151     aBuilder.Generated(theShape);
152
153   theDoc->addNamingName(aLab, theFullName);
154   TDataStd_Name::Set(aLab, theFullName.c_str());
155 }
156
157 // generates a full-name for sub-element of the composite feature (sketch)
158 std::string fullName(CompositeFeaturePtr theComposite, const TopoDS_Shape& theSubShape,
159   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
160 {
161   TopAbs_ShapeEnum aShapeType = theSubShape.ShapeType();
162   gp_Pnt aVertexPos;
163   TColStd_MapOfTransient allCurves;
164   if (aShapeType == TopAbs_VERTEX) { // compare positions
165     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(theSubShape));
166   } else {
167     for(TopExp_Explorer anEdgeExp(theSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
168       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
169       Standard_Real aFirst, aLast;
170       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
171       allCurves.Add(aCurve);
172     }
173   }
174   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
175   std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
176   TColStd_PackedMapOfInteger aRefs; // indixes of sub-elements in composite
177
178   const int aSubNum = theComposite->numberOfSubs();
179   for(int a = 0; a < aSubNum; a++) {
180     FeaturePtr aSub = theComposite->subFeature(a);
181     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
182     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
183     // there may be many shapes (circle and center): register if at least one is in selection
184     for(; aRes != aResults.cend(); aRes++) {
185       ResultConstructionPtr aConstr =
186         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
187       if (!aConstr->shape()) {
188         continue;
189       }
190       if (aShapeType == TopAbs_VERTEX) {
191         if (aConstr->shape()->isVertex()) { // compare vertices positions
192           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
193           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
194           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
195             aRefs.Add(theComposite->subFeatureId(a));
196             aSubNames[theComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
197           }
198         } else { // get first or last vertex of the edge: last is stored with additional delta
199           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
200           int aDelta = kSTART_VERTEX_DELTA;
201           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
202             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
203             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
204               aRefs.Add(aDelta + theComposite->subFeatureId(a));
205               aSubNames[aDelta + theComposite->subFeatureId(a)] =
206                 Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
207               break;
208             }
209             aDelta += kSTART_VERTEX_DELTA;
210           }
211         }
212       } else {
213         if (aConstr->shape()->isEdge()) {
214           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
215           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
216           if (!anEdge.IsNull()) {
217             Standard_Real aFirst, aLast;
218             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
219             if (allCurves.Contains(aCurve)) {
220               int anID = theComposite->subFeatureId(a);
221               aRefs.Add(anID);
222               aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
223               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
224                 // add edges to sub-label to support naming for edges selection
225                 TopExp_Explorer anEdgeExp(theSubShape, TopAbs_EDGE);
226                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
227                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
228                   Standard_Real aFirst, aLast;
229                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
230                   if (aFaceCurve == aCurve) {
231                     int anOrient = Model_SelectionNaming::edgeOrientation(theSubShape, anEdge);
232                     anOrientations[anID] = anOrient;
233                   }
234                 }
235               }
236             }
237           }
238         }
239       }
240     }
241   }
242   std::stringstream aName;
243   // #1839 : do not store name of the feature in the tree, since this name could be changed
244   if (theSubShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole construction result
245     if (theSubShape.ShapeType() == TopAbs_FACE) aName<<"Face";
246     else if (theSubShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
247     else if (theSubShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
248     else if (theSubShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
249
250     // make a composite name from all sub-elements indexes: "1_2_3_4"
251     TColStd_MapIteratorOfPackedMapOfInteger aRef(aRefs);
252     for(; aRef.More(); aRef.Next()) {
253       aName<<"-"<<aSubNames[aRef.Key()];
254       if (anOrientations.find(aRef.Key()) != anOrientations.end()) {
255         if (anOrientations[aRef.Key()] == 1)
256           aName<<"f";
257         else if (anOrientations[aRef.Key()] == -1)
258           aName<<"r";
259       }
260     }
261   }
262   if (!theRefs.IsNull()) {
263     Handle(TColStd_HPackedMapOfInteger) aMap = new TColStd_HPackedMapOfInteger(aRefs);
264     theRefs->ChangeMap(aMap);
265   }
266   return aName.str();
267 }
268
269 // stores shape and name on sub-label of the main stored shape
270 static void saveSubName(CompositeFeaturePtr theComposite,
271   TDF_Label& theLab, const bool isSelectionMode, TopoDS_Shape aSub,
272   std::shared_ptr<Model_Document> theDoc, std::string theFullName)
273 {
274   // trying to store the edge of composite result, not sketch sub as it is
275   if (aSub.ShapeType() == TopAbs_EDGE) {
276     ResultPtr aRes = theComposite->firstResult();
277     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aRes);
278     if (aConstr.get()) {
279       Standard_Real aSubFirst, aSubLast;
280       TopoDS_Edge aSubEdge = TopoDS::Edge(aSub);
281       Handle(Geom_Curve) aSubCurve = BRep_Tool::Curve(aSubEdge, aSubFirst, aSubLast);
282       for(int aFaceIndex = 0; aFaceIndex < aConstr->facesNum(); aFaceIndex++) {
283         GeomShapePtr aGFace = aConstr->face(aFaceIndex);
284         TopoDS_Shape aFace = aGFace->impl<TopoDS_Shape>();
285         for(TopExp_Explorer anExp(aFace, TopAbs_EDGE); anExp.More(); anExp.Next()) {
286           TopoDS_Edge anEdge = TopoDS::Edge(anExp.Current());
287           Standard_Real aFirst, aLast;
288           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
289           if (aCurve == aSubCurve &&
290               ((fabs(aFirst - aSubFirst) < 1.e-9 &&  fabs(aLast - aSubLast) < 1.e-9)) ||
291               (fabs(aFirst - aSubLast) < 1.e-9 &&  fabs(aLast - aSubFirst) < 1.e-9)) {
292             aSub = anEdge;
293             break;
294           }
295         }
296       }
297     }
298   }
299
300   TNaming_Builder aBuilder(theLab);
301   if (isSelectionMode)
302     aBuilder.Select(aSub, aSub);
303   else
304     aBuilder.Generated(aSub);
305   theDoc->addNamingName(theLab, theFullName.c_str());
306   TDataStd_Name::Set(theLab, theFullName.c_str());
307 }
308
309
310 TDF_Label Model_ResultConstruction::startLabel(
311   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theExternal)
312 {
313   theExternal = theExtDoc.get() && theExtDoc != document();
314   if (theExternal) { // external document is used
315     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theExtDoc);
316     return aDoc->extConstructionsLabel();
317   }
318   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
319   return aData->label();
320 }
321
322 int Model_ResultConstruction::select(const std::shared_ptr<GeomAPI_Shape>& theSubShape,
323   const std::shared_ptr<ModelAPI_Document> theExtDoc, const int theIndex)
324 {
325   int anIndex; // resulting index of the sub-label
326   TopoDS_Shape aSubShape;
327   if (theSubShape.get()) {
328     aSubShape = theSubShape->impl<TopoDS_Shape>();
329   } else if (shape().get()) {
330     aSubShape = shape()->impl<TopoDS_Shape>();
331   }
332   // if external document requires this selection, put the naming structures to this doc
333   // to support the naming mechanism in this document correctly
334   bool anExternal;
335   TDF_Label aDataLab = startLabel(theExtDoc, anExternal);
336   if (theIndex == -1) {
337     anIndex = anExternal ? 2 : 1; // for the external doc don't mind about the main shape
338
339     if (theSubShape.get() || anExternal) { // searching for already selected sub (or whole for ext)
340       // iterate all the already presented shapes to see the same
341       TDF_ChildIterator aSubsIter(aDataLab, Standard_False);
342       for(; aSubsIter.More(); aSubsIter.Next()) {
343         const TDF_Label aLab = aSubsIter.Value();
344         if (aLab.Tag() == 1) // skip the root shape label
345           continue;
346         Handle(TNaming_NamedShape) aNS;
347         if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
348           if (aNS->Get().IsSame(aSubShape)) {
349             return aLab.Tag() - 1; // found exactly the needed shape, nothing else to do
350           }
351         }
352         anIndex = aLab.Tag(); // searching for the latest index
353       }
354       anIndex = (anIndex == 1) ? 2 : (anIndex + 1); // next after 1-root, or next after all
355     }
356   } else {
357     anIndex = theIndex + 1;
358   }
359
360   // set the naming structure at index
361   TDF_Label aLab = aDataLab.FindChild(anIndex, Standard_True);
362
363   // if the subshape is part of a result face, select the whole face (#1997)
364   bool isSelectionMode = false; // and other don't set shapes - all the naming is in face label
365   if (!aSubShape.IsNull() && aSubShape.ShapeType() > TopAbs_FACE) {
366     // but before check that sub-vertex correctly detected as intersection of sketch edges (#2389)
367     int anEdgesNum = 2;
368     if (aSubShape.ShapeType() == TopAbs_VERTEX) {
369       anEdgesNum = 0;
370       ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
371       FeaturePtr aThisFeature = document()->feature(aThisPtr);
372       CompositeFeaturePtr aComposite =
373         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
374       if (aComposite.get()) {
375         const int aSubNum = aComposite->numberOfSubs();
376         for(int a = 0; a < aSubNum; a++) {
377           int aSubID = aComposite->subFeatureId(a);
378           FeaturePtr aSub = aComposite->subFeature(a);
379           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
380           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
381           for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
382             ResultConstructionPtr aConstr =
383               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
384             if (aConstr->shape() && aConstr->shape()->isEdge()) {
385               TopoDS_Shape aResShape = aConstr->shape()->impl<TopoDS_Shape>();
386               for(TopExp_Explorer anExp(aResShape, TopAbs_VERTEX); anExp.More(); anExp.Next()) {
387                 if (aSubShape.IsSame(anExp.Current())) {
388                   anEdgesNum++;
389                   break;
390                 }
391               }
392             }
393           }
394         }
395       }
396     }
397     if (anEdgesNum > 1) {
398       for(int aFaceIndex = 0; aFaceIndex < facesNum(); aFaceIndex++) {
399         TopExp_Explorer anExp(face(aFaceIndex)->impl<TopoDS_Shape>(), aSubShape.ShapeType());
400         for(; anExp.More(); anExp.Next()) {
401           if (aSubShape.IsSame(anExp.Current())) { // this is the case: select the whole face
402             // here just store the face index (to update face if update of edge is needed)
403             TNaming_Builder aBuilder(aLab);
404             aBuilder.Select(aSubShape, aSubShape);
405             int aFaceSelID = select(face(aFaceIndex), theExtDoc, -1);
406             TDF_Reference::Set(aLab, aLab.Father().FindChild(aFaceSelID));
407             isSelectionMode = true;
408             break;
409           }
410         }
411       }
412     }
413   }
414
415   // external full result is not identified by index == 0, so, add here the ID
416   if (!theSubShape.get()) {
417     TDataStd_UAttribute::Set(aLab, kFULL_RESULT_ID);
418     // empty NS
419     TNaming_Builder aBuilder(aLab);
420     // store all sub-faces naming since faces may be used for extrusion, where all edges are needed
421     Handle(TDataStd_IntPackedMap) anIndices = TDataStd_IntPackedMap::Set(aLab);
422     std::list<int> aFacesIndexes;
423     for(int a = 0; a < facesNum(); a++) {
424       anIndices->Add(select(face(a), theExtDoc, -1));
425     }
426     return anIndex - 1;
427   }
428
429   { // this to have erased Builder after the shape was generated (NS on this label may be changed)
430     TNaming_Builder aBuilder(aLab);
431     if (aSubShape.IsNull()) {
432       return anIndex - 1; // just keep empty named shape
433     }
434     // wire never happens as sub, it must be generated to be found
435     // by SelectionNaming TNaming_Tool::NamedShape
436     if (isSelectionMode && aSubShape.ShapeType() != TopAbs_WIRE) {
437       aBuilder.Select(aSubShape, aSubShape);
438     } else {
439       aBuilder.Generated(aSubShape);
440     }
441   }
442
443   if (anIndex == 1 && isInfinite()) { // infinitive results has no sub-selection
444     return anIndex - 1;
445   }
446   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
447   FeaturePtr aThisFeature = document()->feature(aThisPtr);
448   CompositeFeaturePtr aComposite =
449     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
450   if (!aComposite || aComposite->numberOfSubs() == 0) {
451     // saving of context is enough: result construction contains exactly the needed shape
452     return anIndex - 1;
453   }
454
455   // identify the results of sub-object of the composite by edges
456   // save type of the selected shape in integer attribute
457   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
458   TDataStd_Integer::Set(aLab, (int)aShapeType);
459   gp_Pnt aVertexPos;
460   TColStd_MapOfTransient allCurves;
461   if (aShapeType == TopAbs_VERTEX) { // compare positions
462     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
463   } else {
464     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
465       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
466       Standard_Real aFirst, aLast;
467       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
468       allCurves.Add(aCurve);
469     }
470   }
471   std::shared_ptr<Model_Document> aMyDoc =
472     std::dynamic_pointer_cast<Model_Document>(document());
473   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
474   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
475   const int aSubNum = aComposite->numberOfSubs();
476   // subs are placed on unique labels because of #2248: sketch curve may produce several edges,
477   // but #2401 - on stable labels
478   NCollection_Map<int> aUsedIDMap; // already used lab tags for placement of shapes
479
480   for(int a = 0; a < aSubNum; a++) {
481     FeaturePtr aSub = aComposite->subFeature(a);
482     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
483     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
484     // there may be many shapes (circle and center): register if at least one is in selection
485     for(; aRes != aResults.cend(); aRes++) {
486       ResultConstructionPtr aConstr =
487         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
488       if (!aConstr->shape()) {
489         continue;
490       }
491       if (aShapeType != TopAbs_VERTEX) {
492         if (aConstr->shape()->isEdge()) {
493           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
494           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
495           if (!anEdge.IsNull()) {
496             Standard_Real aFirst, aLast;
497             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
498             if (allCurves.Contains(aCurve)) {
499               int anID = aComposite->subFeatureId(a);
500               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
501                 // add edges to sub-label to support naming for edges selection
502                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
503                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
504                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
505                   Standard_Real aFirst, aLast;
506                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
507                   if (aFaceCurve == aCurve) {
508                     while(aUsedIDMap.Contains(anID))
509                       anID += 100000;
510                     aUsedIDMap.Add(anID);
511                     TDF_Label aSubLab = aLab.FindChild(anID);
512                     std::string aFullNameSub = fullName(aComposite, anEdge);
513                     saveSubName(aComposite, aSubLab, isSelectionMode, anEdge, aMyDoc, aFullNameSub);
514
515                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
516                     if (anOrient != 0) {
517                       // store the orientation of edge relatively to face if needed
518                       TDataStd_Integer::Set(aSubLab, anOrient);
519                     }
520                   }
521                 }
522               } else { // put vertices of the selected edge to sub-labels
523                 // add edges to sub-label to support naming for edges selection
524                 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
525                       anEdgeExp.More(); anEdgeExp.Next()) {
526                     TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
527                     while(aUsedIDMap.Contains(anID))
528                       anID += 100000;
529                     aUsedIDMap.Add(anID);
530                     TDF_Label aSubLab = aLab.FindChild(anID);
531                     std::string aFullNameSub = fullName(aComposite, aV);
532                     saveSubName(aComposite, aSubLab, isSelectionMode, aV, aMyDoc, aFullNameSub);
533                 }
534               }
535             }
536           }
537         }
538       }
539     }
540   }
541   std::string aFullName = fullName(aComposite, aSubShape, aRefs);
542   // store the selected as primitive
543   registerSubShape(aLab, aSubShape, aFullName, 0, aMyDoc, isSelectionMode);
544   return anIndex - 1;
545 }
546
547 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape(const int theIndex,
548   const std::shared_ptr<ModelAPI_Document> theExtDoc)
549 {
550   std::shared_ptr<GeomAPI_Shape> aResult;
551   if (theIndex == 0)
552     return aResult; // the whole shape, so, NULL
553
554   bool isExt;
555   TDF_Label aLab = startLabel(theExtDoc, isExt).FindChild(theIndex + 1);
556   if (!aLab.IsNull()) { // index is not bad
557     Handle(TNaming_NamedShape) aSelection;
558     if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
559       TopoDS_Shape aSelShape = aSelection->Get();
560       if (aSelShape.IsNull())
561         return aResult; // shape equal to context => null
562       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
563       aResult->setImpl(new TopoDS_Shape(aSelShape));
564     }
565   }
566
567   return aResult;
568 }
569
570 bool Model_ResultConstruction::update(const int theIndex,
571   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theModified)
572 {
573   theModified = false;
574   bool anExt;
575   TDF_Label aLab = startLabel(theExtDoc, anExt).FindChild(theIndex + 1, Standard_True);
576   if (theIndex == 0 || aLab.IsAttribute(kFULL_RESULT_ID)) { // full for external same as index == 0
577     // it is just reference to construction, not sub-shape
578     // if there is a sketch, the sketch-naming must be updated
579     if (!isInfinite()) {
580       // update all faces named by the whole result
581       bool aRes = true;
582       Handle(TDataStd_IntPackedMap) anIndices;
583       if (aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), anIndices)) {
584         NCollection_Map<TopoDS_Shape> aFaces; // collect faces, updated in the tree
585         TColStd_MapIteratorOfPackedMapOfInteger anIndexIter(anIndices->GetMap());
586         Handle(TColStd_HPackedMapOfInteger) aNewPackedMap =
587           new TColStd_HPackedMapOfInteger; // with only faces that are ok
588         // iterate to find existing faces, updated
589         for(; anIndexIter.More(); anIndexIter.Next()) {
590           if (update(anIndexIter.Key(), theExtDoc, theModified)) {
591             GeomShapePtr aFace = shape(anIndexIter.Key(), theExtDoc);
592             if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
593               aNewPackedMap->ChangeMap().Add(anIndexIter.Key());
594               aFaces.Add(aFace->impl<TopoDS_Shape>());
595             }
596           }
597         }
598         // then iterate all existing faces to find new faces
599         int aCurrentFacesNum = facesNum();
600         for(int a = 0; a < aCurrentFacesNum; a++) {
601           GeomShapePtr aFace = face(a);
602           if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
603             // add this one
604             int aNewFaceIndex = select(aFace, theExtDoc, -1);
605             if (aNewFaceIndex > 0) {
606               aNewPackedMap->ChangeMap().Add(aNewFaceIndex);
607             }
608           }
609         }
610         anIndices->ChangeMap(aNewPackedMap);
611       }
612       return aRes;
613     } else {
614       // check is this modified or not
615       std::shared_ptr<GeomAPI_Shape> aNewShape = shape();
616       TopoDS_Shape anOldSh;
617       Handle(TNaming_NamedShape) aNS;
618       if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
619         anOldSh = aNS->Get();
620       }
621       if (aNewShape.get()) {
622         if (anOldSh.IsNull())
623           theModified = true;
624         else {
625           std::shared_ptr<GeomAPI_Shape> anOldShape(new GeomAPI_Shape);
626           anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOldSh));
627           theModified = !anOldShape->isEqual(aNewShape);
628         }
629       }
630       else if (!anOldSh.IsNull()) {
631         theModified = true;
632       }
633
634       // For correct naming selection, put the shape into the naming structure.
635       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
636       TNaming_Builder aBuilder(aLab);
637       aBuilder.Generated(aNewShape->impl<TopoDS_Shape>());
638     }
639     return shape() && !shape()->isNull();
640   }
641   // construction: identification by the results indexes, recompute faces and
642   // take the face that more close by the indexes
643   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
644   FeaturePtr aContextFeature = document()->feature(aThisPtr);
645
646   // sketch sub-element
647   if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
648   {
649     // update the referenced object if it is sub
650     Handle(TDF_Reference) aRef;
651     if (aLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
652       int aFaceIndex = aRef->Get().Tag();
653       // don't check selection ,since face may disappear, but the shape stays correct
654       Model_ResultConstruction::update(aFaceIndex, theExtDoc, theModified);
655     }
656     // getting a type of selected shape
657     Handle(TDataStd_Integer) aTypeAttr;
658     if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
659       return false;
660     }
661     TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
662     // selected indexes will be needed in each "if"
663     Handle(TDataStd_IntPackedMap) aSubIds;
664     std::shared_ptr<GeomAPI_Shape> aNewSelected;
665     bool aNoIndexes =
666       !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
667     // for now working only with composite features
668     CompositeFeaturePtr aComposite =
669       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
670     if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
671       return false;
672     }
673
674     if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) {
675       // compound is for the whole sketch selection
676       // If this is a wire with plane defined then it is a sketch-like object
677       if (!facesNum()) // no faces, update can not work correctly
678         return false;
679       // if there is no edges indexes, any face can be used: take the first
680       std::shared_ptr<GeomAPI_Shape> aNewSelected;
681       if (aNoIndexes) {
682         aNewSelected = face(0);
683       } else { // searching for most looks-like initial face by the indexes
684         // prepare edges of the current result for the fast searching
685         // curves and orientations of edges
686         NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
687         const int aSubNum = aComposite->numberOfSubs();
688         for(int a = 0; a < aSubNum; a++) {
689           int aSubID = aComposite->subFeatureId(a);
690           if (aSubIds->Contains(aSubID)) {
691             FeaturePtr aSub = aComposite->subFeature(a);
692             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
693             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
694             for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
695               ResultConstructionPtr aConstr =
696                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
697               if (aConstr->shape() && aConstr->shape()->isEdge()) {
698                 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
699                 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
700                 if (!anEdge.IsNull()) {
701                   Standard_Real aFirst, aLast;
702                   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
703                   // searching for orientation information
704                   int anOrient = 0;
705                   Handle(TDataStd_Integer) anInt;
706                   if (aLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)) {
707                     anOrient = anInt->Get();
708                   }
709                   allCurves.Bind(aCurve, anOrient);
710                 }
711               }
712             }
713           }
714         }
715         aNewSelected = Model_SelectionNaming::findAppropriateFace(
716           aThisPtr, allCurves, aShapeType == TopAbs_WIRE);
717       }
718       if (aNewSelected) { // store this new selection
719         select(aNewSelected, theExtDoc, theIndex);
720         theModified = true;
721         return true;
722       } else {
723         // if the selection is not found, put the empty shape:
724         // it's better to have disappeared shape, than the old, the lost one
725         TNaming_Builder anEmptyBuilder(aLab);
726         return false;
727       }
728     } else if (aShapeType == TopAbs_EDGE) {
729       // just reselect the edge by the id
730       const int aSubNum = aComposite->numberOfSubs();
731       for(int a = 0; a < aSubNum; a++) {
732         // if aSubIds take any, the first appropriate
733         if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
734           // found the appropriate feature
735           FeaturePtr aFeature = aComposite->subFeature(a);
736           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
737             aFeature->results().cbegin();
738           for(;aResIter != aFeature->results().cend(); aResIter++) {
739             ResultConstructionPtr aRes =
740               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
741             if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
742               select(aRes->shape(), theExtDoc, theIndex);
743               theModified = true;
744               return true;
745             }
746           }
747         }
748       }
749     } else if (aShapeType == TopAbs_VERTEX) {
750       // just reselect the vertex by the id of edge
751       const int aSubNum = aComposite->numberOfSubs();
752       for(int a = 0; a < aSubNum; a++) {
753         // if aSubIds take any, the first appropriate
754         int aFeatureID = aComposite->subFeatureId(a);
755         if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
756           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
757           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
758             // searching for deltas
759             int aVertexNum = 0;
760             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
761             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
762             // found the feature with appropriate edge
763             FeaturePtr aFeature = aComposite->subFeature(a);
764             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
765               aFeature->results().cbegin();
766             for(;aResIter != aFeature->results().cend(); aResIter++) {
767               ResultConstructionPtr aRes =
768                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
769               if (aRes && aRes->shape()) {
770                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
771                   select(aRes->shape(), theExtDoc, theIndex);
772                   theModified = true;
773                   return true;
774                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
775                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
776                   int aVIndex = 1;
777                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
778                     if (aVIndex == aVertexNum) { // found!
779                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
780                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
781                       select(aVertex, theExtDoc, theIndex);
782                       theModified = true;
783                       return true;
784                     }
785                     aVIndex++;
786                   }
787                 }
788               }
789             }
790         }
791       }
792     }
793   } else { // simple construction element: the selected is that needed
794     select(shape(), theExtDoc, theIndex);
795     theModified = true;
796     return true;
797   }
798   return false; // unknown case
799 }