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