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