]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_BodyBuilder.cpp
Salome HOME
Additional fix for the #2659 optimization
[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   const GeomShapePtr theShapes)
369 {
370   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
371   TopTools_MapOfShape aView;
372   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
373   GeomShapePtr aResultShape = shape();
374   for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
375     const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
376     if (!aView.Add(aRoot)) continue;
377     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
378     aRShape->setImpl((new TopoDS_Shape(aRoot)));
379     if (!theMS->isDeleted(aRShape)
380         || aResultShape->isSubShape(aRShape, false)
381         || (theShapes.get() && theShapes->isSubShape(aRShape, false))) {
382       continue;
383     }
384
385     ListOfShape aHist;
386     if (BRepTools_History::IsSupportedType(aRoot)) // to avoid crash in #2572
387       theMS->modified(aRShape, aHist);
388     if (aHist.size() == 0 || (aHist.size() == 1 && aHist.front()->isSame(aRShape)))
389       builder(theTag)->Delete(aRoot);
390   }
391 }
392
393 static void removeBadShapes(ListOfShape& theShapes)
394 {
395   ListOfShape::iterator anIt = theShapes.begin();
396   while (anIt != theShapes.end()) {
397     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
398     bool aSkip = aNewShape.IsNull()
399       || (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
400     if (aSkip) {
401       ListOfShape::iterator aRemoveIt = anIt++;
402       theShapes.erase(aRemoveIt);
403     } else {
404       ++anIt;
405     }
406   }
407 }
408
409 // Keep only the shapes with minimal shape type
410 static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRoot,
411   const GeomShapePtr& theResultShape = GeomShapePtr())
412 {
413   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
414   ListOfShape::iterator anIt = theShapes.begin();
415   while (anIt != theShapes.end()) {
416     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
417     bool aSkip = aNewShape.IsNull() ||
418       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
419     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
420         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
421       ListOfShape::iterator aRemoveIt = anIt++;
422       theShapes.erase(aRemoveIt);
423     } else {
424       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
425       if (aType < aKeepShapeType) {
426         // found a shape with lesser shape type => remove all previous shapes
427         aKeepShapeType = aType;
428         theShapes.erase(theShapes.begin(), anIt);
429         ++anIt;
430       } else if (aType > aKeepShapeType) {
431         // shapes with greater shape type should be removed from the list
432         ListOfShape::iterator aRemoveIt = anIt++;
433         theShapes.erase(aRemoveIt);
434       } else
435         ++anIt;
436     }
437   }
438 }
439
440 // returns an ancestor shape-type thaty used for naming-definition of the sub-type
441 TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
442   if (theSubType == TopAbs_VERTEX)
443     return TopAbs_EDGE;
444   if (theSubType == TopAbs_EDGE)
445     return TopAbs_FACE;
446   return TopAbs_VERTEX; // bad case
447 }
448
449 void Model_BodyBuilder::loadAndOrientModifiedShapes (
450   GeomAlgoAPI_MakeShape* theMS,
451   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
452   const int  theKindOfShape,
453   const int  theTag,
454   const std::string& theName,
455   GeomAPI_DataMapOfShapeShape& theSubShapes,
456   const bool theIsStoreSeparate,
457   const bool theIsStoreAsGenerated)
458 {
459   static const int THE_ANCHOR_TAG = 100000;
460
461   int anIndex = 1;
462   int aTag = theTag;
463   bool isBuilt = !theName.empty();
464   std::string aName = theName;
465   std::ostringstream aStream;
466   GeomShapePtr aResultShape = shape();
467   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
468   TopTools_MapOfShape aView;
469   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
470
471   TopoDS_Shape aShapeToIterate;
472   if (theMS->newShapesCollected(theShapeIn, theKindOfShape)) {
473     // use optimized set of old shapes for this
474     GeomShapePtr aCompound = theMS->oldShapesForNew(theShapeIn, aResultShape, theKindOfShape);
475     if (aCompound.get())
476       aShapeToIterate = aCompound->impl<TopoDS_Shape>();
477   } else {
478     aShapeToIterate = aShapeIn;
479   }
480
481   TopExp_Explorer aShapeExplorer (aShapeToIterate, (TopAbs_ShapeEnum)theKindOfShape);
482   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
483     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
484     if (!aView.Add(aRoot)) continue;
485
486     bool aNotInTree =
487       TNaming_Tool::NamedShape(aRoot, aData->shapeLab()).IsNull();
488     if (aNotInTree && !theIsStoreSeparate) {
489       // there is no sense to write history if old shape does not exist in the document
490       continue; // but if it is stored separately, it will be builded as a primitive
491     }
492     ListOfShape aList;
493     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
494     aRShape->setImpl((new TopoDS_Shape(aRoot)));
495     theMS->modified(aRShape, aList);
496
497     if (!theIsStoreSeparate) {
498       //keepTopLevelShapes(aList, aRoot, aResultShape);
499       removeBadShapes(aList);
500     }
501     // sort the list of images before naming
502     GeomAlgoAPI_SortListOfShapes::sort(aList);
503
504     // to trace situation where several objects are produced by one parent (#2317)
505     int aSameParentShapes = (aShapeIn.ShapeType() == TopAbs_WIRE
506                              || aShapeIn.ShapeType() == TopAbs_SHELL
507                              || aShapeIn.ShapeType() == TopAbs_COMPOUND) ? 0 : -1;
508     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
509       anIt = aList.begin(), aLast = aList.end();
510     for (; anIt != aLast; anIt++) {
511       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
512       if (theSubShapes.isBound(*anIt)) {
513         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
514         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
515       }
516       isBuilt = !theName.empty();
517       if(!aRoot.IsSame(aNewShape)
518          && aResultShape->isSubShape((*anIt), false)
519          && !aResultShape->isSame(*anIt)) // to avoid put of same shape on main label and sub
520       {
521         if (!theIsStoreSeparate) {
522           aSameParentShapes++;
523         } else if (aNotInTree) // check this new shape can not be represented as
524                               // a sub-shape of higher level sub-shapes
525         {
526           TopAbs_ShapeEnum aNewType = aNewShape.ShapeType();
527           TopAbs_ShapeEnum anAncestorType = typeOfAncestor(aNewType);
528           if (anAncestorType != TopAbs_VERTEX) {
529             bool aFound = false;
530             TopoDS_Shape aResultTShape = aResultShape->impl<TopoDS_Shape>();
531             TopExp_Explorer anAncestorExp(aResultTShape, anAncestorType);
532             for(; anAncestorExp.More() && !aFound; anAncestorExp.Next()) {
533               if (aResultTShape.IsSame(anAncestorExp.Current()))
534                 continue;
535               TopExp_Explorer aSubExp(anAncestorExp.Current(), aNewType);
536               for(; aSubExp.More(); aSubExp.Next()) {
537                 if (aNewShape.IsSame(aSubExp.Current())) {
538                   aFound = true;
539                   break;
540                 }
541               }
542             }
543             if (aFound) {
544               continue; // not need to store this shape in the BRep structure
545             }
546           }
547         }
548
549         int aFoundTag = 0;
550         bool isFoundSameOld = false;
551         bool isFoundDiffOld = false;
552
553         // Check if new shape was already stored.
554         for (std::map<int, TNaming_Builder*>::iterator aBuildersIt = myBuilders.begin();
555              aBuildersIt != myBuilders.end();
556              ++aBuildersIt)
557         {
558           TNaming_Builder* aBuilder = aBuildersIt->second;
559           for (TNaming_Iterator aNamingIt(aBuilder->NamedShape());
560                aNamingIt.More();
561                aNamingIt.Next())
562           {
563             if (aNamingIt.NewShape().IsSame(aNewShape))
564             {
565               aNamingIt.OldShape().IsSame(aRoot) ? isFoundSameOld = true
566                                                  : isFoundDiffOld = true;
567               aFoundTag = aBuildersIt->first;
568             }
569           }
570
571           if (isFoundSameOld || isFoundDiffOld) break;
572         }
573
574         if (isFoundSameOld) {
575           // Builder already contains same old->new shapes, don't store it twice.
576           continue;
577         }
578
579         int aBuilderTag = aSameParentShapes > 0 ? THE_ANCHOR_TAG : aTag;
580
581         int aCurShapeType = (int)((*anIt)->shapeType());
582         bool needSuffix = false; // suffix for the name based on the shape type
583         if (aCurShapeType != theKindOfShape) {
584           // modified shape has different type => set another tag
585           // to avoid shapes of different types on the same label
586           aBuilderTag = THE_ANCHOR_TAG;
587           needSuffix = true;
588         }
589         std::string aSuffix;
590         if (needSuffix) {
591           switch (aCurShapeType) {
592             case GeomAPI_Shape::VERTEX: aSuffix = "_v_" + std::to_string(myVIndex++); break;
593             case GeomAPI_Shape::EDGE:   aSuffix = "_e_" + std::to_string(myEIndex++); break;
594             case GeomAPI_Shape::FACE:   aSuffix = "_f_" + std::to_string(myFIndex++); break;
595             default: break;
596           }
597         }
598
599         std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>> aKeepShapes, aMoveShapes;
600         if (isFoundDiffOld) {
601           // Found same new shape with different old shape.
602           if (aFoundTag >= THE_ANCHOR_TAG) {
603             // Found on separated tag.
604             aBuilderTag = aFoundTag; // Store it on the same tag.
605             isBuilt = false; // Don't change name;
606           } else {
607             // Found on previous tag.
608             if (aBuilderTag < THE_ANCHOR_TAG) {
609               // New shape shouls not be separated.
610               aBuilderTag = aFoundTag; // Store it on the same tag.
611               isBuilt = false; // Don't change name;
612             } else {
613               // New shape should be separated from others. Move shapes from found tag to new tag.
614               while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
615                 ++aBuilderTag;
616               }
617
618               TNaming_Builder* aFoundBuilder = myBuilders.at(aFoundTag);
619               Handle(TNaming_NamedShape) aFoundNamedShape = aFoundBuilder->NamedShape();
620               TDF_Label aFoundLabel = aFoundNamedShape->Label();
621               TNaming_Evolution anEvolution = aFoundNamedShape->Evolution();
622               for (TNaming_Iterator aNamingIt(aFoundNamedShape);
623                    aNamingIt.More();
624                    aNamingIt.Next())
625               {
626                 std::pair<TopoDS_Shape, TopoDS_Shape> aShapesPair =
627                   std::make_pair(aNamingIt.OldShape(), aNamingIt.NewShape());
628                 aNamingIt.NewShape().IsSame(aNewShape) ? aMoveShapes.push_back(aShapesPair)
629                                                        : aKeepShapes.push_back(aShapesPair);
630               }
631
632               aFoundNamedShape->Clear();
633               for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aKeepIt =
634                      aKeepShapes.begin();
635                    aKeepIt != aKeepShapes.end();
636                    ++aKeepIt)
637               {
638                 if (anEvolution == TNaming_GENERATED) {
639                   aFoundBuilder->Generated(aKeepIt->first, aKeepIt->second);
640                 } else {
641                   aFoundBuilder->Modify(aKeepIt->first, aKeepIt->second);
642                 }
643               }
644             }
645           }
646         } else if (aBuilderTag == THE_ANCHOR_TAG) {
647           while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
648             ++aBuilderTag;
649           }
650         }
651
652         if(theIsStoreAsGenerated) {
653           // Here we store shapes as generated, to avoid problem when one parent shape produce
654           // several child shapes. In this case naming could not determine which shape to select.
655           builder(aBuilderTag)->Generated(aRoot, aNewShape);
656           for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
657                aMoveShapes.begin();
658                aMoveIt != aMoveShapes.end();
659                ++aMoveIt)
660           {
661             builder(aBuilderTag)->Generated(aMoveIt->first, aMoveIt->second);
662           }
663         } else if (aNotInTree) {
664           // not in tree -> store as primitive (stored as separated)
665           builder(aBuilderTag)->Generated(aNewShape);
666         } else if (aCurShapeType != theKindOfShape) {
667            // if different shape type is produced, make it as generated
668           builder(aBuilderTag)->Generated(aRoot, aNewShape);
669         } else {
670           builder(aBuilderTag)->Modify(aRoot, aNewShape);
671           for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
672                aMoveShapes.begin();
673                aMoveIt != aMoveShapes.end();
674                ++aMoveIt) {
675             builder(aBuilderTag)->Modify(aMoveIt->first, aMoveIt->second);
676           }
677         }
678         if(isBuilt) {
679           aStream.str(std::string());
680           aStream.clear();
681           aStream << theName;
682           if (theIsStoreSeparate && !isFoundDiffOld)
683              aStream << "_" << anIndex++;
684
685           if (aSameParentShapes > 0) {
686             aStream.str(std::string());
687             aStream.clear();
688             aStream << aName << "_" << "divided" << "_" << myDividedIndex++;
689           }
690
691           aStream << aSuffix;
692           buildName(aBuilderTag, aStream.str());
693         }
694         if(theIsStoreSeparate && !isFoundDiffOld) {
695           aTag++;
696         }
697       } else if (aResultShape->isSame(*anIt)) {
698         // keep the modification evolution on the root level (2241 - history propagation issue)
699         TNaming_Builder* aBuilder = builder(0);
700         TDF_Label aShapeLab = aBuilder->NamedShape()->Label();
701         Handle(TDF_Reference) aRef;
702         // Store only in case if it does not have reference.
703         if (!aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
704           if (theIsStoreAsGenerated) {
705             TNaming_Builder* aBuilder = builder(0);
706             if (!aBuilder->NamedShape().IsNull() &&
707                 aBuilder->NamedShape()->Evolution() != TNaming_GENERATED) {
708               myBuilders.erase(0); // clear old builder to avoid different evolutions crash
709             }
710             builder(0)->Generated(aRoot, aNewShape);
711           } else {
712             TNaming_Builder* aBuilder = builder(0);
713             if (!aBuilder->NamedShape().IsNull() &&
714               aBuilder->NamedShape()->Evolution() != TNaming_MODIFY) {
715               myBuilders.erase(0); // clear old builder to avoid different evolutions crash
716             }
717             builder(0)->Modify(aRoot, aNewShape);
718           }
719         }
720       }
721     }
722   }
723 }
724
725 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
726   GeomAlgoAPI_MakeShape* theMS,
727   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
728   const int  theKindOfShape,
729   const int  theTag,
730   const std::string& theName,
731   GeomAPI_DataMapOfShapeShape& theSubShapes)
732 {
733   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
734   TopTools_MapOfShape aView;
735   bool isBuilt = !theName.empty();
736   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
737   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
738     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
739     if (!aView.Add(aRoot)) continue;
740     //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
741     //  continue; // there is no sense to write history if old shape does not exist in the document
742     ListOfShape aList;
743     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
744     aRShape->setImpl((new TopoDS_Shape(aRoot)));
745     theMS->generated(aRShape, aList);
746     keepTopLevelShapes(aList, aRoot);
747     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
748       anIt = aList.begin(), aLast = aList.end();
749     for (; anIt != aLast; anIt++) {
750       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
751       if (theSubShapes.isBound(*anIt)) {
752         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
753         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
754       }
755       if (!aRoot.IsSame (aNewShape)) {
756         builder(theTag)->Generated(aRoot,aNewShape);
757         if(isBuilt)
758           buildName(theTag, theName);
759       }
760       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
761       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
762         TopAbs_ShapeEnum anExplodeShapeType =
763           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
764         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
765         int aTag = 1;
766         std::shared_ptr<Model_Document> aDoc =
767           std::dynamic_pointer_cast<Model_Document>(document());
768         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
769           TDF_Label aChildLabel = aLabel.FindChild(aTag);
770           TNaming_Builder aBuilder(aChildLabel);
771           aBuilder.Generated(aRoot, anExp.Current());
772           TCollection_AsciiString aChildName =
773             TCollection_AsciiString((theName + "_").c_str()) + aTag;
774           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
775           aTag++;
776         }
777       }
778     }
779   }
780 }
781
782 //=======================================================================
783 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
784   const TopAbs_ShapeEnum        theGeneratedFrom,
785   TopTools_DataMapOfShapeShape& theDangles)
786 {
787   theDangles.Clear();
788   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
789   TopAbs_ShapeEnum GeneratedTo;
790   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
791   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
792   else return Standard_False;
793   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
794   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
795     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
796     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
797     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
798   }
799   return theDangles.Extent();
800 }
801
802 //=======================================================================
803 void loadGeneratedDangleShapes(
804   const TopoDS_Shape&      theShapeIn,
805   const TopAbs_ShapeEnum   theGeneratedFrom,
806   TNaming_Builder *        theBuilder)
807 {
808   TopTools_DataMapOfShapeShape dangles;
809   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
810   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
811   for (; itr.More(); itr.Next())
812     theBuilder->Generated(itr.Key(), itr.Value());
813 }
814
815 //=======================================================================
816 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
817   const std::string& theName, int&  theTag)
818 {
819   if(theShape->isNull()) return;
820   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
821   std::string aName;
822   if (aShape.ShapeType() == TopAbs_SOLID) {
823     TopExp_Explorer expl(aShape, TopAbs_FACE);
824     for (; expl.More(); expl.Next()) {
825       builder(theTag)->Generated(expl.Current());
826       TCollection_AsciiString aStr(theTag);
827       aName = theName + aStr.ToCString();
828       buildName(theTag, aName);
829       theTag++;
830     }
831   }
832   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
833     // load faces and all the free edges
834     TopTools_IndexedMapOfShape Faces;
835     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
836     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
837       TopExp_Explorer expl(aShape, TopAbs_FACE);
838       for (; expl.More(); expl.Next()) {
839         builder(theTag)->Generated(expl.Current());
840         TCollection_AsciiString aStr(theTag);
841         aName = theName + aStr.ToCString();
842         buildName(theTag, aName);
843         theTag++;
844       }
845     }
846     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
847     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
848     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
849     {
850       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
851       if (aLL.Extent() < 2) {
852         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
853           continue;
854         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
855         TCollection_AsciiString aStr(theTag);
856         aName = theName + aStr.ToCString();
857         buildName(theTag, aName);
858         theTag++;
859       } else {
860         TopTools_ListIteratorOfListOfShape anIter(aLL);
861         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
862         anIter.Next();
863         if(aFace.IsEqual(anIter.Value())) {
864           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
865           TCollection_AsciiString aStr(theTag);
866           aName = theName + aStr.ToCString();
867           buildName(theTag, aName);
868           theTag++;
869         }
870       }
871     }
872   } else if (aShape.ShapeType() == TopAbs_WIRE) {
873     TopTools_IndexedMapOfShape Edges;
874     BRepTools::Map3DEdges(aShape, Edges);
875     if (Edges.Extent() == 1) {
876       builder(theTag++)->Generated(Edges.FindKey(1));
877       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
878       for (; expl.More(); expl.Next()) {
879         builder(theTag)->Generated(expl.Current());
880         TCollection_AsciiString aStr(theTag);
881         aName = theName + aStr.ToCString();
882         buildName(theTag, aName);
883         theTag++;
884       }
885     } else {
886       TopExp_Explorer expl(aShape, TopAbs_EDGE);
887       for (; expl.More(); expl.Next()) {
888         builder(theTag)->Generated(expl.Current());
889         TCollection_AsciiString aStr(theTag);
890         aName = theName + aStr.ToCString();
891         buildName(theTag, aName);
892         theTag++;
893       }
894       // and load generated vertices.
895       TopTools_DataMapOfShapeShape generated;
896       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
897       {
898         TNaming_Builder* pBuilder = builder(theTag++);
899         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
900       }
901     }
902   } else if (aShape.ShapeType() == TopAbs_EDGE) {
903     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
904     for (; expl.More(); expl.Next()) {
905       builder(theTag)->Generated(expl.Current());
906       TCollection_AsciiString aStr(theTag);
907       aName = theName + aStr.ToCString();
908       buildName(theTag, aName);
909       theTag++;
910     }
911   }
912 }
913
914 //=======================================================================
915 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
916   TopTools_ListOfShape&   theList)
917 {
918   theList.Clear();
919   // edges -> ancestor faces list
920   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
921   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
922   // keeps the shapes which are already in the resulting list
923   TopTools_MapOfShape alreadyThere;
924   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
925   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
926
927   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
928   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
929     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
930     if (ancestors.Extent() < 2)
931       continue;
932     Standard_Integer anID = 0;
933     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
934       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
935     }
936     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
937       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
938         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
939       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
940       for(; aSameEdge.More(); aSameEdge.Next()) {
941         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
942           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
943         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
944           break;
945
946         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
947         for(; aFaceIter1.More(); aFaceIter1.Next()) {
948           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
949           for(; aFaceIter2.More(); aFaceIter2.Next()) {
950             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
951               break;
952           }
953           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
954             break;
955         }
956         if (!aFaceIter1.More()) { // all the faces are same => put to the result
957           if (alreadyThere.Add(aSameEdge.Value()))
958             theList.Append(aSameEdge.Value());
959           if (alreadyThere.Add(anAncestorsIter.Key()))
960             theList.Append(anAncestorsIter.Key());
961         }
962       }
963     } else { // ID is unique, just add this edge
964       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
965     }
966     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
967   }
968   return theList.Extent();
969 }
970
971 //=======================================================================
972 void Model_BodyBuilder::loadFirstLevel(
973   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
974 {
975   if(theShape->isNull()) return;
976   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
977   std::string aName;
978   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
979     TopoDS_Iterator itr(aShape);
980     for (; itr.More(); itr.Next()) {
981       builder(theTag)->Generated(itr.Value());
982       TCollection_AsciiString aStr(theTag);
983       aName = theName + aStr.ToCString();
984       buildName(theTag, aName);
985       if(!theName.empty()) buildName(theTag, aName);
986       theTag++;
987       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
988         itr.Value().ShapeType() == TopAbs_COMPSOLID)
989       {
990         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
991         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
992         loadFirstLevel(itrShape, theName, theTag);
993       } else {
994         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
995         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
996         loadNextLevels(itrShape, theName, theTag);
997       }
998     }
999   } else {
1000     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
1001     itrShape->setImpl(new TopoDS_Shape(aShape));
1002     loadNextLevels(itrShape, theName, theTag);
1003   }
1004   TopTools_ListOfShape   aList;
1005   if(findAmbiguities(aShape, aList)) {
1006     TopTools_ListIteratorOfListOfShape it(aList);
1007     for (; it.More(); it.Next(),theTag++) {
1008       builder(theTag)->Generated(it.Value());
1009       TCollection_AsciiString aStr(theTag);
1010       aName = theName + aStr.ToCString();
1011       buildName(theTag, aName);
1012     }
1013   }
1014 }
1015
1016 //=======================================================================
1017 void Model_BodyBuilder::loadDisconnectedEdges(
1018   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
1019 {
1020   if(theShape->isNull()) return;
1021   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1022   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
1023   TopTools_ListOfShape empty;
1024   TopExp_Explorer explF(aShape, TopAbs_FACE);
1025   for (; explF.More(); explF.Next()) {
1026     const TopoDS_Shape& aFace = explF.Current();
1027     TopExp_Explorer explV(aFace, TopAbs_EDGE);
1028     for (; explV.More(); explV.Next()) {
1029       const TopoDS_Shape& anEdge = explV.Current();
1030       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
1031       Standard_Boolean faceIsNew = Standard_True;
1032       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
1033       for (; itrF.More(); itrF.Next()) {
1034         if (itrF.Value().IsSame(aFace)) {
1035           faceIsNew = Standard_False;
1036           break;
1037         }
1038       }
1039       if (faceIsNew)
1040         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
1041     }
1042   }
1043
1044   TopTools_MapOfShape anEdgesToDelete;
1045   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
1046   std::string aName;
1047   for(;anEx.More();anEx.Next()) {
1048     Standard_Boolean aC0 = Standard_False;
1049     TopoDS_Shape anEdge1 = anEx.Current();
1050     if (edgeNaborFaces.IsBound(anEdge1)) {
1051       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
1052       if (aList1.Extent()<2) continue;
1053       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
1054       for (; itr.More(); itr.Next()) {
1055         TopoDS_Shape anEdge2 = itr.Key();
1056         if(anEdgesToDelete.Contains(anEdge2)) continue;
1057         if (anEdge1.IsSame(anEdge2)) continue;
1058         const TopTools_ListOfShape& aList2 = itr.Value();
1059         // compare lists of the neighbour faces of edge1 and edge2
1060         if (aList1.Extent() == aList2.Extent()) {
1061           Standard_Integer aMatches = 0;
1062           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
1063             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
1064               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
1065           if (aMatches == aList1.Extent()) {
1066             aC0=Standard_True;
1067             builder(theTag)->Generated(anEdge2);
1068             anEdgesToDelete.Add(anEdge2);
1069             TCollection_AsciiString aStr(theTag);
1070             aName = theName + aStr.ToCString();
1071             buildName(theTag, aName);
1072             theTag++;
1073           }
1074         }
1075       }
1076       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
1077       for(;itDelete.More();itDelete.Next())
1078         edgeNaborFaces.UnBind(itDelete.Key());
1079       edgeNaborFaces.UnBind(anEdge1);
1080     }
1081     if (aC0) {
1082       builder(theTag)->Generated(anEdge1);
1083       TCollection_AsciiString aStr(theTag);
1084       aName = theName + aStr.ToCString();
1085       buildName(theTag, aName);
1086       theTag++;
1087     }
1088   }
1089 }
1090
1091 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
1092                                                  const std::string& theName, int&  theTag)
1093 {
1094   if(theShape->isNull()) return;
1095   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1096   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
1097   TopTools_ListOfShape empty;
1098   TopExp_Explorer explF(aShape, TopAbs_EDGE);
1099   for (; explF.More(); explF.Next()) {
1100     const TopoDS_Shape& anEdge = explF.Current();
1101     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
1102     for (; explV.More(); explV.Next()) {
1103       const TopoDS_Shape& aVertex = explV.Current();
1104       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
1105       Standard_Boolean faceIsNew = Standard_True;
1106       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
1107       for (; itrF.More(); itrF.Next()) {
1108         if (itrF.Value().IsSame(anEdge)) {
1109           faceIsNew = Standard_False;
1110           break;
1111         }
1112       }
1113       if (faceIsNew) {
1114         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
1115       }
1116     }
1117   }
1118   std::string aName;
1119   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
1120   for (; itr.More(); itr.Next()) {
1121     const TopTools_ListOfShape& naborEdges = itr.Value();
1122     if (naborEdges.Extent() < 2) {
1123       builder(theTag)->Generated(itr.Key());
1124       TCollection_AsciiString aStr(theTag);
1125       aName = theName + aStr.ToCString();
1126       buildName(theTag, aName);
1127       theTag++;
1128     }
1129   }
1130 }
1131
1132 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
1133 {
1134   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1135   if (aData && aData->isValid()) {
1136     TDF_Label aShapeLab = aData->shapeLab();
1137     Handle(TDF_Reference) aRef;
1138     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1139       aShapeLab = aRef->Get();
1140     }
1141     Handle(TNaming_NamedShape) aName;
1142     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1143       TopoDS_Shape aShape = aName->Get();
1144       if (!aShape.IsNull()) {
1145         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
1146         aRes->setImpl(new TopoDS_Shape(aShape));
1147         return aRes;
1148       }
1149     }
1150   }
1151   return std::shared_ptr<GeomAPI_Shape>();
1152 }
1153
1154 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
1155 {
1156   if (theShape.get()) {
1157     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1158     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1159     if (aData) {
1160       TDF_Label& aShapeLab = aData->shapeLab();
1161       Handle(TNaming_NamedShape) aName;
1162       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1163         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
1164         if (aLatest.IsNull())
1165           return false;
1166         if (aLatest.IsEqual(aShape))
1167           return true;
1168         // check sub-shapes for comp-solids:
1169         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
1170           if (aLatest.IsEqual(anExp.Current()))
1171             return true;
1172         }
1173       }
1174     }
1175   }
1176   return false;
1177 }