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