Salome HOME
Fix for the problem of update of the selection attribute value after it becomes inval...
[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 <TNaming_Builder.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Iterator.hxx>
28 #include <TNaming_Tool.hxx>
29 #include <TDataStd_Name.hxx>
30 #include <TDataStd_Integer.hxx>
31 #include <TopoDS.hxx>
32 #include <TopoDS_Face.hxx>
33 #include <TDF_ChildIterator.hxx>
34 #include <TDF_ChildIDIterator.hxx>
35 #include <TDF_Reference.hxx>
36 #include <TopTools_MapOfShape.hxx>
37 #include <TopExp_Explorer.hxx>
38 #include <TopTools_ListOfShape.hxx>
39 #include <TopTools_ListIteratorOfListOfShape.hxx>
40 #include <TopTools_DataMapOfShapeListOfShape.hxx>
41 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
42 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
43 #include <TopTools_MapIteratorOfMapOfShape.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_IndexedMapOfShape.hxx>
46 #include <TopTools_DataMapOfShapeShape.hxx>
47 #include <TopExp.hxx>
48 #include <BRepTools.hxx>
49 #include <BRep_Tool.hxx>
50 #include <BRepTools_History.hxx>
51 #include <GeomAPI_Shape.h>
52 #include <GeomAlgoAPI_MakeShape.h>
53 #include <GeomAlgoAPI_SortListOfShapes.h>
54 #include <Config_PropManager.h>
55 // DEB
56 //#include <TCollection_AsciiString.hxx>
57 //#include <TDF_Tool.hxx>
58 //#define DEB_IMPORT 1
59
60 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
61 : ModelAPI_BodyBuilder(theOwner),
62   myDividedIndex(1),
63   myVIndex(1),
64   myEIndex(1),
65   myFIndex(1)
66 {
67 }
68
69 // Converts evolution of naming shape to selection evelution and back to avoid
70 // naming support on the disabled results. Deeply in the labels tree, recursively.
71 static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
72   std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
73   Handle(TNaming_NamedShape) aName;
74   int anEvolution = -1;
75   if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
76     TNaming_Evolution aNSEvol = aName->Evolution();
77     if ((aNSEvol == TNaming_SELECTED && theFlag) ||
78         (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
79       return;
80     }
81     anEvolution = (int)(aNSEvol);
82     if (!theFlag) {
83       Handle(TDataStd_Integer) anAttrEvol;
84       if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
85         anEvolution = anAttrEvol->Get();
86       }
87     } else {
88       TDataStd_Integer::Set(theLab, anEvolution);
89     }
90
91     for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
92       // iterator goes in reversed order relatively to the Builder, to, make the list reversed
93       aShapePairs.push_front(std::pair<TopoDS_Shape, TopoDS_Shape>
94         (anIter.OldShape(), anIter.NewShape()));
95     }
96
97     // create new
98     TNaming_Builder aBuilder(theLab);
99     TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
100     std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
101     for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
102       if (theFlag) { // disabled => make selection
103         if (anEvolution == TNaming_DELETE) // issue 2274 : don't put too many same null shapes
104           aBuilder.Select(aPairsIter->first, aPairsIter->first);
105         else if (anEvolution == TNaming_PRIMITIVE)
106           aBuilder.Select(aPairsIter->second, aPairsIter->second);
107         else
108           aBuilder.Select(aPairsIter->second, aPairsIter->first);
109       } else if (anEvol == TNaming_GENERATED) {
110         aBuilder.Generated(aPairsIter->first, aPairsIter->second);
111       } else if (anEvol == TNaming_MODIFY) {
112         aBuilder.Modify(aPairsIter->first, aPairsIter->second);
113       } else if (anEvol == TNaming_DELETE) {
114         aBuilder.Delete(aPairsIter->first);
115       } else if (anEvol == TNaming_PRIMITIVE) {
116         aBuilder.Generated(aPairsIter->second);
117       } else if (anEvol == TNaming_SELECTED) {
118         aBuilder.Select(aPairsIter->second, aPairsIter->first);
119       }
120     }
121   }
122   // recursive call for all sub-labels
123   TDF_ChildIterator anIter(theLab, Standard_False);
124   for(; anIter.More(); anIter.Next()) {
125     evolutionToSelectionRec(anIter.Value(), theFlag);
126   }
127 }
128
129 void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
130 {
131   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
132   if (!aData || !aData->isValid()) // unknown case
133     return;
134   TDF_Label& aShapeLab = aData->shapeLab();
135   evolutionToSelectionRec(aShapeLab, theFlag);
136 }
137
138 void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& 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 std::shared_ptr<GeomAPI_Shape>& theFromShape,
183   const std::shared_ptr<GeomAPI_Shape>& 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 std::shared_ptr<GeomAPI_Shape>& theOldShape,
229   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
230 {
231   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
232   if (aData) {
233     TDF_Label& aShapeLab = aData->shapeLab();
234     // clean builders
235     if (theDecomposeSolidsTag != -2)
236       clean();
237     // store the new shape as primitive
238     TNaming_Builder* aBuilder = builder(0);
239     if (!theOldShape || !theNewShape)
240       return;  // bad shape
241     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
242     if (aShapeOld.IsNull())
243       return;  // null shape inside
244     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
245     if (aShapeNew.IsNull())
246       return;  // null shape inside
247     aBuilder->Modify(aShapeOld, aShapeNew);
248     if(!aBuilder->NamedShape()->IsEmpty()) {
249       Handle(TDataStd_Name) anAttr;
250       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
251         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
252         if(!aName.empty()) {
253           std::shared_ptr<Model_Document> aDoc =
254             std::dynamic_pointer_cast<Model_Document>(document());
255           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
256         }
257       }
258     }
259   }
260 }
261
262 void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>& theShape)
263 {
264   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
265   if (aData) {
266     clean();
267     if (!theShape.get())
268       return; // bad shape
269     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
270     if (aShape.IsNull())
271       return;  // null shape inside
272     TNaming_Builder aBuilder(aData->shapeLab());
273     aBuilder.Select(aShape, aShape);
274   }
275 }
276
277 void Model_BodyBuilder::clean()
278 {
279   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
280   if (aLab.IsNull())
281     return;
282   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
283   for(; aBuilder != myBuilders.end(); aBuilder++) {
284     delete aBuilder->second;
285     // clear also shapes on cleaned sub-labels (#2241)
286     Handle(TNaming_NamedShape) aNS;
287     if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
288       aNS->Clear();
289     }
290   }
291   myBuilders.clear();
292   // remove the old reference (if any)
293   aLab.ForgetAttribute(TDF_Reference::GetID());
294   myDividedIndex = 1;
295   myVIndex = 1;
296   myEIndex = 1;
297   myFIndex = 1;
298 }
299
300 Model_BodyBuilder::~Model_BodyBuilder()
301 {
302   clean();
303 }
304
305 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
306 {
307   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
308   //aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), theName);
309   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), theName.c_str());
310 }
311 void Model_BodyBuilder::generated(
312   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
313 {
314   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
315   builder(theTag)->Generated(aShape);
316   if(!theName.empty())
317     buildName(theTag, theName);
318 }
319
320 void Model_BodyBuilder::generated(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
321   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
322 {
323   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
324   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
325   builder(theTag)->Generated(anOldShape, aNewShape);
326   if(!theName.empty())
327     buildName(theTag, theName);
328   TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
329   if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
330     TopAbs_ShapeEnum anExplodeShapeType = aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
331     const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
332     int aTag = 1;
333     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
334     for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
335       TDF_Label aChildLabel = aLabel.FindChild(aTag);
336       TNaming_Builder aBuilder(aChildLabel);
337       aBuilder.Generated(anOldShape, anExp.Current());
338       TCollection_AsciiString aChildName = TCollection_AsciiString((theName + "_").c_str()) + aTag;
339       //aDoc->addNamingName(aChildLabel, aChildName.ToCString());
340       TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
341       aTag++;
342     }
343   }
344 }
345
346
347 void Model_BodyBuilder::modified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
348   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
349 {
350   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
351   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
352   builder(theTag)->Modify(anOldShape, aNewShape);
353   if(!theName.empty())
354     buildName(theTag, theName);
355 }
356
357 void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
358   const int theTag)
359 {
360   TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
361   builder(theTag)->Delete(aShape);
362 }
363
364 void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
365   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
366   const int  theKindOfShape,
367   const int  theTag)
368 {
369   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
370   TopTools_MapOfShape aView;
371   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
372   GeomShapePtr aResultShape = shape();
373   for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
374     const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
375     if (!aView.Add(aRoot)) continue;
376     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
377     aRShape->setImpl((new TopoDS_Shape(aRoot)));
378     if (theMS->isDeleted (aRShape)) {
379       if (!aResultShape->isSubShape(aRShape, false)) {
380           ListOfShape aHist;
381           if (BRepTools_History::IsSupportedType(aRoot)) // to avoid crash in #2572
382             theMS->modified(aRShape, aHist);
383           if (aHist.size() == 0 || (aHist.size() == 1 && aHist.front()->isSame(aRShape)))
384             builder(theTag)->Delete(aRoot);
385       }
386     }
387   }
388 }
389
390 static void removeBadShapes(ListOfShape& theShapes)
391 {
392   ListOfShape::iterator anIt = theShapes.begin();
393   while (anIt != theShapes.end()) {
394     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
395     bool aSkip = aNewShape.IsNull()
396       || (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
397     if (aSkip) {
398       ListOfShape::iterator aRemoveIt = anIt++;
399       theShapes.erase(aRemoveIt);
400     } else {
401       ++anIt;
402     }
403   }
404 }
405
406 // Keep only the shapes with minimal shape type
407 static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRoot,
408   const GeomShapePtr& theResultShape = GeomShapePtr())
409 {
410   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
411   ListOfShape::iterator anIt = theShapes.begin();
412   while (anIt != theShapes.end()) {
413     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
414     bool aSkip = aNewShape.IsNull() ||
415       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
416     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
417         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
418       ListOfShape::iterator aRemoveIt = anIt++;
419       theShapes.erase(aRemoveIt);
420     } else {
421       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
422       if (aType < aKeepShapeType) {
423         // found a shape with lesser shape type => remove all previous shapes
424         aKeepShapeType = aType;
425         theShapes.erase(theShapes.begin(), anIt);
426         ++anIt;
427       } else if (aType > aKeepShapeType) {
428         // shapes with greater shape type should be removed from the list
429         ListOfShape::iterator aRemoveIt = anIt++;
430         theShapes.erase(aRemoveIt);
431       } else
432         ++anIt;
433     }
434   }
435 }
436
437 // returns an ancestor shape-type thaty used for naming-definition of the sub-type
438 TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
439   if (theSubType == TopAbs_VERTEX)
440     return TopAbs_EDGE;
441   if (theSubType == TopAbs_EDGE)
442     return TopAbs_FACE;
443   return TopAbs_VERTEX; // bad case
444 }
445
446 void Model_BodyBuilder::loadAndOrientModifiedShapes (
447   GeomAlgoAPI_MakeShape* theMS,
448   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
449   const int  theKindOfShape,
450   const int  theTag,
451   const std::string& theName,
452   GeomAPI_DataMapOfShapeShape& theSubShapes,
453   const bool theIsStoreSeparate,
454   const bool theIsStoreAsGenerated)
455 {
456   static const int THE_ANCHOR_TAG = 100000;
457
458   int anIndex = 1;
459   int aTag = theTag;
460   bool isBuilt = !theName.empty();
461   std::string aName = theName;
462   std::ostringstream aStream;
463   GeomShapePtr aResultShape = shape();
464   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
465   TopTools_MapOfShape aView;
466   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
467   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
468   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
469     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
470     if (!aView.Add(aRoot)) continue;
471
472     bool aNotInTree =
473       TNaming_Tool::NamedShape(aRoot, aData->shapeLab()).IsNull();
474     if (aNotInTree && !theIsStoreSeparate) {
475       // there is no sense to write history if old shape does not exist in the document
476       continue; // but if it is stored separately, it will be builded as a primitive
477     }
478     ListOfShape aList;
479     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
480     aRShape->setImpl((new TopoDS_Shape(aRoot)));
481     theMS->modified(aRShape, aList);
482     if (!theIsStoreSeparate) {
483       //keepTopLevelShapes(aList, aRoot, aResultShape);
484       removeBadShapes(aList);
485     }
486     // sort the list of images before naming
487     GeomAlgoAPI_SortListOfShapes::sort(aList);
488
489     // to trace situation where several objects are produced by one parent (#2317)
490     int aSameParentShapes = (aShapeIn.ShapeType() == TopAbs_WIRE
491                              || aShapeIn.ShapeType() == TopAbs_SHELL
492                              || aShapeIn.ShapeType() == TopAbs_COMPOUND) ? 0 : -1;
493     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
494       anIt = aList.begin(), aLast = aList.end();
495     for (; anIt != aLast; anIt++) {
496       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
497       if (theSubShapes.isBound(*anIt)) {
498         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
499         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
500       }
501       isBuilt = !theName.empty();
502       if(!aRoot.IsSame(aNewShape)
503          && aResultShape->isSubShape((*anIt), false)
504          && !aResultShape->isSame(*anIt)) // to avoid put of same shape on main label and sub
505       {
506         if (!theIsStoreSeparate) {
507           aSameParentShapes++;
508         } else if (aNotInTree) // check this new shape can not be represented as
509                               // a sub-shape of higher level sub-shapes
510         {
511           TopAbs_ShapeEnum aNewType = aNewShape.ShapeType();
512           TopAbs_ShapeEnum anAncestorType = typeOfAncestor(aNewType);
513           if (anAncestorType != TopAbs_VERTEX) {
514             bool aFound = false;
515             TopoDS_Shape aResultTShape = aResultShape->impl<TopoDS_Shape>();
516             TopExp_Explorer anAncestorExp(aResultTShape, anAncestorType);
517             for(; anAncestorExp.More() && !aFound; anAncestorExp.Next()) {
518               if (aResultTShape.IsSame(anAncestorExp.Current()))
519                 continue;
520               TopExp_Explorer aSubExp(anAncestorExp.Current(), aNewType);
521               for(; aSubExp.More(); aSubExp.Next()) {
522                 if (aNewShape.IsSame(aSubExp.Current())) {
523                   aFound = true;
524                   break;
525                 }
526               }
527             }
528             if (aFound) {
529               continue; // not need to store this shape in the BRep structure
530             }
531           }
532         }
533
534         int aFoundTag = 0;
535         bool isFoundSameOld = false;
536         bool isFoundDiffOld = false;
537
538         // Check if new shape was already stored.
539         for (std::map<int, TNaming_Builder*>::iterator aBuildersIt = myBuilders.begin();
540              aBuildersIt != myBuilders.end();
541              ++aBuildersIt)
542         {
543           TNaming_Builder* aBuilder = aBuildersIt->second;
544           for (TNaming_Iterator aNamingIt(aBuilder->NamedShape());
545                aNamingIt.More();
546                aNamingIt.Next())
547           {
548             if (aNamingIt.NewShape().IsSame(aNewShape))
549             {
550               aNamingIt.OldShape().IsSame(aRoot) ? isFoundSameOld = true
551                                                  : isFoundDiffOld = true;
552               aFoundTag = aBuildersIt->first;
553             }
554           }
555
556           if (isFoundSameOld || isFoundDiffOld) break;
557         }
558
559         if (isFoundSameOld) {
560           // Builder already contains same old->new shapes, don't store it twice.
561           continue;
562         }
563
564         int aBuilderTag = aSameParentShapes > 0 ? THE_ANCHOR_TAG : aTag;
565
566         int aCurShapeType = (int)((*anIt)->shapeType());
567         bool needSuffix = false; // suffix for the name based on the shape type
568         if (aCurShapeType != theKindOfShape) {
569           // modified shape has different type => set another tag
570           // to avoid shapes of different types on the same label
571           aBuilderTag = THE_ANCHOR_TAG;
572           needSuffix = true;
573         }
574         std::string aSuffix;
575         if (needSuffix) {
576           switch (aCurShapeType) {
577             case GeomAPI_Shape::VERTEX: aSuffix = "_v_" + std::to_string(myVIndex++); break;
578             case GeomAPI_Shape::EDGE:   aSuffix = "_e_" + std::to_string(myEIndex++); break;
579             case GeomAPI_Shape::FACE:   aSuffix = "_f_" + std::to_string(myFIndex++); break;
580             default: break;
581           }
582         }
583
584         std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>> aKeepShapes, aMoveShapes;
585         if (isFoundDiffOld) {
586           // Found same new shape with different old shape.
587           if (aFoundTag >= THE_ANCHOR_TAG) {
588             // Found on separated tag.
589             aBuilderTag = aFoundTag; // Store it on the same tag.
590             isBuilt = false; // Don't change name;
591           } else {
592             // Found on previous tag.
593             if (aBuilderTag < THE_ANCHOR_TAG) {
594               // New shape shouls not be separated.
595               aBuilderTag = aFoundTag; // Store it on the same tag.
596               isBuilt = false; // Don't change name;
597             } else {
598               // New shape should be separated from others. Move shapes from found tag to new tag.
599               while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
600                 ++aBuilderTag;
601               }
602
603               TNaming_Builder* aFoundBuilder = myBuilders.at(aFoundTag);
604               Handle(TNaming_NamedShape) aFoundNamedShape = aFoundBuilder->NamedShape();
605               TDF_Label aFoundLabel = aFoundNamedShape->Label();
606               TNaming_Evolution anEvolution = aFoundNamedShape->Evolution();
607               for (TNaming_Iterator aNamingIt(aFoundNamedShape);
608                    aNamingIt.More();
609                    aNamingIt.Next())
610               {
611                 std::pair<TopoDS_Shape, TopoDS_Shape> aShapesPair =
612                   std::make_pair(aNamingIt.OldShape(), aNamingIt.NewShape());
613                 aNamingIt.NewShape().IsSame(aNewShape) ? aMoveShapes.push_back(aShapesPair)
614                                                        : aKeepShapes.push_back(aShapesPair);
615               }
616
617               aFoundNamedShape->Clear();
618               for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aKeepIt =
619                      aKeepShapes.begin();
620                    aKeepIt != aKeepShapes.end();
621                    ++aKeepIt)
622               {
623                 if (anEvolution == TNaming_GENERATED) {
624                   aFoundBuilder->Generated(aKeepIt->first, aKeepIt->second);
625                 } else {
626                   aFoundBuilder->Modify(aKeepIt->first, aKeepIt->second);
627                 }
628               }
629             }
630           }
631         } else if (aBuilderTag == THE_ANCHOR_TAG) {
632           while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
633             ++aBuilderTag;
634           }
635         }
636
637         if(theIsStoreAsGenerated) {
638           // Here we store shapes as generated, to avoid problem when one parent shape produce
639           // several child shapes. In this case naming could not determine which shape to select.
640           builder(aBuilderTag)->Generated(aRoot, aNewShape);
641           for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
642                aMoveShapes.begin();
643                aMoveIt != aMoveShapes.end();
644                ++aMoveIt)
645           {
646             builder(aBuilderTag)->Generated(aMoveIt->first, aMoveIt->second);
647           }
648         } else if (aNotInTree) {
649           // not in tree -> store as primitive (stored as separated)
650           builder(aBuilderTag)->Generated(aNewShape);
651         } else if (aCurShapeType != theKindOfShape) {
652            // if different shape type is produced, make it as generated
653           builder(aBuilderTag)->Generated(aRoot, aNewShape);
654         } else {
655           builder(aBuilderTag)->Modify(aRoot, aNewShape);
656           for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
657                aMoveShapes.begin();
658                aMoveIt != aMoveShapes.end();
659                ++aMoveIt) {
660             builder(aBuilderTag)->Modify(aMoveIt->first, aMoveIt->second);
661           }
662         }
663         if(isBuilt) {
664           aStream.str(std::string());
665           aStream.clear();
666           aStream << theName;
667           if (theIsStoreSeparate && !isFoundDiffOld)
668              aStream << "_" << anIndex++;
669
670           if (aSameParentShapes > 0) {
671             aStream.str(std::string());
672             aStream.clear();
673             aStream << aName << "_" << "divided" << "_" << myDividedIndex++;
674           }
675
676           aStream << aSuffix;
677           buildName(aBuilderTag, aStream.str());
678         }
679         if(theIsStoreSeparate && !isFoundDiffOld) {
680           aTag++;
681         }
682       } else if (aResultShape->isSame(*anIt)) {
683         // keep the modification evolution on the root level (2241 - history propagation issue)
684         TNaming_Builder* aBuilder = builder(0);
685         TDF_Label aShapeLab = aBuilder->NamedShape()->Label();
686         Handle(TDF_Reference) aRef;
687         // Store only in case if it does not have reference.
688         if (!aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
689           if (theIsStoreAsGenerated) {
690             TNaming_Builder* aBuilder = builder(0);
691             if (!aBuilder->NamedShape().IsNull() &&
692                 aBuilder->NamedShape()->Evolution() != TNaming_GENERATED) {
693               myBuilders.erase(0); // clear old builder to avoid different evolutions crash
694             }
695             builder(0)->Generated(aRoot, aNewShape);
696           } else {
697             TNaming_Builder* aBuilder = builder(0);
698             if (!aBuilder->NamedShape().IsNull() &&
699               aBuilder->NamedShape()->Evolution() != TNaming_MODIFY) {
700               myBuilders.erase(0); // clear old builder to avoid different evolutions crash
701             }
702             builder(0)->Modify(aRoot, aNewShape);
703           }
704         }
705       }
706     }
707   }
708 }
709
710 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
711   GeomAlgoAPI_MakeShape* theMS,
712   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
713   const int  theKindOfShape,
714   const int  theTag,
715   const std::string& theName,
716   GeomAPI_DataMapOfShapeShape& theSubShapes)
717 {
718   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
719   TopTools_MapOfShape aView;
720   bool isBuilt = !theName.empty();
721   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
722   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
723     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
724     if (!aView.Add(aRoot)) continue;
725     //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
726     //  continue; // there is no sense to write history if old shape does not exist in the document
727     ListOfShape aList;
728     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
729     aRShape->setImpl((new TopoDS_Shape(aRoot)));
730     theMS->generated(aRShape, aList);
731     keepTopLevelShapes(aList, aRoot);
732     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
733       anIt = aList.begin(), aLast = aList.end();
734     for (; anIt != aLast; anIt++) {
735       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
736       if (theSubShapes.isBound(*anIt)) {
737         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
738         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
739       }
740       if (!aRoot.IsSame (aNewShape)) {
741         builder(theTag)->Generated(aRoot,aNewShape);
742         if(isBuilt)
743           buildName(theTag, theName);
744       }
745       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
746       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
747         TopAbs_ShapeEnum anExplodeShapeType =
748           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
749         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
750         int aTag = 1;
751         std::shared_ptr<Model_Document> aDoc =
752           std::dynamic_pointer_cast<Model_Document>(document());
753         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
754           TDF_Label aChildLabel = aLabel.FindChild(aTag);
755           TNaming_Builder aBuilder(aChildLabel);
756           aBuilder.Generated(aRoot, anExp.Current());
757           TCollection_AsciiString aChildName =
758             TCollection_AsciiString((theName + "_").c_str()) + aTag;
759           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
760           aTag++;
761         }
762       }
763     }
764   }
765 }
766
767 //=======================================================================
768 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
769   const TopAbs_ShapeEnum        theGeneratedFrom,
770   TopTools_DataMapOfShapeShape& theDangles)
771 {
772   theDangles.Clear();
773   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
774   TopAbs_ShapeEnum GeneratedTo;
775   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
776   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
777   else return Standard_False;
778   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
779   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
780     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
781     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
782     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
783   }
784   return theDangles.Extent();
785 }
786
787 //=======================================================================
788 void loadGeneratedDangleShapes(
789   const TopoDS_Shape&      theShapeIn,
790   const TopAbs_ShapeEnum   theGeneratedFrom,
791   TNaming_Builder *        theBuilder)
792 {
793   TopTools_DataMapOfShapeShape dangles;
794   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
795   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
796   for (; itr.More(); itr.Next())
797     theBuilder->Generated(itr.Key(), itr.Value());
798 }
799
800 //=======================================================================
801 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
802   const std::string& theName, int&  theTag)
803 {
804   if(theShape->isNull()) return;
805   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
806   std::string aName;
807   if (aShape.ShapeType() == TopAbs_SOLID) {
808     TopExp_Explorer expl(aShape, TopAbs_FACE);
809     for (; expl.More(); expl.Next()) {
810       builder(theTag)->Generated(expl.Current());
811       TCollection_AsciiString aStr(theTag);
812       aName = theName + aStr.ToCString();
813       buildName(theTag, aName);
814       theTag++;
815     }
816   }
817   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
818     // load faces and all the free edges
819     TopTools_IndexedMapOfShape Faces;
820     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
821     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
822       TopExp_Explorer expl(aShape, TopAbs_FACE);
823       for (; expl.More(); expl.Next()) {
824         builder(theTag)->Generated(expl.Current());
825         TCollection_AsciiString aStr(theTag);
826         aName = theName + aStr.ToCString();
827         buildName(theTag, aName);
828         theTag++;
829       }
830     }
831     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
832     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
833     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
834     {
835       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
836       if (aLL.Extent() < 2) {
837         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
838           continue;
839         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
840         TCollection_AsciiString aStr(theTag);
841         aName = theName + aStr.ToCString();
842         buildName(theTag, aName);
843         theTag++;
844       } else {
845         TopTools_ListIteratorOfListOfShape anIter(aLL);
846         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
847         anIter.Next();
848         if(aFace.IsEqual(anIter.Value())) {
849           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
850           TCollection_AsciiString aStr(theTag);
851           aName = theName + aStr.ToCString();
852           buildName(theTag, aName);
853           theTag++;
854         }
855       }
856     }
857   } else if (aShape.ShapeType() == TopAbs_WIRE) {
858     TopTools_IndexedMapOfShape Edges;
859     BRepTools::Map3DEdges(aShape, Edges);
860     if (Edges.Extent() == 1) {
861       builder(theTag++)->Generated(Edges.FindKey(1));
862       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
863       for (; expl.More(); expl.Next()) {
864         builder(theTag)->Generated(expl.Current());
865         TCollection_AsciiString aStr(theTag);
866         aName = theName + aStr.ToCString();
867         buildName(theTag, aName);
868         theTag++;
869       }
870     } else {
871       TopExp_Explorer expl(aShape, TopAbs_EDGE);
872       for (; expl.More(); expl.Next()) {
873         builder(theTag)->Generated(expl.Current());
874         TCollection_AsciiString aStr(theTag);
875         aName = theName + aStr.ToCString();
876         buildName(theTag, aName);
877         theTag++;
878       }
879       // and load generated vertices.
880       TopTools_DataMapOfShapeShape generated;
881       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
882       {
883         TNaming_Builder* pBuilder = builder(theTag++);
884         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
885       }
886     }
887   } else if (aShape.ShapeType() == TopAbs_EDGE) {
888     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
889     for (; expl.More(); expl.Next()) {
890       builder(theTag)->Generated(expl.Current());
891       TCollection_AsciiString aStr(theTag);
892       aName = theName + aStr.ToCString();
893       buildName(theTag, aName);
894       theTag++;
895     }
896   }
897 }
898
899 //=======================================================================
900 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
901   TopTools_ListOfShape&   theList)
902 {
903   theList.Clear();
904   // edges -> ancestor faces list
905   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
906   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
907   // keeps the shapes which are already in the resulting list
908   TopTools_MapOfShape alreadyThere;
909   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
910   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
911
912   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
913   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
914     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
915     if (ancestors.Extent() < 2)
916       continue;
917     Standard_Integer anID = 0;
918     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
919       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
920     }
921     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
922       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
923         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
924       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
925       for(; aSameEdge.More(); aSameEdge.Next()) {
926         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
927           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
928         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
929           break;
930
931         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
932         for(; aFaceIter1.More(); aFaceIter1.Next()) {
933           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
934           for(; aFaceIter2.More(); aFaceIter2.Next()) {
935             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
936               break;
937           }
938           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
939             break;
940         }
941         if (!aFaceIter1.More()) { // all the faces are same => put to the result
942           if (alreadyThere.Add(aSameEdge.Value()))
943             theList.Append(aSameEdge.Value());
944           if (alreadyThere.Add(anAncestorsIter.Key()))
945             theList.Append(anAncestorsIter.Key());
946         }
947       }
948     } else { // ID is unique, just add this edge
949       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
950     }
951     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
952   }
953   return theList.Extent();
954 }
955
956 //=======================================================================
957 void Model_BodyBuilder::loadFirstLevel(
958   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
959 {
960   if(theShape->isNull()) return;
961   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
962   std::string aName;
963   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
964     TopoDS_Iterator itr(aShape);
965     for (; itr.More(); itr.Next()) {
966       builder(theTag)->Generated(itr.Value());
967       TCollection_AsciiString aStr(theTag);
968       aName = theName + aStr.ToCString();
969       buildName(theTag, aName);
970       if(!theName.empty()) buildName(theTag, aName);
971       theTag++;
972       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
973         itr.Value().ShapeType() == TopAbs_COMPSOLID)
974       {
975         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
976         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
977         loadFirstLevel(itrShape, theName, theTag);
978       } else {
979         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
980         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
981         loadNextLevels(itrShape, theName, theTag);
982       }
983     }
984   } else {
985     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
986     itrShape->setImpl(new TopoDS_Shape(aShape));
987     loadNextLevels(itrShape, theName, theTag);
988   }
989   TopTools_ListOfShape   aList;
990   if(findAmbiguities(aShape, aList)) {
991     TopTools_ListIteratorOfListOfShape it(aList);
992     for (; it.More(); it.Next(),theTag++) {
993       builder(theTag)->Generated(it.Value());
994       TCollection_AsciiString aStr(theTag);
995       aName = theName + aStr.ToCString();
996       buildName(theTag, aName);
997     }
998   }
999 }
1000
1001 //=======================================================================
1002 void Model_BodyBuilder::loadDisconnectedEdges(
1003   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
1004 {
1005   if(theShape->isNull()) return;
1006   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1007   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
1008   TopTools_ListOfShape empty;
1009   TopExp_Explorer explF(aShape, TopAbs_FACE);
1010   for (; explF.More(); explF.Next()) {
1011     const TopoDS_Shape& aFace = explF.Current();
1012     TopExp_Explorer explV(aFace, TopAbs_EDGE);
1013     for (; explV.More(); explV.Next()) {
1014       const TopoDS_Shape& anEdge = explV.Current();
1015       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
1016       Standard_Boolean faceIsNew = Standard_True;
1017       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
1018       for (; itrF.More(); itrF.Next()) {
1019         if (itrF.Value().IsSame(aFace)) {
1020           faceIsNew = Standard_False;
1021           break;
1022         }
1023       }
1024       if (faceIsNew)
1025         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
1026     }
1027   }
1028
1029   TopTools_MapOfShape anEdgesToDelete;
1030   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
1031   std::string aName;
1032   for(;anEx.More();anEx.Next()) {
1033     Standard_Boolean aC0 = Standard_False;
1034     TopoDS_Shape anEdge1 = anEx.Current();
1035     if (edgeNaborFaces.IsBound(anEdge1)) {
1036       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
1037       if (aList1.Extent()<2) continue;
1038       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
1039       for (; itr.More(); itr.Next()) {
1040         TopoDS_Shape anEdge2 = itr.Key();
1041         if(anEdgesToDelete.Contains(anEdge2)) continue;
1042         if (anEdge1.IsSame(anEdge2)) continue;
1043         const TopTools_ListOfShape& aList2 = itr.Value();
1044         // compare lists of the neighbour faces of edge1 and edge2
1045         if (aList1.Extent() == aList2.Extent()) {
1046           Standard_Integer aMatches = 0;
1047           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
1048             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
1049               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
1050           if (aMatches == aList1.Extent()) {
1051             aC0=Standard_True;
1052             builder(theTag)->Generated(anEdge2);
1053             anEdgesToDelete.Add(anEdge2);
1054             TCollection_AsciiString aStr(theTag);
1055             aName = theName + aStr.ToCString();
1056             buildName(theTag, aName);
1057             theTag++;
1058           }
1059         }
1060       }
1061       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
1062       for(;itDelete.More();itDelete.Next())
1063         edgeNaborFaces.UnBind(itDelete.Key());
1064       edgeNaborFaces.UnBind(anEdge1);
1065     }
1066     if (aC0) {
1067       builder(theTag)->Generated(anEdge1);
1068       TCollection_AsciiString aStr(theTag);
1069       aName = theName + aStr.ToCString();
1070       buildName(theTag, aName);
1071       theTag++;
1072     }
1073   }
1074 }
1075
1076 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
1077                                                  const std::string& theName, int&  theTag)
1078 {
1079   if(theShape->isNull()) return;
1080   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1081   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
1082   TopTools_ListOfShape empty;
1083   TopExp_Explorer explF(aShape, TopAbs_EDGE);
1084   for (; explF.More(); explF.Next()) {
1085     const TopoDS_Shape& anEdge = explF.Current();
1086     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
1087     for (; explV.More(); explV.Next()) {
1088       const TopoDS_Shape& aVertex = explV.Current();
1089       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
1090       Standard_Boolean faceIsNew = Standard_True;
1091       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
1092       for (; itrF.More(); itrF.Next()) {
1093         if (itrF.Value().IsSame(anEdge)) {
1094           faceIsNew = Standard_False;
1095           break;
1096         }
1097       }
1098       if (faceIsNew) {
1099         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
1100       }
1101     }
1102   }
1103   std::string aName;
1104   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
1105   for (; itr.More(); itr.Next()) {
1106     const TopTools_ListOfShape& naborEdges = itr.Value();
1107     if (naborEdges.Extent() < 2) {
1108       builder(theTag)->Generated(itr.Key());
1109       TCollection_AsciiString aStr(theTag);
1110       aName = theName + aStr.ToCString();
1111       buildName(theTag, aName);
1112       theTag++;
1113     }
1114   }
1115 }
1116
1117 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
1118 {
1119   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1120   if (aData && aData->isValid()) {
1121     TDF_Label aShapeLab = aData->shapeLab();
1122     Handle(TDF_Reference) aRef;
1123     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1124       aShapeLab = aRef->Get();
1125     }
1126     Handle(TNaming_NamedShape) aName;
1127     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1128       TopoDS_Shape aShape = aName->Get();
1129       if (!aShape.IsNull()) {
1130         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
1131         aRes->setImpl(new TopoDS_Shape(aShape));
1132         return aRes;
1133       }
1134     }
1135   }
1136   return std::shared_ptr<GeomAPI_Shape>();
1137 }
1138
1139 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
1140 {
1141   if (theShape.get()) {
1142     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1143     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1144     if (aData) {
1145       TDF_Label& aShapeLab = aData->shapeLab();
1146       Handle(TNaming_NamedShape) aName;
1147       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1148         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
1149         if (aLatest.IsNull())
1150           return false;
1151         if (aLatest.IsEqual(aShape))
1152           return true;
1153         // check sub-shapes for comp-solids:
1154         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
1155           if (aLatest.IsEqual(anExp.Current()))
1156             return true;
1157         }
1158       }
1159     }
1160   }
1161   return false;
1162 }