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