]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_BodyBuilder.cpp
Salome HOME
Keep also multiple modificators on the root shape of the body.
[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(
288       theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
289     aFind = myBuilders.find(theTag);
290   }
291   return aFind->second;
292 }
293
294 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
295 {
296   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
297   //aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), theName);
298   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), theName.c_str());
299 }
300 void Model_BodyBuilder::generated(
301   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
302 {
303   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
304   builder(theTag)->Generated(aShape);
305   if(!theName.empty())
306     buildName(theTag, theName);
307 }
308
309 void Model_BodyBuilder::generated(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
310   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
311 {
312   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
313   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
314   builder(theTag)->Generated(anOldShape, aNewShape);
315   if(!theName.empty())
316     buildName(theTag, theName);
317   TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
318   if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
319     TopAbs_ShapeEnum anExplodeShapeType = aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
320     const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
321     int aTag = 1;
322     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
323     for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
324       TDF_Label aChildLabel = aLabel.FindChild(aTag);
325       TNaming_Builder aBuilder(aChildLabel);
326       aBuilder.Generated(anOldShape, anExp.Current());
327       TCollection_AsciiString aChildName = TCollection_AsciiString((theName + "_").c_str()) + aTag;
328       //aDoc->addNamingName(aChildLabel, aChildName.ToCString());
329       TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
330       aTag++;
331     }
332   }
333 }
334
335
336 void Model_BodyBuilder::modified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
337   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
338 {
339   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
340   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
341   builder(theTag)->Modify(anOldShape, aNewShape);
342   if(!theName.empty())
343     buildName(theTag, theName);
344 }
345
346 void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
347   const int theTag)
348 {
349   TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
350   builder(theTag)->Delete(aShape);
351 }
352
353 void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
354   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
355   const int  theKindOfShape,
356   const int  theTag)
357 {
358   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
359   TopTools_MapOfShape aView;
360   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
361   for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
362     const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
363     if (!aView.Add(aRoot)) continue;
364     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
365     aRShape->setImpl((new TopoDS_Shape(aRoot)));
366     if (theMS->isDeleted (aRShape)) {
367       builder(theTag)->Delete(aRoot);
368     }
369   }
370 }
371
372 void Model_BodyBuilder::loadAndOrientModifiedShapes (
373   GeomAlgoAPI_MakeShape* theMS,
374   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
375   const int  theKindOfShape,
376   const int  theTag,
377   const std::string& theName,
378   GeomAPI_DataMapOfShapeShape& theSubShapes,
379   const bool theIsStoreSeparate,
380   const bool theIsStoreAsGenerated)
381 {
382   int anIndex = 1;
383   int aTag = theTag;
384   bool isBuilt = !theName.empty();
385   std::string aName = theName;
386   std::ostringstream aStream;
387   GeomShapePtr aResultShape = shape();
388   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
389   TopTools_MapOfShape aView;
390   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
391   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
392     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
393     if (!aView.Add(aRoot)) continue;
394     if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
395       continue; // there is no sense to write history if old shape does not exist in the document
396     ListOfShape aList;
397     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
398     aRShape->setImpl((new TopoDS_Shape(aRoot)));
399     theMS->modified(aRShape, aList);
400     // to trace situation where several objects are produced by one parent (#2317)
401     int aSameParentShapes = -1;
402     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
403       anIt = aList.begin(), aLast = aList.end();
404     for (; anIt != aLast; anIt++) {
405       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
406       if (theSubShapes.isBound(*anIt)) {
407         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
408         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
409       }
410       GeomShapePtr aGeomNewShape(new GeomAPI_Shape());
411       aGeomNewShape->setImpl(new TopoDS_Shape(aNewShape));
412       if(!aRoot.IsSame(aNewShape) && aResultShape->isSubShape(aGeomNewShape, false) &&
413          !aResultShape->isSame(*anIt)) { // to avoid put of same shape on main label and sub
414         int aBuilderTag = aTag;
415         if (!theIsStoreSeparate)
416           aSameParentShapes++;
417         if (aSameParentShapes > 0) { // store in other label
418           aBuilderTag = 100000 - aSameParentShapes * 10 - aTag;
419         }
420         if(theIsStoreAsGenerated) {
421           // Here we store shapes as generated, to avoid problem when one parent shape produce
422           // several child shapes. In this case naming could not determine which shape to select.
423           builder(aBuilderTag)->Generated(aRoot, aNewShape);
424         } else {
425           builder(aBuilderTag)->Modify(aRoot, aNewShape);
426         }
427         if(isBuilt) {
428           if(theIsStoreSeparate) {
429             aStream.str(std::string());
430             aStream.clear();
431             aStream << theName << "_" << anIndex++;
432             aName = aStream.str();
433           }
434           if (aSameParentShapes > 0) {
435             aStream.str(std::string());
436             aStream.clear();
437             aStream << aName << "_" << aSameParentShapes << "divided";
438             std::string aNameDiv = aStream.str();
439             buildName(aBuilderTag, aNameDiv);
440           } else {
441             buildName(aBuilderTag, aName);
442           }
443         }
444         if(theIsStoreSeparate) {
445           aTag++;
446         }
447       } else if (aResultShape->isSame(*anIt)) {
448         // keep the modification evolution on the root level (2241 - history propagation issue)
449         if(theIsStoreAsGenerated) {
450           builder(0)->Generated(aRoot, aNewShape);
451         } else {
452           builder(0)->Modify(aRoot, aNewShape);
453         }
454       }
455     }
456   }
457 }
458
459 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
460   GeomAlgoAPI_MakeShape* theMS,
461   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
462   const int  theKindOfShape,
463   const int  theTag,
464   const std::string& theName,
465   GeomAPI_DataMapOfShapeShape& theSubShapes)
466 {
467   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
468   TopTools_MapOfShape aView;
469   bool isBuilt = !theName.empty();
470   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
471   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
472     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
473     if (!aView.Add(aRoot)) continue;
474     //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
475     //  continue; // there is no sense to write history if old shape does not exist in the document
476     ListOfShape aList;
477     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
478     aRShape->setImpl((new TopoDS_Shape(aRoot)));
479     theMS->generated(aRShape, aList);
480     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
481       anIt = aList.begin(), aLast = aList.end();
482     for (; anIt != aLast; anIt++) {
483       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
484       if (theSubShapes.isBound(*anIt)) {
485         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
486         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
487       }
488       if (!aRoot.IsSame (aNewShape)) {
489         builder(theTag)->Generated(aRoot,aNewShape);
490         if(isBuilt)
491           buildName(theTag, theName);
492       }
493       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
494       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
495         TopAbs_ShapeEnum anExplodeShapeType =
496           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
497         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
498         int aTag = 1;
499         std::shared_ptr<Model_Document> aDoc =
500           std::dynamic_pointer_cast<Model_Document>(document());
501         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
502           TDF_Label aChildLabel = aLabel.FindChild(aTag);
503           TNaming_Builder aBuilder(aChildLabel);
504           aBuilder.Generated(aRoot, anExp.Current());
505           TCollection_AsciiString aChildName =
506             TCollection_AsciiString((theName + "_").c_str()) + aTag;
507           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
508           aTag++;
509         }
510       }
511     }
512   }
513 }
514
515 //=======================================================================
516 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
517   const TopAbs_ShapeEnum        theGeneratedFrom,
518   TopTools_DataMapOfShapeShape& theDangles)
519 {
520   theDangles.Clear();
521   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
522   TopAbs_ShapeEnum GeneratedTo;
523   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
524   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
525   else return Standard_False;
526   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
527   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
528     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
529     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
530     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
531   }
532   return theDangles.Extent();
533 }
534
535 //=======================================================================
536 void loadGeneratedDangleShapes(
537   const TopoDS_Shape&      theShapeIn,
538   const TopAbs_ShapeEnum   theGeneratedFrom,
539   TNaming_Builder *        theBuilder)
540 {
541   TopTools_DataMapOfShapeShape dangles;
542   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
543   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
544   for (; itr.More(); itr.Next())
545     theBuilder->Generated(itr.Key(), itr.Value());
546 }
547
548 //=======================================================================
549 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
550   const std::string& theName, int&  theTag)
551 {
552   if(theShape->isNull()) return;
553   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
554   std::string aName;
555   if (aShape.ShapeType() == TopAbs_SOLID) {
556     TopExp_Explorer expl(aShape, TopAbs_FACE);
557     for (; expl.More(); expl.Next()) {
558       builder(theTag)->Generated(expl.Current());
559       TCollection_AsciiString aStr(theTag);
560       aName = theName + aStr.ToCString();
561       buildName(theTag, aName);
562       theTag++;
563     }
564   }
565   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
566     // load faces and all the free edges
567     TopTools_IndexedMapOfShape Faces;
568     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
569     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
570       TopExp_Explorer expl(aShape, TopAbs_FACE);
571       for (; expl.More(); expl.Next()) {
572         builder(theTag)->Generated(expl.Current());
573         TCollection_AsciiString aStr(theTag);
574         aName = theName + aStr.ToCString();
575         buildName(theTag, aName);
576         theTag++;
577       }
578     }
579     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
580     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
581     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
582     {
583       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
584       if (aLL.Extent() < 2) {
585         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
586           continue;
587         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
588         TCollection_AsciiString aStr(theTag);
589         aName = theName + aStr.ToCString();
590         buildName(theTag, aName);
591         theTag++;
592       } else {
593         TopTools_ListIteratorOfListOfShape anIter(aLL);
594         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
595         anIter.Next();
596         if(aFace.IsEqual(anIter.Value())) {
597           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
598           TCollection_AsciiString aStr(theTag);
599           aName = theName + aStr.ToCString();
600           buildName(theTag, aName);
601           theTag++;
602         }
603       }
604     }
605   } else if (aShape.ShapeType() == TopAbs_WIRE) {
606     TopTools_IndexedMapOfShape Edges;
607     BRepTools::Map3DEdges(aShape, Edges);
608     if (Edges.Extent() == 1) {
609       builder(theTag++)->Generated(Edges.FindKey(1));
610       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
611       for (; expl.More(); expl.Next()) {
612         builder(theTag)->Generated(expl.Current());
613         TCollection_AsciiString aStr(theTag);
614         aName = theName + aStr.ToCString();
615         buildName(theTag, aName);
616         theTag++;
617       }
618     } else {
619       TopExp_Explorer expl(aShape, TopAbs_EDGE);
620       for (; expl.More(); expl.Next()) {
621         builder(theTag)->Generated(expl.Current());
622         TCollection_AsciiString aStr(theTag);
623         aName = theName + aStr.ToCString();
624         buildName(theTag, aName);
625         theTag++;
626       }
627       // and load generated vertices.
628       TopTools_DataMapOfShapeShape generated;
629       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
630       {
631         TNaming_Builder* pBuilder = builder(theTag++);
632         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
633       }
634     }
635   } else if (aShape.ShapeType() == TopAbs_EDGE) {
636     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
637     for (; expl.More(); expl.Next()) {
638       builder(theTag)->Generated(expl.Current());
639       TCollection_AsciiString aStr(theTag);
640       aName = theName + aStr.ToCString();
641       buildName(theTag, aName);
642       theTag++;
643     }
644   }
645 }
646
647 //=======================================================================
648 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
649   TopTools_ListOfShape&   theList)
650 {
651   theList.Clear();
652   // edges -> ancestor faces list
653   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
654   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
655   // keeps the shapes which are already in the resulting list
656   TopTools_MapOfShape alreadyThere;
657   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
658   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
659
660   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
661   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
662     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
663     if (ancestors.Extent() < 2)
664       continue;
665     Standard_Integer anID = 0;
666     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
667       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
668     }
669     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
670       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
671         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
672       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
673       for(; aSameEdge.More(); aSameEdge.Next()) {
674         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
675           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
676         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
677           break;
678
679         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
680         for(; aFaceIter1.More(); aFaceIter1.Next()) {
681           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
682           for(; aFaceIter2.More(); aFaceIter2.Next()) {
683             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
684               break;
685           }
686           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
687             break;
688         }
689         if (!aFaceIter1.More()) { // all the faces are same => put to the result
690           if (alreadyThere.Add(aSameEdge.Value()))
691             theList.Append(aSameEdge.Value());
692           if (alreadyThere.Add(anAncestorsIter.Key()))
693             theList.Append(anAncestorsIter.Key());
694         }
695       }
696     } else { // ID is unique, just add this edge
697       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
698     }
699     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
700   }
701   return theList.Extent();
702 }
703
704 //=======================================================================
705 void Model_BodyBuilder::loadFirstLevel(
706   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
707 {
708   if(theShape->isNull()) return;
709   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
710   std::string aName;
711   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
712     TopoDS_Iterator itr(aShape);
713     for (; itr.More(); itr.Next()) {
714       builder(theTag)->Generated(itr.Value());
715       TCollection_AsciiString aStr(theTag);
716       aName = theName + aStr.ToCString();
717       buildName(theTag, aName);
718       if(!theName.empty()) buildName(theTag, aName);
719       theTag++;
720       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
721         itr.Value().ShapeType() == TopAbs_COMPSOLID)
722       {
723         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
724         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
725         loadFirstLevel(itrShape, theName, theTag);
726       } else {
727         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
728         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
729         loadNextLevels(itrShape, theName, theTag);
730       }
731     }
732   } else {
733     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
734     itrShape->setImpl(new TopoDS_Shape(aShape));
735     loadNextLevels(itrShape, theName, theTag);
736   }
737   TopTools_ListOfShape   aList;
738   if(findAmbiguities(aShape, aList)) {
739     TopTools_ListIteratorOfListOfShape it(aList);
740     for (; it.More(); it.Next(),theTag++) {
741       builder(theTag)->Generated(it.Value());
742       TCollection_AsciiString aStr(theTag);
743       aName = theName + aStr.ToCString();
744       buildName(theTag, aName);
745     }
746   }
747 }
748
749 //=======================================================================
750 void Model_BodyBuilder::loadDisconnectedEdges(
751   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
752 {
753   if(theShape->isNull()) return;
754   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
755   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
756   TopTools_ListOfShape empty;
757   TopExp_Explorer explF(aShape, TopAbs_FACE);
758   for (; explF.More(); explF.Next()) {
759     const TopoDS_Shape& aFace = explF.Current();
760     TopExp_Explorer explV(aFace, TopAbs_EDGE);
761     for (; explV.More(); explV.Next()) {
762       const TopoDS_Shape& anEdge = explV.Current();
763       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
764       Standard_Boolean faceIsNew = Standard_True;
765       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
766       for (; itrF.More(); itrF.Next()) {
767         if (itrF.Value().IsSame(aFace)) {
768           faceIsNew = Standard_False;
769           break;
770         }
771       }
772       if (faceIsNew)
773         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
774     }
775   }
776
777   TopTools_MapOfShape anEdgesToDelete;
778   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
779   std::string aName;
780   for(;anEx.More();anEx.Next()) {
781     Standard_Boolean aC0 = Standard_False;
782     TopoDS_Shape anEdge1 = anEx.Current();
783     if (edgeNaborFaces.IsBound(anEdge1)) {
784       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
785       if (aList1.Extent()<2) continue;
786       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
787       for (; itr.More(); itr.Next()) {
788         TopoDS_Shape anEdge2 = itr.Key();
789         if(anEdgesToDelete.Contains(anEdge2)) continue;
790         if (anEdge1.IsSame(anEdge2)) continue;
791         const TopTools_ListOfShape& aList2 = itr.Value();
792         // compare lists of the neighbour faces of edge1 and edge2
793         if (aList1.Extent() == aList2.Extent()) {
794           Standard_Integer aMatches = 0;
795           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
796             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
797               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
798           if (aMatches == aList1.Extent()) {
799             aC0=Standard_True;
800             builder(theTag)->Generated(anEdge2);
801             anEdgesToDelete.Add(anEdge2);
802             TCollection_AsciiString aStr(theTag);
803             aName = theName + aStr.ToCString();
804             buildName(theTag, aName);
805             theTag++;
806           }
807         }
808       }
809       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
810       for(;itDelete.More();itDelete.Next())
811         edgeNaborFaces.UnBind(itDelete.Key());
812       edgeNaborFaces.UnBind(anEdge1);
813     }
814     if (aC0) {
815       builder(theTag)->Generated(anEdge1);
816       TCollection_AsciiString aStr(theTag);
817       aName = theName + aStr.ToCString();
818       buildName(theTag, aName);
819       theTag++;
820     }
821   }
822 }
823
824 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
825                                                  const std::string& theName, int&  theTag)
826 {
827   if(theShape->isNull()) return;
828   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
829   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
830   TopTools_ListOfShape empty;
831   TopExp_Explorer explF(aShape, TopAbs_EDGE);
832   for (; explF.More(); explF.Next()) {
833     const TopoDS_Shape& anEdge = explF.Current();
834     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
835     for (; explV.More(); explV.Next()) {
836       const TopoDS_Shape& aVertex = explV.Current();
837       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
838       Standard_Boolean faceIsNew = Standard_True;
839       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
840       for (; itrF.More(); itrF.Next()) {
841         if (itrF.Value().IsSame(anEdge)) {
842           faceIsNew = Standard_False;
843           break;
844         }
845       }
846       if (faceIsNew) {
847         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
848       }
849     }
850   }
851   std::string aName;
852   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
853   for (; itr.More(); itr.Next()) {
854     const TopTools_ListOfShape& naborEdges = itr.Value();
855     if (naborEdges.Extent() < 2) {
856       builder(theTag)->Generated(itr.Key());
857       TCollection_AsciiString aStr(theTag);
858       aName = theName + aStr.ToCString();
859       buildName(theTag, aName);
860       theTag++;
861     }
862   }
863 }
864
865 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
866 {
867   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
868   if (aData) {
869     TDF_Label aShapeLab = aData->shapeLab();
870     Handle(TDF_Reference) aRef;
871     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
872       aShapeLab = aRef->Get();
873     }
874     Handle(TNaming_NamedShape) aName;
875     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
876       TopoDS_Shape aShape = aName->Get();
877       if (!aShape.IsNull()) {
878         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
879         aRes->setImpl(new TopoDS_Shape(aShape));
880         return aRes;
881       }
882     }
883   }
884   return std::shared_ptr<GeomAPI_Shape>();
885 }
886
887 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
888 {
889   if (theShape.get()) {
890     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
891     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
892     if (aData) {
893       TDF_Label& aShapeLab = aData->shapeLab();
894       Handle(TNaming_NamedShape) aName;
895       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
896         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
897         if (aLatest.IsNull())
898           return false;
899         if (aLatest.IsEqual(aShape))
900           return true;
901         // check sub-shapes for comp-solids:
902         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
903           if (aLatest.IsEqual(anExp.Current()))
904             return true;
905         }
906       }
907     }
908   }
909   return false;
910 }