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