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