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