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