Salome HOME
Merge remote-tracking branch 'remotes/origin/Dev_2.8.0' into Dev_2.8.0
[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(TDF_Label& theLab, const bool isSelectionMode, const TopoDS_Shape& aSub,
271   std::shared_ptr<Model_Document> theDoc, std::string theFullName)
272 {
273   TNaming_Builder aBuilder(theLab);
274   if (isSelectionMode)
275     aBuilder.Select(aSub, aSub);
276   else
277     aBuilder.Generated(aSub);
278   theDoc->addNamingName(theLab, theFullName.c_str());
279   TDataStd_Name::Set(theLab, theFullName.c_str());
280 }
281
282
283 TDF_Label Model_ResultConstruction::startLabel(
284   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theExternal)
285 {
286   theExternal = theExtDoc.get() && theExtDoc != document();
287   if (theExternal) { // external document is used
288     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theExtDoc);
289     return aDoc->extConstructionsLabel();
290   }
291   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
292   return aData->label();
293 }
294
295 int Model_ResultConstruction::select(const std::shared_ptr<GeomAPI_Shape>& theSubShape,
296   const std::shared_ptr<ModelAPI_Document> theExtDoc, const int theIndex)
297 {
298   int anIndex; // resulting index of the sub-label
299   TopoDS_Shape aSubShape;
300   if (theSubShape.get()) {
301     aSubShape = theSubShape->impl<TopoDS_Shape>();
302   } else if (shape().get()) {
303     aSubShape = shape()->impl<TopoDS_Shape>();
304   }
305   // if external document requires this selection, put the naming structures to this doc
306   // to support the naming mechanism in this document correctly
307   bool anExternal;
308   TDF_Label aDataLab = startLabel(theExtDoc, anExternal);
309   if (theIndex == -1) {
310     anIndex = anExternal ? 2 : 1; // for the external doc don't mind about the main shape
311
312     if (theSubShape.get() || anExternal) { // searching for already selected sub (or whole for ext)
313       // iterate all the already presented shapes to see the same
314       TDF_ChildIterator aSubsIter(aDataLab, Standard_False);
315       for(; aSubsIter.More(); aSubsIter.Next()) {
316         const TDF_Label aLab = aSubsIter.Value();
317         if (aLab.Tag() == 1) // skip the root shape label
318           continue;
319         Handle(TNaming_NamedShape) aNS;
320         if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
321           if (aNS->Get().IsSame(aSubShape)) {
322             return aLab.Tag() - 1; // found exactly the needed shape, nothing else to do
323           }
324         }
325         anIndex = aLab.Tag(); // searching for the latest index
326       }
327       anIndex = (anIndex == 1) ? 2 : (anIndex + 1); // next after 1-root, or next after all
328     }
329   } else {
330     anIndex = theIndex + 1;
331   }
332
333   // set the naming structure at index
334   TDF_Label aLab = aDataLab.FindChild(anIndex, Standard_True);
335
336   // if the subshape is part of a result face, select the whole face (#1997)
337   bool isSelectionMode = false; // and other don't set shapes - all the naming is in face label
338   if (!aSubShape.IsNull() && aSubShape.ShapeType() > TopAbs_FACE) {
339     for(int aFaceIndex = 0; aFaceIndex < facesNum(); aFaceIndex++) {
340       TopExp_Explorer anExp(face(aFaceIndex)->impl<TopoDS_Shape>(), aSubShape.ShapeType());
341       for(; anExp.More(); anExp.Next()) {
342         if (aSubShape.IsSame(anExp.Current())) { // this is the case: select the whole face
343           // here just store the face index (to update face if update of edge is needed)
344           TNaming_Builder aBuilder(aLab);
345           aBuilder.Select(aSubShape, aSubShape);
346           int aFaceSelID = select(face(aFaceIndex), theExtDoc, -1);
347           TDF_Reference::Set(aLab, aLab.Father().FindChild(aFaceSelID));
348           isSelectionMode = true;
349           break;
350         }
351       }
352     }
353   }
354
355   // external full result is not identified by index == 0, so, add here the ID
356   if (!theSubShape.get()) {
357     TDataStd_UAttribute::Set(aLab, kFULL_RESULT_ID);
358     // empty NS
359     TNaming_Builder aBuilder(aLab);
360     // store all sub-faces naming since faces may be used for extrusion, where all edges are needed
361     Handle(TDataStd_IntPackedMap) anIndices = TDataStd_IntPackedMap::Set(aLab);
362     std::list<int> aFacesIndexes;
363     for(int a = 0; a < facesNum(); a++) {
364       anIndices->Add(select(face(a), theExtDoc, -1));
365     }
366     return anIndex - 1;
367   }
368
369   { // this to have erased Builder after the shape was generated (NS on this label may be changed)
370     TNaming_Builder aBuilder(aLab);
371     if (aSubShape.IsNull()) {
372       return anIndex - 1; // just keep empty named shape
373     }
374     // wire never happens as sub, it must be generated to be found
375     // by SelectionNaming TNaming_Tool::NamedShape
376     if (isSelectionMode && aSubShape.ShapeType() != TopAbs_WIRE) {
377       aBuilder.Select(aSubShape, aSubShape);
378     } else {
379       aBuilder.Generated(aSubShape);
380     }
381   }
382
383   if (anIndex == 1 && isInfinite()) { // infinitive results has no sub-selection
384     return anIndex - 1;
385   }
386   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
387   FeaturePtr aThisFeature = document()->feature(aThisPtr);
388   CompositeFeaturePtr aComposite =
389     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
390   if (!aComposite || aComposite->numberOfSubs() == 0) {
391     // saving of context is enough: result construction contains exactly the needed shape
392     return anIndex - 1;
393   }
394
395   // identify the results of sub-object of the composite by edges
396   // save type of the selected shape in integer attribute
397   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
398   TDataStd_Integer::Set(aLab, (int)aShapeType);
399   gp_Pnt aVertexPos;
400   TColStd_MapOfTransient allCurves;
401   if (aShapeType == TopAbs_VERTEX) { // compare positions
402     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
403   } else {
404     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
405       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
406       Standard_Real aFirst, aLast;
407       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
408       allCurves.Add(aCurve);
409     }
410   }
411   std::shared_ptr<Model_Document> aMyDoc =
412     std::dynamic_pointer_cast<Model_Document>(document());
413   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
414   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
415   const int aSubNum = aComposite->numberOfSubs();
416   // subs are placed one by one  because of #2248): sketch curve may produce several edges
417   int aSubLabId = 1;
418
419   for(int a = 0; a < aSubNum; a++) {
420     FeaturePtr aSub = aComposite->subFeature(a);
421     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
422     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
423     // there may be many shapes (circle and center): register if at least one is in selection
424     for(; aRes != aResults.cend(); aRes++) {
425       ResultConstructionPtr aConstr =
426         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
427       if (!aConstr->shape()) {
428         continue;
429       }
430       if (aShapeType != TopAbs_VERTEX) {
431         if (aConstr->shape()->isEdge()) {
432           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
433           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
434           if (!anEdge.IsNull()) {
435             Standard_Real aFirst, aLast;
436             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
437             if (allCurves.Contains(aCurve)) {
438               int anID = aComposite->subFeatureId(a);
439               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
440                 // add edges to sub-label to support naming for edges selection
441                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
442                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
443                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
444                   Standard_Real aFirst, aLast;
445                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
446                   if (aFaceCurve == aCurve) {
447                     TDF_Label aSubLab = aLab.FindChild(anID);
448                     TDF_Label aShapeSubLab = aLab.FindChild(aSubLabId++);
449                     std::string aFullNameSub = fullName(aComposite, anEdge);
450                     saveSubName(aShapeSubLab, isSelectionMode, anEdge, aMyDoc, aFullNameSub);
451
452                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
453                     if (anOrient != 0) {
454                       // store the orientation of edge relatively to face if needed
455                       TDataStd_Integer::Set(aSubLab, anOrient);
456                     }
457                   }
458                 }
459               } else { // put vertices of the selected edge to sub-labels
460                 // add edges to sub-label to support naming for edges selection
461                 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
462                       anEdgeExp.More(); anEdgeExp.Next()) {
463                     TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
464                     TDF_Label aShapeSubLab = aLab.FindChild(aSubLabId++);
465                     std::string aFullNameSub = fullName(aComposite, aV);
466                     saveSubName(aShapeSubLab, isSelectionMode, aV, aMyDoc, aFullNameSub);
467                 }
468               }
469             }
470           }
471         }
472       }
473     }
474   }
475   std::string aFullName = fullName(aComposite, aSubShape, aRefs);
476   // store the selected as primitive
477   registerSubShape(aLab, aSubShape, aFullName, 0, aMyDoc, isSelectionMode);
478   return anIndex - 1;
479 }
480
481 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape(const int theIndex,
482   const std::shared_ptr<ModelAPI_Document> theExtDoc)
483 {
484   std::shared_ptr<GeomAPI_Shape> aResult;
485   if (theIndex == 0)
486     return aResult; // the whole shape, so, NULL
487
488   bool isExt;
489   TDF_Label aLab = startLabel(theExtDoc, isExt).FindChild(theIndex + 1);
490   if (!aLab.IsNull()) { // index is not bad
491     Handle(TNaming_NamedShape) aSelection;
492     if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
493       TopoDS_Shape aSelShape = aSelection->Get();
494       if (aSelShape.IsNull())
495         return aResult; // shape equal to context => null
496       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
497       aResult->setImpl(new TopoDS_Shape(aSelShape));
498     }
499   }
500
501   return aResult;
502 }
503
504 bool Model_ResultConstruction::update(const int theIndex,
505   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theModified)
506 {
507   theModified = false;
508   bool anExt;
509   TDF_Label aLab = startLabel(theExtDoc, anExt).FindChild(theIndex + 1, Standard_True);
510   if (theIndex == 0 || aLab.IsAttribute(kFULL_RESULT_ID)) { // full for external same as index == 0
511     // it is just reference to construction, not sub-shape
512     // if there is a sketch, the sketch-naming must be updated
513     if (!isInfinite()) {
514       // update all faces named by the whole result
515       bool aRes = true;
516       Handle(TDataStd_IntPackedMap) anIndices;
517       if (aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), anIndices)) {
518         NCollection_Map<TopoDS_Shape> aFaces; // collect faces, updated in the tree
519         TColStd_MapIteratorOfPackedMapOfInteger anIndexIter(anIndices->GetMap());
520         Handle(TColStd_HPackedMapOfInteger) aNewPackedMap =
521           new TColStd_HPackedMapOfInteger; // with only faces that are ok
522         // iterate to find existing faces, updated
523         for(; anIndexIter.More(); anIndexIter.Next()) {
524           if (update(anIndexIter.Key(), theExtDoc, theModified)) {
525             GeomShapePtr aFace = shape(anIndexIter.Key(), theExtDoc);
526             if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
527               aNewPackedMap->ChangeMap().Add(anIndexIter.Key());
528               aFaces.Add(aFace->impl<TopoDS_Shape>());
529             }
530           }
531         }
532         // then iterate all existing faces to find new faces
533         int aCurrentFacesNum = facesNum();
534         for(int a = 0; a < aCurrentFacesNum; a++) {
535           GeomShapePtr aFace = face(a);
536           if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
537             // add this one
538             int aNewFaceIndex = select(aFace, theExtDoc, -1);
539             if (aNewFaceIndex > 0) {
540               aNewPackedMap->ChangeMap().Add(aNewFaceIndex);
541             }
542           }
543         }
544         anIndices->ChangeMap(aNewPackedMap);
545       }
546       return aRes;
547     } else {
548       // For correct naming selection, put the shape into the naming structure.
549       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
550       TNaming_Builder aBuilder(aLab);
551       aBuilder.Generated(shape()->impl<TopoDS_Shape>());
552     }
553     return shape() && !shape()->isNull();
554   }
555   // construction: identification by the results indexes, recompute faces and
556   // take the face that more close by the indexes
557   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
558   FeaturePtr aContextFeature = document()->feature(aThisPtr);
559
560   // sketch sub-element
561   if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
562   {
563     // update the referenced object if it is sub
564     Handle(TDF_Reference) aRef;
565     if (aLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
566       int aFaceIndex = aRef->Get().Tag();
567       // don't check selection ,since face may disappear, but the shape stays correct
568       Model_ResultConstruction::update(aFaceIndex, theExtDoc, theModified);
569     }
570     // getting a type of selected shape
571     Handle(TDataStd_Integer) aTypeAttr;
572     if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
573       return false;
574     }
575     TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
576     // selected indexes will be needed in each "if"
577     Handle(TDataStd_IntPackedMap) aSubIds;
578     std::shared_ptr<GeomAPI_Shape> aNewSelected;
579     bool aNoIndexes =
580       !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
581     // for now working only with composite features
582     CompositeFeaturePtr aComposite =
583       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
584     if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
585       return false;
586     }
587
588     if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) {
589       // compound is for the whole sketch selection
590       // If this is a wire with plane defined then it is a sketch-like object
591       if (!facesNum()) // no faces, update can not work correctly
592         return false;
593       // if there is no edges indexes, any face can be used: take the first
594       std::shared_ptr<GeomAPI_Shape> aNewSelected;
595       if (aNoIndexes) {
596         aNewSelected = face(0);
597       } else { // searching for most looks-like initial face by the indexes
598         // prepare edges of the current result for the fast searching
599         // curves and orientations of edges
600         NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
601         const int aSubNum = aComposite->numberOfSubs();
602         for(int a = 0; a < aSubNum; a++) {
603           int aSubID = aComposite->subFeatureId(a);
604           if (aSubIds->Contains(aSubID)) {
605             FeaturePtr aSub = aComposite->subFeature(a);
606             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
607             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
608             for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
609               ResultConstructionPtr aConstr =
610                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
611               if (aConstr->shape() && aConstr->shape()->isEdge()) {
612                 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
613                 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
614                 if (!anEdge.IsNull()) {
615                   Standard_Real aFirst, aLast;
616                   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
617                   // searching for orientation information
618                   int anOrient = 0;
619                   Handle(TDataStd_Integer) anInt;
620                   if (aLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)) {
621                     anOrient = anInt->Get();
622                   }
623                   allCurves.Bind(aCurve, anOrient);
624                 }
625               }
626             }
627           }
628         }
629         aNewSelected = Model_SelectionNaming::findAppropriateFace(
630           aThisPtr, allCurves, aShapeType == TopAbs_WIRE);
631       }
632       if (aNewSelected) { // store this new selection
633         select(aNewSelected, theExtDoc, theIndex);
634         theModified = true;
635         return true;
636       } else {
637         // if the selection is not found, put the empty shape:
638         // it's better to have disappeared shape, than the old, the lost one
639         TNaming_Builder anEmptyBuilder(aLab);
640         return false;
641       }
642     } else if (aShapeType == TopAbs_EDGE) {
643       // just reselect the edge by the id
644       const int aSubNum = aComposite->numberOfSubs();
645       for(int a = 0; a < aSubNum; a++) {
646         // if aSubIds take any, the first appropriate
647         if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
648           // found the appropriate feature
649           FeaturePtr aFeature = aComposite->subFeature(a);
650           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
651             aFeature->results().cbegin();
652           for(;aResIter != aFeature->results().cend(); aResIter++) {
653             ResultConstructionPtr aRes =
654               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
655             if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
656               select(aRes->shape(), theExtDoc, theIndex);
657               theModified = true;
658               return true;
659             }
660           }
661         }
662       }
663     } else if (aShapeType == TopAbs_VERTEX) {
664       // just reselect the vertex by the id of edge
665       const int aSubNum = aComposite->numberOfSubs();
666       for(int a = 0; a < aSubNum; a++) {
667         // if aSubIds take any, the first appropriate
668         int aFeatureID = aComposite->subFeatureId(a);
669         if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
670           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
671           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
672             // searching for deltas
673             int aVertexNum = 0;
674             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
675             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
676             // found the feature with appropriate edge
677             FeaturePtr aFeature = aComposite->subFeature(a);
678             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
679               aFeature->results().cbegin();
680             for(;aResIter != aFeature->results().cend(); aResIter++) {
681               ResultConstructionPtr aRes =
682                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
683               if (aRes && aRes->shape()) {
684                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
685                   select(aRes->shape(), theExtDoc, theIndex);
686                   theModified = true;
687                   return true;
688                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
689                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
690                   int aVIndex = 1;
691                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
692                     if (aVIndex == aVertexNum) { // found!
693                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
694                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
695                       select(aVertex, theExtDoc, theIndex);
696                       theModified = true;
697                       return true;
698                     }
699                     aVIndex++;
700                   }
701                 }
702               }
703             }
704         }
705       }
706     }
707   } else { // simple construction element: the selected is that needed
708     select(shape(), theExtDoc, theIndex);
709     theModified = true;
710     return true;
711   }
712   return false; // unknown case
713 }