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