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