Salome HOME
Support of wide string
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
1 // Copyright (C) 2014-2019  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_BodyBuilder.h>
21
22 #include <Model_Data.h>
23 #include <Model_Document.h>
24 #include <ModelAPI_Session.h>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Iterator.hxx>
28 #include <TNaming_Tool.hxx>
29 #include <TNaming_SameShapeIterator.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_ExtStringList.hxx>
33 #include <TopoDS.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TDF_ChildIterator.hxx>
36 #include <TDF_ChildIDIterator.hxx>
37 #include <TDF_Reference.hxx>
38 #include <TDF_Tool.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_DataMapOfShapeListOfShape.hxx>
44 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
46 #include <TopTools_MapIteratorOfMapOfShape.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_IndexedMapOfShape.hxx>
49 #include <TopTools_DataMapOfShapeShape.hxx>
50 #include <TopExp.hxx>
51 #include <BRepTools.hxx>
52 #include <BRep_Tool.hxx>
53 #include <BRepTools_History.hxx>
54 #include <GeomAPI_Shape.h>
55 #include <GeomAPI_ShapeExplorer.h>
56 #include <GeomAlgoAPI_MakeShape.h>
57 #include <GeomAlgoAPI_SortListOfShapes.h>
58 #include <Config_PropManager.h>
59 // DEB
60 //#include <TCollection_AsciiString.hxx>
61 //#define DEB_IMPORT 1
62
63 /// reference to the shape in external document: sting list attribute identifier
64 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
65
66 static const int INVALID_TAG            = -1;
67 static const int GENERATED_VERTICES_TAG = 1;
68 static const int GENERATED_EDGES_TAG    = 2;
69 static const int GENERATED_FACES_TAG    = 3;
70 static const int MODIFIED_VERTICES_TAG  = 4;
71 static const int MODIFIED_EDGES_TAG     = 5;
72 static const int MODIFIED_FACES_TAG     = 6;
73 static const int DELETED_TAG            = 7;
74 static const int PRIMITIVES_START_TAG   = 11;
75
76 static int getGenerationTag(const TopoDS_Shape& theShape) {
77   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
78   switch (aShapeType) {
79     case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
80     case TopAbs_EDGE:   return GENERATED_EDGES_TAG;
81     case TopAbs_FACE:   return GENERATED_FACES_TAG;
82   }
83
84   return INVALID_TAG;
85 }
86
87 static int getModificationTag(const TopoDS_Shape& theShape) {
88   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
89   switch (aShapeType) {
90     case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
91     case TopAbs_EDGE:   return MODIFIED_EDGES_TAG;
92     case TopAbs_FACE:   return MODIFIED_FACES_TAG;
93   }
94
95   return INVALID_TAG;
96 }
97
98 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
99                             const TopoDS_Shape& theOldShape,
100                             const TopoDS_Shape& theNewShape)
101 {
102   for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
103     aNamingIt.More();
104     aNamingIt.Next())
105   {
106     if (aNamingIt.NewShape().IsSame(theNewShape)
107       && aNamingIt.OldShape().IsSame(theOldShape))
108     {
109       return true;
110     }
111   }
112
113   return false;
114 }
115
116 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
117 : ModelAPI_BodyBuilder(theOwner),
118   myFreePrimitiveTag(PRIMITIVES_START_TAG)
119 {
120 }
121
122 /// Checks that shape is presented in the tree with not-selection evolution
123 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
124 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
125   TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
126 {
127   bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
128   if (aResult) { //check evolution and a label of this shape
129     for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
130     {
131       static Handle(TNaming_NamedShape) aNS;
132       if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
133         if (aNS->Evolution() != TNaming_SELECTED) {
134           theOriginalLabel = aNS->Label();
135           return true;
136         }
137       }
138     }
139   }
140   if (!theAccess2.IsNull()) {
141     static const TDF_Label anEmpty;
142     return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
143   }
144   return false;
145 }
146
147 /// Stores entry to the external label in the entries list at this label
148 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
149 {
150   // store information about the external document reference to restore old shape on open
151   if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
152     Handle(TDataStd_ExtStringList) anEntries;
153     if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
154       anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
155     }
156     TCollection_AsciiString anEntry;
157     TDF_Tool::Entry(theExternal, anEntry);
158     // check it already contains this entry
159     TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
160     for(; anIter.More(); anIter.Next())
161       if (anIter.Value() == anEntry)
162         break;
163     if (!anIter.More()) {
164       anEntries->Append(anEntry);
165     }
166   }
167 }
168
169 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
170                               const bool theIsStoreSameShapes)
171 {
172   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
173   if (aData) {
174     TDF_Label aShapeLab = aData->shapeLab();
175     // clean builders
176     clean();
177     // store the new shape as primitive
178     TNaming_Builder aBuilder(aShapeLab);
179     if (!theShape)
180       return;  // bad shape
181     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
182     if (aShape.IsNull())
183       return;  // null shape inside
184
185     if(!theIsStoreSameShapes) {
186       Handle(TNaming_NamedShape) aNS;
187       if (TNaming_Tool::HasLabel(aShapeLab, aShape))
188         aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
189       // the last condition is for the issue 2751 : existing shape may be found in compound-NS
190       if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
191         // This shape is already in document, store reference instead of shape;
192         const TDF_Label aFoundLabel = aNS->Label();
193         TDF_Reference::Set(aShapeLab, aFoundLabel);
194         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
195         return;
196       }
197     }
198
199     aBuilder.Generated(aShape);
200     // register name
201     aShapeLab.ForgetAttribute(TDF_Reference::GetID());
202     if(!aBuilder.NamedShape()->IsEmpty()) {
203       Handle(TDataStd_Name) anAttr;
204       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
205         std::wstring aName ((wchar_t*)anAttr->Get().ToExtString());
206         if(!aName.empty()) {
207           std::shared_ptr<Model_Document> aDoc =
208             std::dynamic_pointer_cast<Model_Document>(document());
209           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
210         }
211       }
212     }
213   }
214 }
215
216 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
217   const GeomShapePtr& theToShape, const bool theIsCleanStored)
218 {
219   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
220   if (aData) {
221     TDF_Label aShapeLab = aData->shapeLab();
222     // clean builders
223     if (theIsCleanStored)
224       clean();
225     TNaming_Builder* aBuilder = builder(0);
226     if (!theFromShape || !theToShape)
227       return;  // bad shape
228     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
229     if (aShapeBasis.IsNull())
230       return;  // null shape inside
231     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
232     if (aShapeNew.IsNull())
233       return;  // null shape inside
234
235     // There is no sense to write history if old shape does not exist in the document.
236     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
237       ModelAPI_Session::get()->moduleDocument())->generalLabel();
238     TDF_Label anOriginalLabel;
239     if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
240       if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
241         aBuilder->Generated(aShapeNew);
242       }
243     } else {
244       if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
245         myBuilders.erase(0);
246         aBuilder = builder(0);
247       }
248
249       aBuilder->Generated(aShapeBasis, aShapeNew);
250       // store information about the external document reference to restore old shape on open
251       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
252     }
253
254     // register name
255     if(!aBuilder->NamedShape()->IsEmpty()) {
256       Handle(TDataStd_Name) anAttr;
257       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
258         std::wstring aName((wchar_t*)anAttr->Get().ToExtString());
259         if(!aName.empty()) {
260           std::shared_ptr<Model_Document> aDoc =
261             std::dynamic_pointer_cast<Model_Document>(document());
262           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
263         }
264       }
265     }
266   }
267 }
268
269 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
270   const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
271 {
272   bool aStored = false;
273   std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
274   for (; anOldIter != theFromShapes.cend(); anOldIter++) {
275     bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
276     if (!aStore) {
277       ListOfShape aNews; // check this old really generates theToShape
278       theMakeShape->generated(*anOldIter, aNews);
279       ListOfShape::iterator aNewIter = aNews.begin();
280       for (; aNewIter != aNews.end(); aNewIter++) {
281         if (theToShape->isSame(*aNewIter))
282           break;
283       }
284       aStore = aNewIter != aNews.end();
285     }
286     if (aStore) {
287       storeGenerated(*anOldIter, theToShape, !aStored);
288       TNaming_Builder* aBuilder = builder(0);
289       aStored = !aBuilder->NamedShape()->IsEmpty();
290     }
291   }
292   if (!aStored) { // store as PRIMITIVE, but clean in any way
293     store(theToShape);
294     return;
295   }
296 }
297
298 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
299 {
300   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
301   if (aFind == myBuilders.end()) {
302     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
303     myBuilders[theTag] = new TNaming_Builder(
304       theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
305     aFind = myBuilders.find(theTag);
306   }
307   return aFind->second;
308 }
309
310 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
311                                       const GeomShapePtr& theNewShape,
312                                       const bool theIsCleanStored)
313 {
314   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
315   if (aData) {
316     // clean builders
317     if (theIsCleanStored) clean();
318     TNaming_Builder* aBuilder = builder(0);
319     if (!theOldShape || !theNewShape)
320       return;  // bad shape
321     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
322     if (aShapeOld.IsNull())
323       return;  // null shape inside
324     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
325     if (aShapeNew.IsNull())
326       return;  // null shape inside
327
328     // There is no sense to write history if old shape does not exist in the document.
329     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
330       ModelAPI_Session::get()->moduleDocument())->generalLabel();
331     TDF_Label anOriginalLabel;
332     if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
333       if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
334         aBuilder->Generated(aShapeNew);
335       }
336     } else {
337       if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
338         myBuilders.erase(0);
339         aBuilder = builder(0);
340       }
341
342       aBuilder->Modify(aShapeOld, aShapeNew);
343       // store information about the external document reference to restore old shape on open
344       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
345     }
346
347     if(!aBuilder->NamedShape()->IsEmpty()) {
348       Handle(TDataStd_Name) anAttr;
349       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
350         std::wstring aName ((wchar_t*)anAttr->Get().ToExtString());
351         if(!aName.empty()) {
352           std::shared_ptr<Model_Document> aDoc =
353             std::dynamic_pointer_cast<Model_Document>(document());
354           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
355         }
356       }
357     }
358   }
359 }
360
361 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
362   const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
363 {
364   bool aStored = false;
365   std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
366   for(; anOldIter != theOldShapes.cend(); anOldIter++) {
367     // compounds may cause crash if call "modified"
368     bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
369                 (*anOldIter)->isCompSolid();
370     if (!aStore) {
371       ListOfShape aNews; // check this old really modifies theNewShape
372       theMakeShape->modified(*anOldIter, aNews);
373       ListOfShape::iterator aNewIter = aNews.begin();
374       for(; aNewIter != aNews.end(); aNewIter++) {
375         if (theNewShape->isSame(*aNewIter))
376           break;
377       }
378       aStore = aNewIter != aNews.end();
379     }
380     if (aStore) {
381       storeModified(*anOldIter, theNewShape, !aStored);
382       TNaming_Builder* aBuilder = builder(0);
383       aStored = !aBuilder->NamedShape()->IsEmpty();
384     }
385   }
386   if (!aStored) {
387     // check the new shape is already in the tree, so, no need to store primitive, just reference
388     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
389     if (aData.get()) {
390       TDF_Label aShapeLab = aData->shapeLab();
391       TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
392       Handle(TNaming_NamedShape) aNS;
393       if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
394         aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
395       // the last condition is for the issue 2751 : existing shape may be found in compound-NS
396       if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
397         // This shape is already in document, store reference instead of shape;
398         const TDF_Label aFoundLabel = aNS->Label();
399         TDF_Reference::Set(aShapeLab, aFoundLabel);
400         myBuilders.erase(0);
401         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
402         return;
403       }
404     }
405     store(theNewShape); // store as PRIMITIVE, but clean in any way
406     return;
407   }
408 }
409
410 void Model_BodyBuilder::clean()
411 {
412   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
413   if (aLab.IsNull())
414     return;
415   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
416   for(; aBuilder != myBuilders.end(); aBuilder++) {
417     Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
418     delete aBuilder->second;
419     if (!aNS.IsNull() && !aNS->Label().IsNull())
420       aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
421   }
422   myBuilders.clear();
423   myPrimitivesNamesIndexMap.clear();
424   // remove the old reference (if any)
425   aLab.ForgetAttribute(TDF_Reference::GetID());
426   myFreePrimitiveTag = PRIMITIVES_START_TAG;
427   TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
428   for(; anEntriesIter.More(); anEntriesIter.Next()) {
429     anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
430   }
431 }
432
433 void Model_BodyBuilder::cleanCash()
434 {
435   myPrimitivesNamesIndexMap.clear();
436 }
437
438 Model_BodyBuilder::~Model_BodyBuilder()
439 {
440   clean();
441 }
442
443 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
444 {
445   std::string aName = theName;
446   std::string aPrefix = "";
447   switch (theTag) {
448     case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
449     case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
450     case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
451     case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
452     case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
453     case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
454   }
455   aName.insert(0, aPrefix);
456
457   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
458 }
459 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
460                                   const std::string& theName,
461                                   const bool theCheckIsInResult)
462 {
463   GeomShapePtr aResultShape = shape();
464   if (theCheckIsInResult) {
465     bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
466     if (aNewShapeIsNotInResultShape) {
467       return false;
468     }
469   }
470
471   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
472   builder(myFreePrimitiveTag)->Generated(aShape);
473   if (!theName.empty()) {
474     std::string aName = theName;
475     if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
476       IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
477       aName += "_" + std::to_string(++(anIndexTags.index));
478       anIndexTags.tags.push_back(myFreePrimitiveTag);
479       if (anIndexTags.index == 2) {
480         buildName(anIndexTags.tags.front(), theName + "_1");
481       }
482     }
483     else {
484       IndexTags anIndexTags;
485       anIndexTags.index = 1;
486       anIndexTags.tags.push_back(myFreePrimitiveTag);
487       myPrimitivesNamesIndexMap[theName] = anIndexTags;
488     }
489
490     buildName(myFreePrimitiveTag, aName);
491   }
492   ++myFreePrimitiveTag;
493   return true;
494 }
495
496 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
497                                   const GeomShapePtr& theNewShape,
498                                   const std::string& theName)
499 {
500   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
501   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
502   TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
503   int aTag;
504   if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
505     // TODO: This is a workaround. New shape should be only vertex, edge or face.
506     TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
507     aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
508     for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
509       builder(aTag)->Generated(anOldShape, anExp.Current());
510     }
511     buildName(aTag, theName);
512   } else {
513     aTag = getGenerationTag(aNewShape);
514     if (aTag == INVALID_TAG) return;
515     builder(aTag)->Generated(anOldShape, aNewShape);
516     buildName(aTag, theName);
517   }
518 }
519
520 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
521                                  const GeomShapePtr& theNewShape,
522                                  const std::string& theName)
523 {
524   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
525   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
526   int aTag = getModificationTag(aNewShape);
527   if (aTag == INVALID_TAG) return;
528   builder(aTag)->Modify(anOldShape, aNewShape);
529   buildName(aTag, theName);
530 }
531
532 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
533                                           const GeomShapePtr& theOldShape,
534                                           const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
535                                           const GeomShapePtr& theShapesToExclude)
536 {
537   TopTools_MapOfShape anAlreadyProcessedShapes;
538   GeomShapePtr aResultShape = shape();
539   for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
540        anExp.more();
541        anExp.next())
542   {
543     GeomShapePtr anOldSubShape = anExp.current();
544     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
545     if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
546         || !theAlgo->isDeleted(anOldSubShape)
547         || aResultShape->isSubShape(anOldSubShape, false)
548         || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
549     {
550       continue;
551     }
552
553     ListOfShape aNewShapes;
554     if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
555       theAlgo->modified(anOldSubShape, aNewShapes);
556     }
557
558     if (aNewShapes.size() == 0
559         || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
560       builder(DELETED_TAG)->Delete(anOldSubShape_);
561     }
562   }
563 }
564
565 // Keep only the shapes with minimal shape type
566 static void keepTopLevelShapes(ListOfShape& theShapes,
567                                const TopoDS_Shape& theRoot,
568                                const GeomShapePtr& theResultShape = GeomShapePtr())
569 {
570   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
571   ListOfShape::iterator anIt = theShapes.begin();
572   while (anIt != theShapes.end()) {
573     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
574     bool aSkip = aNewShape.IsNull() ||
575       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
576     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
577         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
578       ListOfShape::iterator aRemoveIt = anIt++;
579       theShapes.erase(aRemoveIt);
580     } else {
581       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
582       if (aType < aKeepShapeType) {
583         // found a shape with lesser shape type => remove all previous shapes
584         aKeepShapeType = aType;
585         theShapes.erase(theShapes.begin(), anIt);
586         ++anIt;
587       } else if (aType > aKeepShapeType) {
588         // shapes with greater shape type should be removed from the list
589         ListOfShape::iterator aRemoveIt = anIt++;
590         theShapes.erase(aRemoveIt);
591       } else
592         ++anIt;
593     }
594   }
595 }
596
597 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
598                                            const GeomShapePtr& theOldShape,
599                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
600                                            const std::string& theName)
601 {
602   GeomShapePtr aResultShape = shape();
603   GeomShapePtr aShapeToExplore = theOldShape;
604   if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
605     // use optimized set of old shapes for this
606     GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
607                                                       aResultShape,
608                                                       theShapeTypeToExplore);
609     if (aCompound.get()) aShapeToExplore = aCompound;
610   }
611
612   TopTools_MapOfShape anAlreadyProcessedShapes;
613   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
614   for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
615        anOldShapeExp.more();
616        anOldShapeExp.next())
617   {
618     GeomShapePtr anOldSubShape = anOldShapeExp.current();
619     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
620
621     // There is no sense to write history if shape already processed
622     // or old shape does not exist in the document.
623     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
624     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
625       ModelAPI_Session::get()->moduleDocument())->generalLabel();
626     TDF_Label anOriginalLabel;
627     bool anOldSubShapeNotInTree =
628       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
629     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
630       continue;
631     }
632
633     // Get new shapes.
634     ListOfShape aNewShapes;
635     theAlgo->modified(anOldSubShape, aNewShapes);
636
637     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
638          aNewShapesIt != aNewShapes.cend();
639          ++aNewShapesIt)
640     {
641       GeomShapePtr aNewShape = *aNewShapesIt;
642       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
643       bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
644
645       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
646       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
647       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
648         continue;
649
650       if (aResultShape->isSame(aNewShape))
651         continue; // it is stored on the root level (2241 - history propagation issue)
652
653       int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
654       TNaming_Builder*aBuilder = builder(aTag);
655       if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
656         continue; // new shape was already stored.
657
658       buildName(aTag, theName);
659       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
660                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
661       // store information about the external document reference to restore old shape on open
662       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
663     }
664   }
665 }
666
667 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
668                                             const GeomShapePtr& theOldShape,
669                                             const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
670                                             const std::string& theName,
671                                             const bool theSaveOldIfNotInTree)
672 {
673   GeomShapePtr aResultShape = shape();
674   TopTools_MapOfShape anAlreadyProcessedShapes;
675   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
676   for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
677        anOldShapeExp.more();
678        anOldShapeExp.next())
679   {
680     GeomShapePtr anOldSubShape = anOldShapeExp.current();
681     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
682
683     // There is no sense to write history if shape already processed
684     // or old shape does not exist in the document.
685     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
686     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
687       ModelAPI_Session::get()->moduleDocument())->generalLabel();
688     TDF_Label anOriginalLabel;
689     bool anOldSubShapeNotInTree =
690       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
691     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
692       if (theSaveOldIfNotInTree) {
693         std::string aSelectionName = theName + "Selected";
694         generated(anOldSubShape, aSelectionName, false);
695       } else
696         continue;
697     }
698
699     // Get new shapes.
700     ListOfShape aNewShapes;
701     theAlgo->generated(anOldSubShape, aNewShapes);
702
703     keepTopLevelShapes(aNewShapes, anOldSubShape_);
704
705     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
706          aNewShapesIt != aNewShapes.cend();
707          ++aNewShapesIt)
708     {
709       GeomShapePtr aNewShape = *aNewShapesIt;
710       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
711
712       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
713       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
714       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
715         continue;
716       }
717
718       if (aResultShape->isSame(aNewShape))
719         continue; // it is stored on the root level
720
721       TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
722       if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
723         // TODO: This is a workaround. New shape should be only edge or face.
724         TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
725                                                                             : TopAbs_FACE;
726         int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
727         for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
728           builder(aTag)->Generated(anOldSubShape_, anExp.Current());
729           // store information about the external document reference to restore old shape on open
730           storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
731         }
732         buildName(aTag, theName);
733       } else {
734         int aTag = getGenerationTag(aNewShape_);
735         if (aTag == INVALID_TAG) return;
736         builder(aTag)->Generated(anOldSubShape_, aNewShape_);
737         buildName(aTag, theName);
738         // store information about the external document reference to restore old shape on open
739         storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
740       }
741     }
742   }
743 }
744
745 // LCOV_EXCL_START
746 //=======================================================================
747 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
748   const TopAbs_ShapeEnum        theGeneratedFrom,
749   TopTools_DataMapOfShapeShape& theDangles)
750 {
751   theDangles.Clear();
752   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
753   TopAbs_ShapeEnum GeneratedTo;
754   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
755   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
756   else return Standard_False;
757   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
758   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
759     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
760     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
761     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
762   }
763   return theDangles.Extent();
764 }
765
766 //=======================================================================
767 void loadGeneratedDangleShapes(
768   const TopoDS_Shape&      theShapeIn,
769   const TopAbs_ShapeEnum   theGeneratedFrom,
770   TNaming_Builder *        theBuilder)
771 {
772   TopTools_DataMapOfShapeShape dangles;
773   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
774   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
775   for (; itr.More(); itr.Next())
776     theBuilder->Generated(itr.Key(), itr.Value());
777 }
778 // LCOV_EXCL_STOP
779
780 //=======================================================================
781 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
782                                        const std::string& theName)
783 {
784   if(theShape->isNull()) return;
785   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
786   std::string aName;
787   if (aShape.ShapeType() == TopAbs_SOLID) {
788     TopExp_Explorer expl(aShape, TopAbs_FACE);
789     for (; expl.More(); expl.Next()) {
790       builder(myFreePrimitiveTag)->Generated(expl.Current());
791       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
792       aName = theName + "_" + aStr.ToCString();
793       buildName(myFreePrimitiveTag, aName);
794       ++myFreePrimitiveTag;
795     }
796   }
797   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
798     // load faces and all the free edges
799     TopTools_IndexedMapOfShape Faces;
800     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
801     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
802       TopExp_Explorer expl(aShape, TopAbs_FACE);
803       for (; expl.More(); expl.Next()) {
804         builder(myFreePrimitiveTag)->Generated(expl.Current());
805         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
806         aName = theName + "_" + aStr.ToCString();
807         buildName(myFreePrimitiveTag, aName);
808         ++myFreePrimitiveTag;
809       }
810     }
811     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
812     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
813     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
814     {
815       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
816       if (aLL.Extent() < 2) {
817         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
818           continue;
819         builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
820         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
821         aName = theName + "_" + aStr.ToCString();
822         buildName(myFreePrimitiveTag, aName);
823         ++myFreePrimitiveTag;
824       } else {
825         TopTools_ListIteratorOfListOfShape anIter(aLL);
826         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
827         anIter.Next();
828         if(aFace.IsEqual(anIter.Value())) {
829           builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
830           TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
831           aName = theName + "_" + aStr.ToCString();
832           buildName(myFreePrimitiveTag, aName);
833           ++myFreePrimitiveTag;
834         }
835       }
836     }
837   } else if (aShape.ShapeType() == TopAbs_WIRE) {
838     TopTools_IndexedMapOfShape Edges;
839     BRepTools::Map3DEdges(aShape, Edges);
840     if (Edges.Extent() == 1) {
841       builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
842       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
843       for (; expl.More(); expl.Next()) {
844         builder(myFreePrimitiveTag)->Generated(expl.Current());
845         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
846         aName = theName + "_" + aStr.ToCString();
847         buildName(myFreePrimitiveTag, aName);
848         ++myFreePrimitiveTag;
849       }
850     } else {
851       TopExp_Explorer expl(aShape, TopAbs_EDGE);
852       for (; expl.More(); expl.Next()) {
853         builder(myFreePrimitiveTag)->Generated(expl.Current());
854         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
855         aName = theName + "_" + aStr.ToCString();
856         buildName(myFreePrimitiveTag, aName);
857         ++myFreePrimitiveTag;
858       }
859       // and load generated vertices.
860       TopTools_DataMapOfShapeShape generated;
861       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
862       {
863         TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
864         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
865       }
866     }
867   } else if (aShape.ShapeType() == TopAbs_EDGE) {
868     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
869     for (; expl.More(); expl.Next()) {
870       builder(myFreePrimitiveTag)->Generated(expl.Current());
871       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
872       aName = theName + "_" + aStr.ToCString();
873       buildName(myFreePrimitiveTag, aName);
874       ++myFreePrimitiveTag;
875     }
876   }
877 }
878
879 //=======================================================================
880 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
881   TopTools_ListOfShape&   theList)
882 {
883   theList.Clear();
884   // edges -> ancestor faces list
885   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
886   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
887   // keeps the shapes which are already in the resulting list
888   TopTools_MapOfShape alreadyThere;
889   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
890   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
891
892   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
893   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
894     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
895     if (ancestors.Extent() < 2)
896       continue;
897     Standard_Integer anID = 0;
898     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
899       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
900     }
901     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
902       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
903         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
904       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
905       for(; aSameEdge.More(); aSameEdge.Next()) {
906         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
907           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
908         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
909           break;
910
911         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
912         for(; aFaceIter1.More(); aFaceIter1.Next()) {
913           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
914           for(; aFaceIter2.More(); aFaceIter2.Next()) {
915             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
916               break;
917           }
918           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
919             break;
920         }
921         if (!aFaceIter1.More()) { // all the faces are same => put to the result
922           if (alreadyThere.Add(aSameEdge.Value()))
923             theList.Append(aSameEdge.Value());
924           if (alreadyThere.Add(anAncestorsIter.Key()))
925             theList.Append(anAncestorsIter.Key());
926         }
927       }
928     } else { // ID is unique, just add this edge
929       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
930     }
931     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
932   }
933   return theList.Extent();
934 }
935
936 //=======================================================================
937 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
938 {
939   GeomShapePtr aShapePtr = shape();
940   if (theShape->isNull() || !aShapePtr.get())
941     return;
942   TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
943   if (aShape.IsNull())
944     return;
945   std::string aName;
946   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
947     TopoDS_Iterator itr(aShape);
948     for (; itr.More(); itr.Next()) {
949       builder(myFreePrimitiveTag)->Generated(itr.Value());
950       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
951       aName = theName + "_" + aStr.ToCString();
952       buildName(myFreePrimitiveTag, aName);
953       ++myFreePrimitiveTag;
954       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
955         itr.Value().ShapeType() == TopAbs_COMPSOLID)
956       {
957         GeomShapePtr itrShape(new GeomAPI_Shape());
958         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
959         loadFirstLevel(itrShape, theName);
960       } else {
961         GeomShapePtr itrShape(new GeomAPI_Shape());
962         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
963         loadNextLevels(itrShape, theName);
964       }
965     }
966   } else {
967     GeomShapePtr itrShape(new GeomAPI_Shape());
968     itrShape->setImpl(new TopoDS_Shape(aShape));
969     loadNextLevels(itrShape, theName);
970   }
971   TopTools_ListOfShape   aList;
972   if(findAmbiguities(aShape, aList)) {
973     TopTools_ListIteratorOfListOfShape it(aList);
974     for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
975       builder(myFreePrimitiveTag)->Generated(it.Value());
976       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
977       aName = theName + "_" + aStr.ToCString();
978       buildName(myFreePrimitiveTag, aName);
979     }
980   }
981 }
982
983 GeomShapePtr Model_BodyBuilder::shape()
984 {
985   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
986   if (aData && aData->isValid()) {
987     TDF_Label aShapeLab = aData->shapeLab();
988     Handle(TDF_Reference) aRef;
989     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
990       aShapeLab = aRef->Get();
991     }
992     Handle(TNaming_NamedShape) aName;
993     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
994       TopoDS_Shape aShape = aName->Get();
995       if (!aShape.IsNull()) {
996         GeomShapePtr aRes(new GeomAPI_Shape);
997         aRes->setImpl(new TopoDS_Shape(aShape));
998         return aRes;
999       }
1000     }
1001   }
1002   return GeomShapePtr();
1003 }