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