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