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