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