]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_BodyBuilder.cpp
Salome HOME
Fix for the issue #19989 : Sketch in error after edit and apply on Fuse (without...
[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 static TDF_Label builderLabel(DataPtr theData, const int theTag )
302 {
303   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
304   return theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
305 }
306
307 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
308 {
309   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
310   if (aFind == myBuilders.end()) {
311     myBuilders[theTag] = new TNaming_Builder(builderLabel(data(), theTag));
312     aFind = myBuilders.find(theTag);
313   }
314   return aFind->second;
315 }
316
317 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
318                                       const GeomShapePtr& theNewShape,
319                                       const bool theIsCleanStored)
320 {
321   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
322   if (aData) {
323     // clean builders
324     if (theIsCleanStored) clean();
325     TNaming_Builder* aBuilder = builder(0);
326     if (!theOldShape || !theNewShape)
327       return;  // bad shape
328     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
329     if (aShapeOld.IsNull())
330       return;  // null shape inside
331     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
332     if (aShapeNew.IsNull())
333       return;  // null shape inside
334
335     // There is no sense to write history if old shape does not exist in the document.
336     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
337       ModelAPI_Session::get()->moduleDocument())->generalLabel();
338     TDF_Label anOriginalLabel;
339     TopTools_ListOfShape anOldList;
340     if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
341       if (aShapeOld.ShapeType() == TopAbs_COMPOUND)  { // check this could be a compund by a whole feature selection
342         for(TopoDS_Iterator aCompIter(aShapeOld); aCompIter.More(); aCompIter.Next()) {
343           if (isShapeInTree(aData->shapeLab(), anAccess2, aCompIter.Value(), anOriginalLabel)) {
344             anOldList.Append(aCompIter.Value());
345           } else {
346             anOldList.Clear();
347             break;
348           }
349         }
350       }
351     } else {
352       anOldList.Append(aShapeOld);
353     }
354     if (anOldList.IsEmpty()) {
355       if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
356         aBuilder->Generated(aShapeNew);
357       }
358     } else {
359       if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
360         myBuilders.erase(0);
361         aBuilder = builder(0);
362       }
363       TopTools_ListIteratorOfListOfShape anOldIter(anOldList);
364       for(; anOldIter.More(); anOldIter.Next()) {
365         aBuilder->Modify(anOldIter.Value(), aShapeNew);
366       }
367       // store information about the external document reference to restore old shape on open
368       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
369     }
370
371     if(!aBuilder->NamedShape()->IsEmpty()) {
372       Handle(TDataStd_Name) anAttr;
373       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
374         std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
375         if(!aName.empty()) {
376           std::shared_ptr<Model_Document> aDoc =
377             std::dynamic_pointer_cast<Model_Document>(document());
378           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
379         }
380       }
381     }
382   }
383 }
384
385 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
386   const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
387 {
388   bool aStored = false;
389   std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
390   for(; anOldIter != theOldShapes.cend(); anOldIter++) {
391     // compounds may cause crash if call "modified"
392     bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
393                 (*anOldIter)->isCompSolid();
394     if (!aStore) {
395       ListOfShape aNews; // check this old really modifies theNewShape
396       theMakeShape->modified(*anOldIter, aNews);
397       ListOfShape::iterator aNewIter = aNews.begin();
398       for(; aNewIter != aNews.end(); aNewIter++) {
399         if (theNewShape->isSame(*aNewIter))
400           break;
401       }
402       aStore = aNewIter != aNews.end();
403     }
404     if (aStore) {
405       storeModified(*anOldIter, theNewShape, !aStored);
406       TNaming_Builder* aBuilder = builder(0);
407       aStored = !aBuilder->NamedShape()->IsEmpty();
408     }
409   }
410   if (!aStored) {
411     // check the new shape is already in the tree, so, no need to store primitive, just reference
412     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
413     if (aData.get()) {
414       TDF_Label aShapeLab = aData->shapeLab();
415       TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
416       Handle(TNaming_NamedShape) aNS;
417       if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
418         aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
419       // the last condition is for the issue 2751 : existing shape may be found in compound-NS
420       if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
421         // This shape is already in document, store reference instead of shape;
422         const TDF_Label aFoundLabel = aNS->Label();
423         TDF_Reference::Set(aShapeLab, aFoundLabel);
424         myBuilders.erase(0);
425         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
426         return;
427       }
428     }
429     store(theNewShape); // store as PRIMITIVE, but clean in any way
430     return;
431   }
432 }
433
434 void Model_BodyBuilder::clean()
435 {
436   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
437   if (aLab.IsNull())
438     return;
439   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
440   for(; aBuilder != myBuilders.end(); aBuilder++) {
441     Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
442     delete aBuilder->second;
443     if (!aNS.IsNull() && !aNS->Label().IsNull())
444       aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
445   }
446   myBuilders.clear();
447   myPrimitivesNamesIndexMap.clear();
448   // remove the old reference (if any)
449   aLab.ForgetAttribute(TDF_Reference::GetID());
450   myFreePrimitiveTag = PRIMITIVES_START_TAG;
451   TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
452   for(; anEntriesIter.More(); anEntriesIter.Next()) {
453     anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
454   }
455 }
456
457 void Model_BodyBuilder::cleanCash()
458 {
459   myPrimitivesNamesIndexMap.clear();
460 }
461
462 Model_BodyBuilder::~Model_BodyBuilder()
463 {
464   clean();
465 }
466
467 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
468 {
469   std::string aName = theName;
470   std::string aPrefix = "";
471   switch (theTag) {
472     case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
473     case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
474     case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
475     case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
476     case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
477     case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
478   }
479   aName.insert(0, aPrefix);
480
481   TDataStd_Name::Set(builderLabel(data(), theTag), aName.c_str());
482 }
483 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
484                                   const std::string& theName,
485                                   const bool theCheckIsInResult)
486 {
487   GeomShapePtr aResultShape = shape();
488   if (theCheckIsInResult) {
489     bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
490     if (aNewShapeIsNotInResultShape) {
491       return false;
492     }
493   }
494
495   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
496   builder(myFreePrimitiveTag)->Generated(aShape);
497   if (!theName.empty()) {
498     std::string aName = theName;
499     if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
500       IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
501       aName += "_" + std::to_string(++(anIndexTags.index));
502       anIndexTags.tags.push_back(myFreePrimitiveTag);
503       if (anIndexTags.index == 2) {
504         buildName(anIndexTags.tags.front(), theName + "_1");
505       }
506     }
507     else {
508       IndexTags anIndexTags;
509       anIndexTags.index = 1;
510       anIndexTags.tags.push_back(myFreePrimitiveTag);
511       myPrimitivesNamesIndexMap[theName] = anIndexTags;
512     }
513
514     buildName(myFreePrimitiveTag, aName);
515   }
516   ++myFreePrimitiveTag;
517   return true;
518 }
519
520 void Model_BodyBuilder::generated(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   TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
527   int aTag;
528   if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
529     // TODO: This is a workaround. New shape should be only vertex, edge or face.
530     TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
531     aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
532     for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
533       builder(aTag)->Generated(anOldShape, anExp.Current());
534     }
535     buildName(aTag, theName);
536   } else {
537     aTag = getGenerationTag(aNewShape);
538     if (aTag == INVALID_TAG) return;
539     builder(aTag)->Generated(anOldShape, aNewShape);
540     buildName(aTag, theName);
541   }
542 }
543
544 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
545                                  const GeomShapePtr& theNewShape,
546                                  const std::string& theName)
547 {
548   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
549   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
550   int aTag = getModificationTag(aNewShape);
551   if (aTag == INVALID_TAG) return;
552   builder(aTag)->Modify(anOldShape, aNewShape);
553   buildName(aTag, theName);
554 }
555
556 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
557                                           const GeomShapePtr& theOldShape,
558                                           const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
559                                           const GeomShapePtr& theShapesToExclude)
560 {
561   TopTools_MapOfShape anAlreadyProcessedShapes;
562   GeomShapePtr aResultShape = shape();
563   for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
564        anExp.more();
565        anExp.next())
566   {
567     GeomShapePtr anOldSubShape = anExp.current();
568     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
569     if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
570         || !theAlgo->isDeleted(anOldSubShape)
571         || aResultShape->isSubShape(anOldSubShape, false)
572         || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
573     {
574       continue;
575     }
576
577     ListOfShape aNewShapes;
578     if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
579       theAlgo->modified(anOldSubShape, aNewShapes);
580     }
581
582     if (aNewShapes.size() == 0
583         || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
584       builder(DELETED_TAG)->Delete(anOldSubShape_);
585     }
586   }
587 }
588
589 // Keep only the shapes with minimal shape type
590 static void keepTopLevelShapes(ListOfShape& theShapes,
591                                const TopoDS_Shape& theRoot,
592                                const GeomShapePtr& theResultShape = GeomShapePtr())
593 {
594   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
595   ListOfShape::iterator anIt = theShapes.begin();
596   while (anIt != theShapes.end()) {
597     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
598     bool aSkip = aNewShape.IsNull() ||
599       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
600     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
601         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
602       ListOfShape::iterator aRemoveIt = anIt++;
603       theShapes.erase(aRemoveIt);
604     } else {
605       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
606       if (aType < aKeepShapeType) {
607         // found a shape with lesser shape type => remove all previous shapes
608         aKeepShapeType = aType;
609         theShapes.erase(theShapes.begin(), anIt);
610         ++anIt;
611       } else if (aType > aKeepShapeType) {
612         // shapes with greater shape type should be removed from the list
613         ListOfShape::iterator aRemoveIt = anIt++;
614         theShapes.erase(aRemoveIt);
615       } else
616         ++anIt;
617     }
618   }
619 }
620
621 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
622                                            const GeomShapePtr& theOldShape,
623                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
624                                            const std::string& theName)
625 {
626   GeomShapePtr aResultShape = shape();
627   GeomShapePtr aShapeToExplore = theOldShape;
628   if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
629     // use optimized set of old shapes for this
630     GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
631                                                       aResultShape,
632                                                       theShapeTypeToExplore);
633     if (aCompound.get()) aShapeToExplore = aCompound;
634   }
635
636   TopTools_MapOfShape anAlreadyProcessedShapes;
637   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
638   for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
639        anOldShapeExp.more();
640        anOldShapeExp.next())
641   {
642     GeomShapePtr anOldSubShape = anOldShapeExp.current();
643     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
644
645     // There is no sense to write history if shape already processed
646     // or old shape does not exist in the document.
647     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
648     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
649       ModelAPI_Session::get()->moduleDocument())->generalLabel();
650     TDF_Label anOriginalLabel;
651     bool anOldSubShapeNotInTree =
652       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
653     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
654       continue;
655     }
656
657     // Get new shapes.
658     ListOfShape aNewShapes;
659     theAlgo->modified(anOldSubShape, aNewShapes);
660
661     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
662          aNewShapesIt != aNewShapes.cend();
663          ++aNewShapesIt)
664     {
665       GeomShapePtr aNewShape = *aNewShapesIt;
666       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
667       bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
668
669       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
670       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
671       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
672         continue;
673
674       if (aResultShape->isSame(aNewShape))
675         continue; // it is stored on the root level (2241 - history propagation issue)
676
677       int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
678       TNaming_Builder*aBuilder = builder(aTag);
679       if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
680         continue; // new shape was already stored.
681
682       buildName(aTag, theName);
683       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
684                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
685       // store information about the external document reference to restore old shape on open
686       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
687     }
688   }
689 }
690
691 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
692                                             const GeomShapePtr& theOldShape,
693                                             const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
694                                             const std::string& theName,
695                                             const bool theSaveOldIfNotInTree)
696 {
697   GeomShapePtr aResultShape = shape();
698   TopTools_MapOfShape anAlreadyProcessedShapes;
699   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
700   for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
701        anOldShapeExp.more();
702        anOldShapeExp.next())
703   {
704     GeomShapePtr anOldSubShape = anOldShapeExp.current();
705     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
706
707     // There is no sense to write history if shape already processed
708     // or old shape does not exist in the document.
709     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
710     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
711       ModelAPI_Session::get()->moduleDocument())->generalLabel();
712     TDF_Label anOriginalLabel;
713     bool anOldSubShapeNotInTree =
714       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
715     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
716       if (theSaveOldIfNotInTree) {
717         std::string aSelectionName = theName + "Selected";
718         generated(anOldSubShape, aSelectionName, false);
719       } else
720         continue;
721     }
722
723     // Get new shapes.
724     ListOfShape aNewShapes;
725     theAlgo->generated(anOldSubShape, aNewShapes);
726
727     keepTopLevelShapes(aNewShapes, anOldSubShape_);
728
729     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
730          aNewShapesIt != aNewShapes.cend();
731          ++aNewShapesIt)
732     {
733       GeomShapePtr aNewShape = *aNewShapesIt;
734       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
735
736       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
737       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
738       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
739         continue;
740       }
741
742       if (aResultShape->isSame(aNewShape))
743         continue; // it is stored on the root level
744
745       TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
746       if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
747         // TODO: This is a workaround. New shape should be only edge or face.
748         TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
749                                                                             : TopAbs_FACE;
750         int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
751         for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
752           builder(aTag)->Generated(anOldSubShape_, anExp.Current());
753           // store information about the external document reference to restore old shape on open
754           storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
755         }
756         buildName(aTag, theName);
757       } else {
758         int aTag = getGenerationTag(aNewShape_);
759         if (aTag == INVALID_TAG) return;
760         builder(aTag)->Generated(anOldSubShape_, aNewShape_);
761         buildName(aTag, theName);
762         // store information about the external document reference to restore old shape on open
763         storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
764       }
765     }
766   }
767 }
768
769 // LCOV_EXCL_START
770 //=======================================================================
771 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
772   const TopAbs_ShapeEnum        theGeneratedFrom,
773   TopTools_DataMapOfShapeShape& theDangles)
774 {
775   theDangles.Clear();
776   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
777   TopAbs_ShapeEnum GeneratedTo;
778   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
779   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
780   else return Standard_False;
781   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
782   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
783     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
784     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
785     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
786   }
787   return theDangles.Extent();
788 }
789
790 //=======================================================================
791 void loadGeneratedDangleShapes(
792   const TopoDS_Shape&      theShapeIn,
793   const TopAbs_ShapeEnum   theGeneratedFrom,
794   TNaming_Builder *        theBuilder)
795 {
796   TopTools_DataMapOfShapeShape dangles;
797   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
798   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
799   for (; itr.More(); itr.Next())
800     theBuilder->Generated(itr.Key(), itr.Value());
801 }
802 // LCOV_EXCL_STOP
803
804 //=======================================================================
805 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
806                                        const std::string& theName)
807 {
808   if(theShape->isNull()) return;
809   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
810   std::string aName;
811   if (aShape.ShapeType() == TopAbs_SOLID) {
812     TopExp_Explorer expl(aShape, TopAbs_FACE);
813     for (; expl.More(); expl.Next()) {
814       builder(myFreePrimitiveTag)->Generated(expl.Current());
815       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
816       aName = theName + "_" + aStr.ToCString();
817       buildName(myFreePrimitiveTag, aName);
818       ++myFreePrimitiveTag;
819     }
820   }
821   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
822     // load faces and all the free edges
823     TopTools_IndexedMapOfShape Faces;
824     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
825     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
826       TopExp_Explorer expl(aShape, TopAbs_FACE);
827       for (; expl.More(); expl.Next()) {
828         builder(myFreePrimitiveTag)->Generated(expl.Current());
829         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
830         aName = theName + "_" + aStr.ToCString();
831         buildName(myFreePrimitiveTag, aName);
832         ++myFreePrimitiveTag;
833       }
834     }
835     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
836     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
837     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
838     {
839       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
840       if (aLL.Extent() < 2) {
841         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
842           continue;
843         builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
844         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
845         aName = theName + "_" + aStr.ToCString();
846         buildName(myFreePrimitiveTag, aName);
847         ++myFreePrimitiveTag;
848       } else {
849         TopTools_ListIteratorOfListOfShape anIter(aLL);
850         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
851         anIter.Next();
852         if(aFace.IsEqual(anIter.Value())) {
853           builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
854           TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
855           aName = theName + "_" + aStr.ToCString();
856           buildName(myFreePrimitiveTag, aName);
857           ++myFreePrimitiveTag;
858         }
859       }
860     }
861   } else if (aShape.ShapeType() == TopAbs_WIRE) {
862     TopTools_IndexedMapOfShape Edges;
863     BRepTools::Map3DEdges(aShape, Edges);
864     if (Edges.Extent() == 1) {
865       builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
866       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
867       for (; expl.More(); expl.Next()) {
868         builder(myFreePrimitiveTag)->Generated(expl.Current());
869         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
870         aName = theName + "_" + aStr.ToCString();
871         buildName(myFreePrimitiveTag, aName);
872         ++myFreePrimitiveTag;
873       }
874     } else {
875       TopExp_Explorer expl(aShape, TopAbs_EDGE);
876       for (; expl.More(); expl.Next()) {
877         builder(myFreePrimitiveTag)->Generated(expl.Current());
878         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
879         aName = theName + "_" + aStr.ToCString();
880         buildName(myFreePrimitiveTag, aName);
881         ++myFreePrimitiveTag;
882       }
883       // and load generated vertices.
884       TopTools_DataMapOfShapeShape generated;
885       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
886       {
887         TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
888         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
889       }
890     }
891   } else if (aShape.ShapeType() == TopAbs_EDGE) {
892     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
893     for (; expl.More(); expl.Next()) {
894       builder(myFreePrimitiveTag)->Generated(expl.Current());
895       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
896       aName = theName + "_" + aStr.ToCString();
897       buildName(myFreePrimitiveTag, aName);
898       ++myFreePrimitiveTag;
899     }
900   }
901 }
902
903 //=======================================================================
904 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
905   TopTools_ListOfShape&   theList)
906 {
907   theList.Clear();
908   // edges -> ancestor faces list
909   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
910   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
911   // keeps the shapes which are already in the resulting list
912   TopTools_MapOfShape alreadyThere;
913   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
914   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
915
916   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
917   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
918     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
919     if (ancestors.Extent() < 2)
920       continue;
921     Standard_Integer anID = 0;
922     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
923       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
924     }
925     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
926       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
927         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
928       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
929       for(; aSameEdge.More(); aSameEdge.Next()) {
930         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
931           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
932         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
933           break;
934
935         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
936         for(; aFaceIter1.More(); aFaceIter1.Next()) {
937           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
938           for(; aFaceIter2.More(); aFaceIter2.Next()) {
939             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
940               break;
941           }
942           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
943             break;
944         }
945         if (!aFaceIter1.More()) { // all the faces are same => put to the result
946           if (alreadyThere.Add(aSameEdge.Value()))
947             theList.Append(aSameEdge.Value());
948           if (alreadyThere.Add(anAncestorsIter.Key()))
949             theList.Append(anAncestorsIter.Key());
950         }
951       }
952     } else { // ID is unique, just add this edge
953       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
954     }
955     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
956   }
957   return theList.Extent();
958 }
959
960 //=======================================================================
961 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
962 {
963   GeomShapePtr aShapePtr = shape();
964   if (theShape->isNull() || !aShapePtr.get())
965     return;
966   TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
967   if (aShape.IsNull())
968     return;
969   std::string aName;
970   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
971     TopoDS_Iterator itr(aShape);
972     for (; itr.More(); itr.Next()) {
973       builder(myFreePrimitiveTag)->Generated(itr.Value());
974       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
975       aName = theName + "_" + aStr.ToCString();
976       buildName(myFreePrimitiveTag, aName);
977       ++myFreePrimitiveTag;
978       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
979         itr.Value().ShapeType() == TopAbs_COMPSOLID)
980       {
981         GeomShapePtr itrShape(new GeomAPI_Shape());
982         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
983         loadFirstLevel(itrShape, theName);
984       } else {
985         GeomShapePtr itrShape(new GeomAPI_Shape());
986         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
987         loadNextLevels(itrShape, theName);
988       }
989     }
990   } else {
991     GeomShapePtr itrShape(new GeomAPI_Shape());
992     itrShape->setImpl(new TopoDS_Shape(aShape));
993     loadNextLevels(itrShape, theName);
994   }
995   TopTools_ListOfShape   aList;
996   if(findAmbiguities(aShape, aList)) {
997     TopTools_ListIteratorOfListOfShape it(aList);
998     for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
999       builder(myFreePrimitiveTag)->Generated(it.Value());
1000       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
1001       aName = theName + "_" + aStr.ToCString();
1002       buildName(myFreePrimitiveTag, aName);
1003     }
1004   }
1005 }
1006
1007 GeomShapePtr Model_BodyBuilder::shape()
1008 {
1009   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1010   if (aData && aData->isValid()) {
1011     TDF_Label aShapeLab = aData->shapeLab();
1012     Handle(TDF_Reference) aRef;
1013     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1014       aShapeLab = aRef->Get();
1015     }
1016     Handle(TNaming_NamedShape) aName;
1017     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1018       TopoDS_Shape aShape = aName->Get();
1019       if (!aShape.IsNull()) {
1020         GeomShapePtr aRes(new GeomAPI_Shape);
1021         aRes->setImpl(new TopoDS_Shape(aShape));
1022         return aRes;
1023       }
1024     }
1025   }
1026   return GeomShapePtr();
1027 }