Salome HOME
Issue #2561: CEA 2018-1 Cut
[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) // 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 void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
217   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
218 {
219   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
220   if (aData) {
221     TDF_Label& aShapeLab = aData->shapeLab();
222     // clean builders
223     if (theDecomposeSolidsTag != -2)
224       clean();
225     // store the new shape as primitive
226     TNaming_Builder aBuilder(aShapeLab);
227     if (!theOldShape || !theNewShape)
228       return;  // bad shape
229     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
230     if (aShapeOld.IsNull())
231       return;  // null shape inside
232     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
233     if (aShapeNew.IsNull())
234       return;  // null shape inside
235     aBuilder.Modify(aShapeOld, aShapeNew);
236     if(!aBuilder.NamedShape()->IsEmpty()) {
237       Handle(TDataStd_Name) anAttr;
238       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
239         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
240         if(!aName.empty()) {
241           std::shared_ptr<Model_Document> aDoc =
242             std::dynamic_pointer_cast<Model_Document>(document());
243           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
244         }
245       }
246     }
247   }
248 }
249
250 void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>& theShape)
251 {
252   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
253   if (aData) {
254     clean();
255     if (!theShape.get())
256       return; // bad shape
257     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
258     if (aShape.IsNull())
259       return;  // null shape inside
260     TNaming_Builder aBuilder(aData->shapeLab());
261     aBuilder.Select(aShape, aShape);
262   }
263 }
264
265 void Model_BodyBuilder::clean()
266 {
267   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
268   if (aLab.IsNull())
269     return;
270   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
271   for(; aBuilder != myBuilders.end(); aBuilder++) {
272     delete aBuilder->second;
273     // clear also shapes on cleaned sub-labels (#2241)
274     Handle(TNaming_NamedShape) aNS;
275     if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
276       aNS->Clear();
277     }
278   }
279   myBuilders.clear();
280   // remove the old reference (if any)
281   aLab.ForgetAttribute(TDF_Reference::GetID());
282   myDividedIndex = 1;
283   myVIndex = 1;
284   myEIndex = 1;
285   myFIndex = 1;
286 }
287
288 Model_BodyBuilder::~Model_BodyBuilder()
289 {
290   clean();
291 }
292
293 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
294 {
295   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
296   if (aFind == myBuilders.end()) {
297     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
298     myBuilders[theTag] = new TNaming_Builder(
299       theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
300     aFind = myBuilders.find(theTag);
301   }
302   return aFind->second;
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             builder(0)->Generated(aRoot, aNewShape);
691           } else {
692             builder(0)->Modify(aRoot, aNewShape);
693           }
694         }
695       }
696     }
697   }
698 }
699
700 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
701   GeomAlgoAPI_MakeShape* theMS,
702   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
703   const int  theKindOfShape,
704   const int  theTag,
705   const std::string& theName,
706   GeomAPI_DataMapOfShapeShape& theSubShapes)
707 {
708   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
709   TopTools_MapOfShape aView;
710   bool isBuilt = !theName.empty();
711   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
712   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
713     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
714     if (!aView.Add(aRoot)) continue;
715     //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
716     //  continue; // there is no sense to write history if old shape does not exist in the document
717     ListOfShape aList;
718     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
719     aRShape->setImpl((new TopoDS_Shape(aRoot)));
720     theMS->generated(aRShape, aList);
721     keepTopLevelShapes(aList, aRoot);
722     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
723       anIt = aList.begin(), aLast = aList.end();
724     for (; anIt != aLast; anIt++) {
725       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
726       if (theSubShapes.isBound(*anIt)) {
727         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
728         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
729       }
730       if (!aRoot.IsSame (aNewShape)) {
731         builder(theTag)->Generated(aRoot,aNewShape);
732         if(isBuilt)
733           buildName(theTag, theName);
734       }
735       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
736       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
737         TopAbs_ShapeEnum anExplodeShapeType =
738           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
739         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
740         int aTag = 1;
741         std::shared_ptr<Model_Document> aDoc =
742           std::dynamic_pointer_cast<Model_Document>(document());
743         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
744           TDF_Label aChildLabel = aLabel.FindChild(aTag);
745           TNaming_Builder aBuilder(aChildLabel);
746           aBuilder.Generated(aRoot, anExp.Current());
747           TCollection_AsciiString aChildName =
748             TCollection_AsciiString((theName + "_").c_str()) + aTag;
749           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
750           aTag++;
751         }
752       }
753     }
754   }
755 }
756
757 //=======================================================================
758 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
759   const TopAbs_ShapeEnum        theGeneratedFrom,
760   TopTools_DataMapOfShapeShape& theDangles)
761 {
762   theDangles.Clear();
763   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
764   TopAbs_ShapeEnum GeneratedTo;
765   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
766   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
767   else return Standard_False;
768   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
769   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
770     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
771     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
772     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
773   }
774   return theDangles.Extent();
775 }
776
777 //=======================================================================
778 void loadGeneratedDangleShapes(
779   const TopoDS_Shape&      theShapeIn,
780   const TopAbs_ShapeEnum   theGeneratedFrom,
781   TNaming_Builder *        theBuilder)
782 {
783   TopTools_DataMapOfShapeShape dangles;
784   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
785   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
786   for (; itr.More(); itr.Next())
787     theBuilder->Generated(itr.Key(), itr.Value());
788 }
789
790 //=======================================================================
791 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
792   const std::string& theName, int&  theTag)
793 {
794   if(theShape->isNull()) return;
795   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
796   std::string aName;
797   if (aShape.ShapeType() == TopAbs_SOLID) {
798     TopExp_Explorer expl(aShape, TopAbs_FACE);
799     for (; expl.More(); expl.Next()) {
800       builder(theTag)->Generated(expl.Current());
801       TCollection_AsciiString aStr(theTag);
802       aName = theName + aStr.ToCString();
803       buildName(theTag, aName);
804       theTag++;
805     }
806   }
807   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
808     // load faces and all the free edges
809     TopTools_IndexedMapOfShape Faces;
810     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
811     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
812       TopExp_Explorer expl(aShape, TopAbs_FACE);
813       for (; expl.More(); expl.Next()) {
814         builder(theTag)->Generated(expl.Current());
815         TCollection_AsciiString aStr(theTag);
816         aName = theName + aStr.ToCString();
817         buildName(theTag, aName);
818         theTag++;
819       }
820     }
821     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
822     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
823     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
824     {
825       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
826       if (aLL.Extent() < 2) {
827         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
828           continue;
829         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
830         TCollection_AsciiString aStr(theTag);
831         aName = theName + aStr.ToCString();
832         buildName(theTag, aName);
833         theTag++;
834       } else {
835         TopTools_ListIteratorOfListOfShape anIter(aLL);
836         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
837         anIter.Next();
838         if(aFace.IsEqual(anIter.Value())) {
839           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
840           TCollection_AsciiString aStr(theTag);
841           aName = theName + aStr.ToCString();
842           buildName(theTag, aName);
843           theTag++;
844         }
845       }
846     }
847   } else if (aShape.ShapeType() == TopAbs_WIRE) {
848     TopTools_IndexedMapOfShape Edges;
849     BRepTools::Map3DEdges(aShape, Edges);
850     if (Edges.Extent() == 1) {
851       builder(theTag++)->Generated(Edges.FindKey(1));
852       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
853       for (; expl.More(); expl.Next()) {
854         builder(theTag)->Generated(expl.Current());
855         TCollection_AsciiString aStr(theTag);
856         aName = theName + aStr.ToCString();
857         buildName(theTag, aName);
858         theTag++;
859       }
860     } else {
861       TopExp_Explorer expl(aShape, TopAbs_EDGE);
862       for (; expl.More(); expl.Next()) {
863         builder(theTag)->Generated(expl.Current());
864         TCollection_AsciiString aStr(theTag);
865         aName = theName + aStr.ToCString();
866         buildName(theTag, aName);
867         theTag++;
868       }
869       // and load generated vertices.
870       TopTools_DataMapOfShapeShape generated;
871       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
872       {
873         TNaming_Builder* pBuilder = builder(theTag++);
874         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
875       }
876     }
877   } else if (aShape.ShapeType() == TopAbs_EDGE) {
878     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
879     for (; expl.More(); expl.Next()) {
880       builder(theTag)->Generated(expl.Current());
881       TCollection_AsciiString aStr(theTag);
882       aName = theName + aStr.ToCString();
883       buildName(theTag, aName);
884       theTag++;
885     }
886   }
887 }
888
889 //=======================================================================
890 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
891   TopTools_ListOfShape&   theList)
892 {
893   theList.Clear();
894   // edges -> ancestor faces list
895   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
896   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
897   // keeps the shapes which are already in the resulting list
898   TopTools_MapOfShape alreadyThere;
899   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
900   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
901
902   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
903   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
904     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
905     if (ancestors.Extent() < 2)
906       continue;
907     Standard_Integer anID = 0;
908     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
909       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
910     }
911     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
912       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
913         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
914       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
915       for(; aSameEdge.More(); aSameEdge.Next()) {
916         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
917           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
918         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
919           break;
920
921         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
922         for(; aFaceIter1.More(); aFaceIter1.Next()) {
923           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
924           for(; aFaceIter2.More(); aFaceIter2.Next()) {
925             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
926               break;
927           }
928           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
929             break;
930         }
931         if (!aFaceIter1.More()) { // all the faces are same => put to the result
932           if (alreadyThere.Add(aSameEdge.Value()))
933             theList.Append(aSameEdge.Value());
934           if (alreadyThere.Add(anAncestorsIter.Key()))
935             theList.Append(anAncestorsIter.Key());
936         }
937       }
938     } else { // ID is unique, just add this edge
939       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
940     }
941     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
942   }
943   return theList.Extent();
944 }
945
946 //=======================================================================
947 void Model_BodyBuilder::loadFirstLevel(
948   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
949 {
950   if(theShape->isNull()) return;
951   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
952   std::string aName;
953   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
954     TopoDS_Iterator itr(aShape);
955     for (; itr.More(); itr.Next()) {
956       builder(theTag)->Generated(itr.Value());
957       TCollection_AsciiString aStr(theTag);
958       aName = theName + aStr.ToCString();
959       buildName(theTag, aName);
960       if(!theName.empty()) buildName(theTag, aName);
961       theTag++;
962       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
963         itr.Value().ShapeType() == TopAbs_COMPSOLID)
964       {
965         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
966         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
967         loadFirstLevel(itrShape, theName, theTag);
968       } else {
969         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
970         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
971         loadNextLevels(itrShape, theName, theTag);
972       }
973     }
974   } else {
975     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
976     itrShape->setImpl(new TopoDS_Shape(aShape));
977     loadNextLevels(itrShape, theName, theTag);
978   }
979   TopTools_ListOfShape   aList;
980   if(findAmbiguities(aShape, aList)) {
981     TopTools_ListIteratorOfListOfShape it(aList);
982     for (; it.More(); it.Next(),theTag++) {
983       builder(theTag)->Generated(it.Value());
984       TCollection_AsciiString aStr(theTag);
985       aName = theName + aStr.ToCString();
986       buildName(theTag, aName);
987     }
988   }
989 }
990
991 //=======================================================================
992 void Model_BodyBuilder::loadDisconnectedEdges(
993   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
994 {
995   if(theShape->isNull()) return;
996   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
997   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
998   TopTools_ListOfShape empty;
999   TopExp_Explorer explF(aShape, TopAbs_FACE);
1000   for (; explF.More(); explF.Next()) {
1001     const TopoDS_Shape& aFace = explF.Current();
1002     TopExp_Explorer explV(aFace, TopAbs_EDGE);
1003     for (; explV.More(); explV.Next()) {
1004       const TopoDS_Shape& anEdge = explV.Current();
1005       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
1006       Standard_Boolean faceIsNew = Standard_True;
1007       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
1008       for (; itrF.More(); itrF.Next()) {
1009         if (itrF.Value().IsSame(aFace)) {
1010           faceIsNew = Standard_False;
1011           break;
1012         }
1013       }
1014       if (faceIsNew)
1015         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
1016     }
1017   }
1018
1019   TopTools_MapOfShape anEdgesToDelete;
1020   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
1021   std::string aName;
1022   for(;anEx.More();anEx.Next()) {
1023     Standard_Boolean aC0 = Standard_False;
1024     TopoDS_Shape anEdge1 = anEx.Current();
1025     if (edgeNaborFaces.IsBound(anEdge1)) {
1026       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
1027       if (aList1.Extent()<2) continue;
1028       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
1029       for (; itr.More(); itr.Next()) {
1030         TopoDS_Shape anEdge2 = itr.Key();
1031         if(anEdgesToDelete.Contains(anEdge2)) continue;
1032         if (anEdge1.IsSame(anEdge2)) continue;
1033         const TopTools_ListOfShape& aList2 = itr.Value();
1034         // compare lists of the neighbour faces of edge1 and edge2
1035         if (aList1.Extent() == aList2.Extent()) {
1036           Standard_Integer aMatches = 0;
1037           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
1038             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
1039               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
1040           if (aMatches == aList1.Extent()) {
1041             aC0=Standard_True;
1042             builder(theTag)->Generated(anEdge2);
1043             anEdgesToDelete.Add(anEdge2);
1044             TCollection_AsciiString aStr(theTag);
1045             aName = theName + aStr.ToCString();
1046             buildName(theTag, aName);
1047             theTag++;
1048           }
1049         }
1050       }
1051       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
1052       for(;itDelete.More();itDelete.Next())
1053         edgeNaborFaces.UnBind(itDelete.Key());
1054       edgeNaborFaces.UnBind(anEdge1);
1055     }
1056     if (aC0) {
1057       builder(theTag)->Generated(anEdge1);
1058       TCollection_AsciiString aStr(theTag);
1059       aName = theName + aStr.ToCString();
1060       buildName(theTag, aName);
1061       theTag++;
1062     }
1063   }
1064 }
1065
1066 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
1067                                                  const std::string& theName, int&  theTag)
1068 {
1069   if(theShape->isNull()) return;
1070   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1071   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
1072   TopTools_ListOfShape empty;
1073   TopExp_Explorer explF(aShape, TopAbs_EDGE);
1074   for (; explF.More(); explF.Next()) {
1075     const TopoDS_Shape& anEdge = explF.Current();
1076     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
1077     for (; explV.More(); explV.Next()) {
1078       const TopoDS_Shape& aVertex = explV.Current();
1079       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
1080       Standard_Boolean faceIsNew = Standard_True;
1081       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
1082       for (; itrF.More(); itrF.Next()) {
1083         if (itrF.Value().IsSame(anEdge)) {
1084           faceIsNew = Standard_False;
1085           break;
1086         }
1087       }
1088       if (faceIsNew) {
1089         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
1090       }
1091     }
1092   }
1093   std::string aName;
1094   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
1095   for (; itr.More(); itr.Next()) {
1096     const TopTools_ListOfShape& naborEdges = itr.Value();
1097     if (naborEdges.Extent() < 2) {
1098       builder(theTag)->Generated(itr.Key());
1099       TCollection_AsciiString aStr(theTag);
1100       aName = theName + aStr.ToCString();
1101       buildName(theTag, aName);
1102       theTag++;
1103     }
1104   }
1105 }
1106
1107 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
1108 {
1109   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1110   if (aData) {
1111     TDF_Label aShapeLab = aData->shapeLab();
1112     Handle(TDF_Reference) aRef;
1113     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1114       aShapeLab = aRef->Get();
1115     }
1116     Handle(TNaming_NamedShape) aName;
1117     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1118       TopoDS_Shape aShape = aName->Get();
1119       if (!aShape.IsNull()) {
1120         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
1121         aRes->setImpl(new TopoDS_Shape(aShape));
1122         return aRes;
1123       }
1124     }
1125   }
1126   return std::shared_ptr<GeomAPI_Shape>();
1127 }
1128
1129 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
1130 {
1131   if (theShape.get()) {
1132     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1133     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1134     if (aData) {
1135       TDF_Label& aShapeLab = aData->shapeLab();
1136       Handle(TNaming_NamedShape) aName;
1137       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1138         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
1139         if (aLatest.IsNull())
1140           return false;
1141         if (aLatest.IsEqual(aShape))
1142           return true;
1143         // check sub-shapes for comp-solids:
1144         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
1145           if (aLatest.IsEqual(anExp.Current()))
1146             return true;
1147         }
1148       }
1149     }
1150   }
1151   return false;
1152 }