Salome HOME
Memory usage optimization for Builders on big tags creation (like Partition).
[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_Reference.hxx>
35 #include <TopTools_MapOfShape.hxx>
36 #include <TopExp_Explorer.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_ListIteratorOfListOfShape.hxx>
39 #include <TopTools_DataMapOfShapeListOfShape.hxx>
40 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
41 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
42 #include <TopTools_MapIteratorOfMapOfShape.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_IndexedMapOfShape.hxx>
45 #include <TopTools_DataMapOfShapeShape.hxx>
46 #include <TopExp.hxx>
47 #include <BRepTools.hxx>
48 #include <BRep_Tool.hxx>
49 #include <GeomAPI_Shape.h>
50 #include <GeomAlgoAPI_MakeShape.h>
51 #include <Config_PropManager.h>
52 // DEB
53 //#include <TCollection_AsciiString.hxx>
54 //#include <TDF_Tool.hxx>
55 //#define DEB_IMPORT 1
56
57 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
58 : ModelAPI_BodyBuilder(theOwner)
59 {
60 }
61
62 // Converts evolution of naming shape to selection evelution and back to avoid
63 // naming support on the disabled results. Deeply in the labels tree, recursively.
64 static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
65   std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
66   Handle(TNaming_NamedShape) aName;
67   int anEvolution = -1;
68   if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
69     TNaming_Evolution aNSEvol = aName->Evolution();
70     if ((aNSEvol == TNaming_SELECTED && theFlag) ||
71         (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
72       return;
73     }
74     anEvolution = (int)(aNSEvol);
75     if (!theFlag) {
76       Handle(TDataStd_Integer) anAttrEvol;
77       if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
78         anEvolution = anAttrEvol->Get();
79       }
80     } else {
81       TDataStd_Integer::Set(theLab, anEvolution);
82     }
83
84     for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
85       // iterator goes in reversed order relatively to the Builder, to, make the list reversed
86       aShapePairs.push_front(std::pair<TopoDS_Shape, TopoDS_Shape>
87         (anIter.OldShape(), anIter.NewShape()));
88     }
89
90     // create new
91     TNaming_Builder aBuilder(theLab);
92     TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
93     std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
94     for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
95       if (theFlag) { // disabled => make selection
96         aBuilder.Select(aPairsIter->second, aPairsIter->first);
97       } else if (anEvol == TNaming_GENERATED) {
98         aBuilder.Generated(aPairsIter->first, aPairsIter->second);
99       } else if (anEvol == TNaming_MODIFY) {
100         aBuilder.Modify(aPairsIter->first, aPairsIter->second);
101       } else if (anEvol == TNaming_DELETE) {
102         aBuilder.Delete(aPairsIter->first);
103       } else if (anEvol == TNaming_PRIMITIVE) {
104         aBuilder.Generated(aPairsIter->second);
105       } else if (anEvol == TNaming_SELECTED) {
106         aBuilder.Select(aPairsIter->second, aPairsIter->first);
107       }
108     }
109   }
110   // recursive call for all sub-labels
111   TDF_ChildIterator anIter(theLab, Standard_False);
112   for(; anIter.More(); anIter.Next()) {
113     evolutionToSelectionRec(anIter.Value(), theFlag);
114   }
115 }
116
117 void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
118 {
119   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
120   if (!aData) // unknown case
121     return;
122   TDF_Label& aShapeLab = aData->shapeLab();
123   evolutionToSelectionRec(aShapeLab, theFlag);
124 }
125
126 void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
127                               const bool theIsStoreSameShapes)
128 {
129   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
130   if (aData) {
131     TDF_Label& aShapeLab = aData->shapeLab();
132     // clean builders
133     clean();
134     // store the new shape as primitive
135     TNaming_Builder aBuilder(aShapeLab);
136     if (!theShape)
137       return;  // bad shape
138     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
139     if (aShape.IsNull())
140       return;  // null shape inside
141
142     if(!theIsStoreSameShapes) {
143       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
144       if(!aNS.IsNull() && !aNS->IsEmpty()) {
145         // This shape is already in document, store reference instead of shape;
146         const TDF_Label aFoundLabel = aNS->Label();
147         TDF_Reference::Set(aShapeLab, aFoundLabel);
148         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
149         return;
150       }
151     }
152
153     aBuilder.Generated(aShape);
154     // register name
155     aShapeLab.ForgetAttribute(TDF_Reference::GetID());
156     if(!aBuilder.NamedShape()->IsEmpty()) {
157       Handle(TDataStd_Name) anAttr;
158       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
159         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
160         if(!aName.empty()) {
161           std::shared_ptr<Model_Document> aDoc =
162             std::dynamic_pointer_cast<Model_Document>(document());
163           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
164         }
165       }
166     }
167   }
168 }
169
170 void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& theFromShape,
171   const std::shared_ptr<GeomAPI_Shape>& theToShape)
172 {
173   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
174   if (aData) {
175     TDF_Label& aShapeLab = aData->shapeLab();
176     // clean builders
177     clean();
178     // store the new shape as primitive
179     TNaming_Builder aBuilder(aShapeLab);
180     if (!theFromShape || !theToShape)
181       return;  // bad shape
182     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
183     if (aShapeBasis.IsNull())
184       return;  // null shape inside
185     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
186     if (aShapeNew.IsNull())
187       return;  // null shape inside
188     aBuilder.Generated(aShapeBasis, aShapeNew);
189     // register name
190     if(!aBuilder.NamedShape()->IsEmpty()) {
191       Handle(TDataStd_Name) anAttr;
192       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
193         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
194         if(!aName.empty()) {
195           std::shared_ptr<Model_Document> aDoc =
196             std::dynamic_pointer_cast<Model_Document>(document());
197           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
198         }
199       }
200     }
201   }
202 }
203
204 void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
205   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
206 {
207   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
208   if (aData) {
209     TDF_Label& aShapeLab = aData->shapeLab();
210     // clean builders
211     clean();
212     // store the new shape as primitive
213     TNaming_Builder aBuilder(aShapeLab);
214     if (!theOldShape || !theNewShape)
215       return;  // bad shape
216     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
217     if (aShapeOld.IsNull())
218       return;  // null shape inside
219     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
220     if (aShapeNew.IsNull())
221       return;  // null shape inside
222     aBuilder.Modify(aShapeOld, aShapeNew);
223     if(!aBuilder.NamedShape()->IsEmpty()) {
224       Handle(TDataStd_Name) anAttr;
225       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
226         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
227         if(!aName.empty()) {
228           std::shared_ptr<Model_Document> aDoc =
229             std::dynamic_pointer_cast<Model_Document>(document());
230           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
231         }
232       }
233     }
234   }
235 }
236
237 void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>& theShape)
238 {
239   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
240   if (aData) {
241     clean();
242     if (!theShape.get())
243       return; // bad shape
244     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
245     if (aShape.IsNull())
246       return;  // null shape inside
247     TNaming_Builder aBuilder(aData->shapeLab());
248     aBuilder.Select(aShape, aShape);
249   }
250 }
251
252 void Model_BodyBuilder::clean()
253 {
254   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
255   for(; aBuilder != myBuilders.end(); aBuilder++)
256     delete aBuilder->second;
257   myBuilders.clear();
258 }
259
260 Model_BodyBuilder::~Model_BodyBuilder()
261 {
262   clean();
263 }
264
265 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
266 {
267   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
268   if (aFind == myBuilders.end()) {
269     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
270     myBuilders[theTag] = new TNaming_Builder(aData->shapeLab().FindChild(theTag));
271     aFind = myBuilders.find(theTag);
272   }
273   return aFind->second;
274 }
275
276 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
277 {
278   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
279   //aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), theName);
280   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), theName.c_str());
281 }
282 void Model_BodyBuilder::generated(
283   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
284 {
285   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
286   builder(theTag)->Generated(aShape);
287   if(!theName.empty())
288     buildName(theTag, theName);
289 }
290
291 void Model_BodyBuilder::generated(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
292   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
293 {
294   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
295   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
296   builder(theTag)->Generated(anOldShape, aNewShape);
297   if(!theName.empty())
298     buildName(theTag, theName);
299   TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
300   if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
301     TopAbs_ShapeEnum anExplodeShapeType = aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
302     const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
303     int aTag = 1;
304     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
305     for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
306       TDF_Label aChildLabel = aLabel.FindChild(aTag);
307       TNaming_Builder aBuilder(aChildLabel);
308       aBuilder.Generated(anOldShape, anExp.Current());
309       TCollection_AsciiString aChildName = TCollection_AsciiString((theName + "_").c_str()) + aTag;
310       //aDoc->addNamingName(aChildLabel, aChildName.ToCString());
311       TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
312       aTag++;
313     }
314   }
315 }
316
317
318 void Model_BodyBuilder::modified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
319   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
320 {
321   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
322   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
323   builder(theTag)->Modify(anOldShape, aNewShape);
324   if(!theName.empty())
325     buildName(theTag, theName);
326 }
327
328 void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
329   const int theTag)
330 {
331   TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
332   builder(theTag)->Delete(aShape);
333 }
334
335 void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
336   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
337   const int  theKindOfShape,
338   const int  theTag)
339 {
340   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
341   TopTools_MapOfShape aView;
342   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
343   for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
344     const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
345     if (!aView.Add(aRoot)) continue;
346     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
347     aRShape->setImpl((new TopoDS_Shape(aRoot)));
348     if (theMS->isDeleted (aRShape)) {
349       builder(theTag)->Delete(aRoot);
350     }
351   }
352 }
353
354 void Model_BodyBuilder::loadAndOrientModifiedShapes (
355   GeomAlgoAPI_MakeShape* theMS,
356   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
357   const int  theKindOfShape,
358   const int  theTag,
359   const std::string& theName,
360   GeomAPI_DataMapOfShapeShape& theSubShapes,
361   const bool theIsStoreSeparate,
362   const bool theIsStoreAsGenerated)
363 {
364   int anIndex = 1;
365   int aTag = theTag;
366   bool isBuilt = !theName.empty();
367   std::string aName = theName;
368   std::ostringstream aStream;
369   GeomShapePtr aResultShape = shape();
370   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
371   TopTools_MapOfShape aView;
372   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
373   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
374     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
375     if (!aView.Add(aRoot)) continue;
376     ListOfShape aList;
377     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
378     aRShape->setImpl((new TopoDS_Shape(aRoot)));
379     theMS->modified(aRShape, aList);
380     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
381       anIt = aList.begin(), aLast = aList.end();
382     for (; anIt != aLast; anIt++) {
383       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
384       if (theSubShapes.isBound(*anIt)) {
385         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
386         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
387       }
388       GeomShapePtr aGeomNewShape(new GeomAPI_Shape());
389       aGeomNewShape->setImpl(new TopoDS_Shape(aNewShape));
390       if(!aRoot.IsSame(aNewShape) && aResultShape->isSubShape(aGeomNewShape)) {
391         if(theIsStoreAsGenerated) {
392           // Here we store shapes as generated, to avoid problem when one parent shape produce
393           // several child shapes. In this case naming could not determine which shape to select.
394           builder(aTag)->Generated(aRoot,aNewShape);
395         } else {
396           builder(aTag)->Modify(aRoot,aNewShape);
397         }
398         if(isBuilt) {
399           if(theIsStoreSeparate) {
400             aStream.str(std::string());
401             aStream.clear();
402             aStream << theName << "_" << anIndex++;
403             aName = aStream.str();
404           }
405           buildName(aTag, aName);
406         }
407         if(theIsStoreSeparate) {
408           aTag++;
409         }
410       }
411     }
412   }
413 }
414
415 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
416   GeomAlgoAPI_MakeShape* theMS,
417   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
418   const int  theKindOfShape,
419   const int  theTag,
420   const std::string& theName,
421   GeomAPI_DataMapOfShapeShape& theSubShapes)
422 {
423   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
424   TopTools_MapOfShape aView;
425   bool isBuilt = !theName.empty();
426   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
427   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
428     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
429     if (!aView.Add(aRoot)) continue;
430     ListOfShape aList;
431     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
432     aRShape->setImpl((new TopoDS_Shape(aRoot)));
433     theMS->generated(aRShape, aList);
434     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
435       anIt = aList.begin(), aLast = aList.end();
436     for (; anIt != aLast; anIt++) {
437       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
438       if (theSubShapes.isBound(*anIt)) {
439         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
440         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
441       }
442       if (!aRoot.IsSame (aNewShape)) {
443         builder(theTag)->Generated(aRoot,aNewShape);
444         if(isBuilt)
445           buildName(theTag, theName);
446       }
447       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
448       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
449         TopAbs_ShapeEnum anExplodeShapeType =
450           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
451         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
452         int aTag = 1;
453         std::shared_ptr<Model_Document> aDoc =
454           std::dynamic_pointer_cast<Model_Document>(document());
455         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
456           TDF_Label aChildLabel = aLabel.FindChild(aTag);
457           TNaming_Builder aBuilder(aChildLabel);
458           aBuilder.Generated(aRoot, anExp.Current());
459           TCollection_AsciiString aChildName =
460             TCollection_AsciiString((theName + "_").c_str()) + aTag;
461           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
462           aTag++;
463         }
464       }
465     }
466   }
467 }
468
469 //=======================================================================
470 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
471   const TopAbs_ShapeEnum        theGeneratedFrom,
472   TopTools_DataMapOfShapeShape& theDangles)
473 {
474   theDangles.Clear();
475   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
476   TopAbs_ShapeEnum GeneratedTo;
477   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
478   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
479   else return Standard_False;
480   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
481   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
482     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
483     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
484     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
485   }
486   return theDangles.Extent();
487 }
488
489 //=======================================================================
490 void loadGeneratedDangleShapes(
491   const TopoDS_Shape&      theShapeIn,
492   const TopAbs_ShapeEnum   theGeneratedFrom,
493   TNaming_Builder *        theBuilder)
494 {
495   TopTools_DataMapOfShapeShape dangles;
496   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
497   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
498   for (; itr.More(); itr.Next())
499     theBuilder->Generated(itr.Key(), itr.Value());
500 }
501
502 //=======================================================================
503 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
504   const std::string& theName, int&  theTag)
505 {
506   if(theShape->isNull()) return;
507   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
508   std::string aName;
509   if (aShape.ShapeType() == TopAbs_SOLID) {
510     TopExp_Explorer expl(aShape, TopAbs_FACE);
511     for (; expl.More(); expl.Next()) {
512       builder(theTag)->Generated(expl.Current());
513       TCollection_AsciiString aStr(theTag);
514       aName = theName + aStr.ToCString();
515       buildName(theTag, aName);
516       theTag++;
517     }
518   }
519   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
520     // load faces and all the free edges
521     TopTools_IndexedMapOfShape Faces;
522     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
523     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
524       TopExp_Explorer expl(aShape, TopAbs_FACE);
525       for (; expl.More(); expl.Next()) {
526         builder(theTag)->Generated(expl.Current());
527         TCollection_AsciiString aStr(theTag);
528         aName = theName + aStr.ToCString();
529         buildName(theTag, aName);
530         theTag++;
531       }
532     }
533     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
534     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
535     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
536     {
537       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
538       if (aLL.Extent() < 2) {
539         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
540           continue;
541         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
542         TCollection_AsciiString aStr(theTag);
543         aName = theName + aStr.ToCString();
544         buildName(theTag, aName);
545         theTag++;
546       } else {
547         TopTools_ListIteratorOfListOfShape anIter(aLL);
548         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
549         anIter.Next();
550         if(aFace.IsEqual(anIter.Value())) {
551           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
552           TCollection_AsciiString aStr(theTag);
553           aName = theName + aStr.ToCString();
554           buildName(theTag, aName);
555           theTag++;
556         }
557       }
558     }
559   } else if (aShape.ShapeType() == TopAbs_WIRE) {
560     TopTools_IndexedMapOfShape Edges;
561     BRepTools::Map3DEdges(aShape, Edges);
562     if (Edges.Extent() == 1) {
563       builder(++theTag)->Generated(Edges.FindKey(1));
564       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
565       for (; expl.More(); expl.Next()) {
566         builder(theTag)->Generated(expl.Current());
567         TCollection_AsciiString aStr(theTag);
568         aName = theName + aStr.ToCString();
569         buildName(theTag, aName);
570         theTag++;
571       }
572     } else {
573       TopExp_Explorer expl(aShape, TopAbs_EDGE);
574       for (; expl.More(); expl.Next()) {
575         builder(theTag)->Generated(expl.Current());
576         TCollection_AsciiString aStr(theTag);
577         aName = theName + aStr.ToCString();
578         buildName(theTag, aName);
579         theTag++;
580       }
581       // and load generated vertices.
582       TopTools_DataMapOfShapeShape generated;
583       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
584       {
585         TNaming_Builder* pBuilder = builder(theTag++);
586         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
587       }
588     }
589   } else if (aShape.ShapeType() == TopAbs_EDGE) {
590     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
591     for (; expl.More(); expl.Next()) {
592       builder(theTag)->Generated(expl.Current());
593       TCollection_AsciiString aStr(theTag);
594       aName = theName + aStr.ToCString();
595       buildName(theTag, aName);
596       theTag++;
597     }
598   }
599 }
600
601 //=======================================================================
602 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
603   TopTools_ListOfShape&   theList)
604 {
605   int aNumEdges(0);
606   theList.Clear();
607   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
608   TopAbs_ShapeEnum aTS(TopAbs_EDGE);
609   TopAbs_ShapeEnum aTA(TopAbs_FACE);
610   TopTools_MapOfShape aMap1, aMap2; // map1 - for edge ancestors; map2 - for keys => edges
611   TopTools_ListOfShape aKeyList;
612   TopExp::MapShapesAndAncestors(theShapeIn, aTS, aTA, subShapeAndAncestors);
613   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
614     const TopoDS_Shape& aKeyEdge1 = subShapeAndAncestors.FindKey(i);
615     const TopTools_ListOfShape& ancestors1 = subShapeAndAncestors.FindFromIndex(i);
616     aMap1.Clear();
617     TopTools_ListIteratorOfListOfShape it(ancestors1);
618     for(;it.More();it.Next()) aMap1.Add(it.Value()); // fill map with key ancestors => aKey1
619     for (Standard_Integer j = 1; j <= subShapeAndAncestors.Extent(); j++) {
620       if (i == j) continue;
621       const TopoDS_Shape& aKeyEdge2 = subShapeAndAncestors.FindKey(j);
622       const TopTools_ListOfShape& ancestors2 = subShapeAndAncestors.FindFromIndex(j);
623       if(ancestors1.Extent() == ancestors2.Extent() && ancestors1.Extent() > 1) {
624         int aNum (ancestors2.Extent());
625         TopTools_ListIteratorOfListOfShape it(ancestors2);
626         for(;it.More();it.Next())
627           if(aMap1.Contains(it.Value())) aNum--;
628         if(aNum == 0) {
629           if(aMap2.Add(aKeyEdge1))
630             aKeyList.Append(aKeyEdge1);
631           if(aMap2.Add(aKeyEdge2))
632             aKeyList.Append(aKeyEdge2);
633         }
634       }
635     } // at the end ==> List of edges to be named in addition
636   }
637   aNumEdges = aKeyList.Extent();
638   if(aNumEdges)
639     theList.Assign(aKeyList);
640   return aNumEdges;
641 }
642
643 //=======================================================================
644 void Model_BodyBuilder::loadFirstLevel(
645   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
646 {
647   if(theShape->isNull()) return;
648   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
649   std::string aName;
650   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
651     TopoDS_Iterator itr(aShape);
652     for (; itr.More(); itr.Next(),theTag++) {
653       builder(theTag)->Generated(itr.Value());
654       TCollection_AsciiString aStr(theTag);
655       aName = theName + aStr.ToCString();
656       buildName(theTag, aName);
657       if(!theName.empty()) buildName(theTag, aName);
658       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
659         itr.Value().ShapeType() == TopAbs_COMPSOLID)
660       {
661         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
662         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
663         loadFirstLevel(itrShape, theName, theTag);
664       } else {
665         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
666         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
667         loadNextLevels(itrShape, theName, theTag);
668       }
669     }
670   } else {
671     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
672     itrShape->setImpl(new TopoDS_Shape(aShape));
673     loadNextLevels(itrShape, theName, theTag);
674   }
675   TopTools_ListOfShape   aList;
676   if(findAmbiguities(aShape, aList)) {
677     TopTools_ListIteratorOfListOfShape it(aList);
678     for (; it.More(); it.Next(),theTag++) {
679       builder(theTag)->Generated(it.Value());
680       TCollection_AsciiString aStr(theTag);
681       aName = theName + aStr.ToCString();
682       buildName(theTag, aName);
683     }
684   }
685 }
686
687 //=======================================================================
688 void Model_BodyBuilder::loadDisconnectedEdges(
689   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
690 {
691   if(theShape->isNull()) return;
692   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
693   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
694   TopTools_ListOfShape empty;
695   TopExp_Explorer explF(aShape, TopAbs_FACE);
696   for (; explF.More(); explF.Next()) {
697     const TopoDS_Shape& aFace = explF.Current();
698     TopExp_Explorer explV(aFace, TopAbs_EDGE);
699     for (; explV.More(); explV.Next()) {
700       const TopoDS_Shape& anEdge = explV.Current();
701       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
702       Standard_Boolean faceIsNew = Standard_True;
703       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
704       for (; itrF.More(); itrF.Next()) {
705         if (itrF.Value().IsSame(aFace)) {
706           faceIsNew = Standard_False;
707           break;
708         }
709       }
710       if (faceIsNew)
711         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
712     }
713   }
714
715   TopTools_MapOfShape anEdgesToDelete;
716   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
717   std::string aName;
718   for(;anEx.More();anEx.Next()) {
719     Standard_Boolean aC0 = Standard_False;
720     TopoDS_Shape anEdge1 = anEx.Current();
721     if (edgeNaborFaces.IsBound(anEdge1)) {
722       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
723       if (aList1.Extent()<2) continue;
724       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
725       for (; itr.More(); itr.Next()) {
726         TopoDS_Shape anEdge2 = itr.Key();
727         if(anEdgesToDelete.Contains(anEdge2)) continue;
728         if (anEdge1.IsSame(anEdge2)) continue;
729         const TopTools_ListOfShape& aList2 = itr.Value();
730         // compare lists of the neighbour faces of edge1 and edge2
731         if (aList1.Extent() == aList2.Extent()) {
732           Standard_Integer aMatches = 0;
733           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
734             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
735               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
736           if (aMatches == aList1.Extent()) {
737             aC0=Standard_True;
738             builder(theTag)->Generated(anEdge2);
739             anEdgesToDelete.Add(anEdge2);
740             TCollection_AsciiString aStr(theTag);
741             aName = theName + aStr.ToCString();
742             buildName(theTag, aName);
743             theTag++;
744           }
745         }
746       }
747       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
748       for(;itDelete.More();itDelete.Next())
749         edgeNaborFaces.UnBind(itDelete.Key());
750       edgeNaborFaces.UnBind(anEdge1);
751     }
752     if (aC0) {
753       builder(theTag)->Generated(anEdge1);
754       TCollection_AsciiString aStr(theTag);
755       aName = theName + aStr.ToCString();
756       buildName(theTag, aName);
757       theTag++;
758     }
759   }
760 }
761
762 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
763                                                  const std::string& theName, int&  theTag)
764 {
765   if(theShape->isNull()) return;
766   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
767   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
768   TopTools_ListOfShape empty;
769   TopExp_Explorer explF(aShape, TopAbs_EDGE);
770   for (; explF.More(); explF.Next()) {
771     const TopoDS_Shape& anEdge = explF.Current();
772     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
773     for (; explV.More(); explV.Next()) {
774       const TopoDS_Shape& aVertex = explV.Current();
775       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
776       Standard_Boolean faceIsNew = Standard_True;
777       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
778       for (; itrF.More(); itrF.Next()) {
779         if (itrF.Value().IsSame(anEdge)) {
780           faceIsNew = Standard_False;
781           break;
782         }
783       }
784       if (faceIsNew) {
785         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
786       }
787     }
788   }
789   std::string aName;
790   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
791   for (; itr.More(); itr.Next()) {
792     const TopTools_ListOfShape& naborEdges = itr.Value();
793     if (naborEdges.Extent() < 2) {
794       builder(theTag)->Generated(itr.Key());
795       TCollection_AsciiString aStr(theTag);
796       aName = theName + aStr.ToCString();
797       buildName(theTag, aName);
798       theTag++;
799     }
800   }
801 }
802
803 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
804 {
805   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
806   if (aData) {
807     TDF_Label aShapeLab = aData->shapeLab();
808     Handle(TDF_Reference) aRef;
809     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
810       aShapeLab = aRef->Get();
811     }
812     Handle(TNaming_NamedShape) aName;
813     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
814       TopoDS_Shape aShape = aName->Get();
815       if (!aShape.IsNull()) {
816         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
817         aRes->setImpl(new TopoDS_Shape(aShape));
818         return aRes;
819       }
820     }
821   }
822   return std::shared_ptr<GeomAPI_Shape>();
823 }
824
825 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
826 {
827   if (theShape.get()) {
828     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
829     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
830     if (aData) {
831       TDF_Label& aShapeLab = aData->shapeLab();
832       Handle(TNaming_NamedShape) aName;
833       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
834         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
835         if (aLatest.IsNull())
836           return false;
837         if (aLatest.IsEqual(aShape))
838           return true;
839         // check sub-shapes for comp-solids:
840         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
841           if (aLatest.IsEqual(anExp.Current()))
842             return true;
843         }
844       }
845     }
846   }
847   return false;
848 }