]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_BodyBuilder.cpp
Salome HOME
d4e81b0eb42961a146f7925b76e780dbec70a704
[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 <BRepTools_History.hxx>
51 #include <GeomAPI_Shape.h>
52 #include <GeomAPI_ShapeExplorer.h>
53 #include <GeomAlgoAPI_MakeShape.h>
54 #include <GeomAlgoAPI_SortListOfShapes.h>
55 #include <Config_PropManager.h>
56 // DEB
57 //#include <TCollection_AsciiString.hxx>
58 //#include <TDF_Tool.hxx>
59 //#define DEB_IMPORT 1
60
61 static const int INVALID_TAG            = -1;
62 static const int GENERATED_VERTICES_TAG = 1;
63 static const int GENERATED_EDGES_TAG    = 2;
64 static const int GENERATED_FACES_TAG    = 3;
65 static const int MODIFIED_VERTICES_TAG  = 4;
66 static const int MODIFIED_EDGES_TAG     = 5;
67 static const int MODIFIED_FACES_TAG     = 6;
68 static const int DELETED_TAG            = 7;
69 static const int PRIMITIVES_START_TAG   = 11;
70
71 static int getGenerationTag(const TopoDS_Shape& theShape) {
72   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
73   switch (aShapeType) {
74     case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
75     case TopAbs_EDGE:   return GENERATED_EDGES_TAG;
76     case TopAbs_FACE:   return GENERATED_FACES_TAG;
77   }
78
79   return INVALID_TAG;
80 }
81
82 static int getModificationTag(const TopoDS_Shape& theShape) {
83   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
84   switch (aShapeType) {
85     case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
86     case TopAbs_EDGE:   return MODIFIED_EDGES_TAG;
87     case TopAbs_FACE:   return MODIFIED_FACES_TAG;
88   }
89
90   return INVALID_TAG;
91 }
92
93 static TopAbs_ShapeEnum convertShapeType(const GeomAPI_Shape::ShapeType theType) {
94   switch (theType) {
95     case GeomAPI_Shape::VERTEX:    return TopAbs_VERTEX;
96     case GeomAPI_Shape::EDGE:      return TopAbs_EDGE;
97     case GeomAPI_Shape::WIRE:      return TopAbs_WIRE;
98     case GeomAPI_Shape::FACE:      return TopAbs_FACE;
99     case GeomAPI_Shape::SHELL:     return TopAbs_SHELL;
100     case GeomAPI_Shape::SOLID:     return TopAbs_SOLID;
101     case GeomAPI_Shape::COMPSOLID: return TopAbs_COMPSOLID;
102     case GeomAPI_Shape::COMPOUND:  return TopAbs_COMPOUND;
103     case GeomAPI_Shape::SHAPE:     return TopAbs_SHAPE;
104   }
105   return TopAbs_SHAPE;
106 }
107
108 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
109                             const TopoDS_Shape& theOldShape,
110                             const TopoDS_Shape& theNewShape)
111 {
112   for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
113     aNamingIt.More();
114     aNamingIt.Next())
115   {
116     if (aNamingIt.NewShape().IsSame(theNewShape)
117       && aNamingIt.OldShape().IsSame(theOldShape))
118     {
119       return true;
120     }
121   }
122
123   return false;
124 }
125
126 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
127 : ModelAPI_BodyBuilder(theOwner),
128   myFreePrimitiveTag(PRIMITIVES_START_TAG)
129 {
130 }
131
132 void Model_BodyBuilder::store(const GeomShapePtr& 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 GeomShapePtr& theFromShape,
177   const GeomShapePtr& 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 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
211 {
212   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
213   if (aFind == myBuilders.end()) {
214     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
215     myBuilders[theTag] = new TNaming_Builder(
216       theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
217     aFind = myBuilders.find(theTag);
218   }
219   return aFind->second;
220 }
221
222 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
223                                       const GeomShapePtr& theNewShape,
224                                       const bool theIsCleanStored)
225 {
226   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
227   if (aData) {
228     // clean builders
229     if (theIsCleanStored) clean();
230     // store the new shape as primitive
231     TNaming_Builder* aBuilder = builder(0);
232     if (!theOldShape || !theNewShape)
233       return;  // bad shape
234     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
235     if (aShapeOld.IsNull())
236       return;  // null shape inside
237     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
238     if (aShapeNew.IsNull())
239       return;  // null shape inside
240     aBuilder->Modify(aShapeOld, aShapeNew);
241     if(!aBuilder->NamedShape()->IsEmpty()) {
242       Handle(TDataStd_Name) anAttr;
243       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
244         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
245         if(!aName.empty()) {
246           std::shared_ptr<Model_Document> aDoc =
247             std::dynamic_pointer_cast<Model_Document>(document());
248           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
249         }
250       }
251     }
252   }
253 }
254
255 void  Model_BodyBuilder::storeWithoutNaming(const GeomShapePtr& theShape)
256 {
257   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
258   if (aData) {
259     clean();
260     if (!theShape.get())
261       return; // bad shape
262     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
263     if (aShape.IsNull())
264       return;  // null shape inside
265     TNaming_Builder aBuilder(aData->shapeLab());
266     aBuilder.Select(aShape, aShape);
267   }
268 }
269
270 void Model_BodyBuilder::clean()
271 {
272   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
273   if (aLab.IsNull())
274     return;
275   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
276   for(; aBuilder != myBuilders.end(); aBuilder++) {
277     delete aBuilder->second;
278     // clear also shapes on cleaned sub-labels (#2241)
279     Handle(TNaming_NamedShape) aNS;
280     if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
281       aNS->Clear();
282     }
283   }
284   myBuilders.clear();
285   // remove the old reference (if any)
286   aLab.ForgetAttribute(TDF_Reference::GetID());
287   myFreePrimitiveTag = PRIMITIVES_START_TAG;
288 }
289
290 Model_BodyBuilder::~Model_BodyBuilder()
291 {
292   clean();
293 }
294
295 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
296 {
297   std::string aName = theName;
298   std::string aPrefix = "";
299   switch (theTag) {
300     case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
301     case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
302     case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
303     case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
304     case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
305     case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
306   }
307   aName.insert(0, aPrefix);
308
309   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
310 }
311 void Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
312                                   const std::string& theName)
313 {
314   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
315   builder(myFreePrimitiveTag)->Generated(aShape);
316   if (!theName.empty()) {
317     buildName(myFreePrimitiveTag, theName);
318   }
319   ++myFreePrimitiveTag;
320 }
321
322 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
323                                   const GeomShapePtr& theNewShape,
324                                   const std::string& theName)
325 {
326   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
327   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
328   TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
329   int aTag;
330   if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
331     // TODO: This is a workaround. New shape should be only vertex, edge or face.
332     TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
333     aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
334     for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
335       builder(aTag)->Generated(anOldShape, anExp.Current());
336     }
337     buildName(aTag, theName);
338   } else {
339     aTag = getGenerationTag(aNewShape);
340     if (aTag == INVALID_TAG) return;
341     builder(aTag)->Generated(anOldShape, aNewShape);
342     buildName(aTag, theName);
343   }
344 }
345
346 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
347                                  const GeomShapePtr& theNewShape,
348                                  const std::string& theName)
349 {
350   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
351   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
352   int aTag = getModificationTag(aNewShape);
353   if (aTag == INVALID_TAG) return;
354   builder(aTag)->Modify(anOldShape, aNewShape);
355   buildName(aTag, theName);
356 }
357
358 void Model_BodyBuilder::deleted(const GeomShapePtr& theOldShape)
359 {
360   TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
361   builder(DELETED_TAG)->Delete(aShape);
362 }
363
364 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
365                                           const GeomShapePtr& theOldShape,
366                                           const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
367                                           const GeomShapePtr& theShapesToExclude)
368 {
369   TopTools_MapOfShape anAlreadyProcessedShapes;
370   GeomShapePtr aResultShape = shape();
371   for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
372        anExp.more();
373        anExp.next())
374   {
375     GeomShapePtr anOldSubShape = anExp.current();
376     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
377     if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
378         || !theAlgo->isDeleted(anOldSubShape)
379         || aResultShape->isSubShape(anOldSubShape, false)
380         || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
381     {
382       continue;
383     }
384
385     ListOfShape aNewShapes;
386     if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
387       theAlgo->modified(anOldSubShape, aNewShapes);
388     }
389
390     if (aNewShapes.size() == 0
391         || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
392       builder(DELETED_TAG)->Delete(anOldSubShape_);
393     }
394   }
395 }
396
397 static void removeBadShapes(ListOfShape& theShapes)
398 {
399   ListOfShape::iterator anIt = theShapes.begin();
400   while (anIt != theShapes.end()) {
401     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
402     bool aSkip = aNewShape.IsNull()
403       || (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
404     if (aSkip) {
405       ListOfShape::iterator aRemoveIt = anIt++;
406       theShapes.erase(aRemoveIt);
407     } else {
408       ++anIt;
409     }
410   }
411 }
412
413 // Keep only the shapes with minimal shape type
414 static void keepTopLevelShapes(ListOfShape& theShapes,
415                                const TopoDS_Shape& theRoot,
416                                const GeomShapePtr& theResultShape = GeomShapePtr())
417 {
418   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
419   ListOfShape::iterator anIt = theShapes.begin();
420   while (anIt != theShapes.end()) {
421     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
422     bool aSkip = aNewShape.IsNull() ||
423       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
424     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
425         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
426       ListOfShape::iterator aRemoveIt = anIt++;
427       theShapes.erase(aRemoveIt);
428     } else {
429       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
430       if (aType < aKeepShapeType) {
431         // found a shape with lesser shape type => remove all previous shapes
432         aKeepShapeType = aType;
433         theShapes.erase(theShapes.begin(), anIt);
434         ++anIt;
435       } else if (aType > aKeepShapeType) {
436         // shapes with greater shape type should be removed from the list
437         ListOfShape::iterator aRemoveIt = anIt++;
438         theShapes.erase(aRemoveIt);
439       } else
440         ++anIt;
441     }
442   }
443 }
444
445 // returns an ancestor shape-type thaty used for naming-definition of the sub-type
446 TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
447   if (theSubType == TopAbs_VERTEX)
448     return TopAbs_EDGE;
449   if (theSubType == TopAbs_EDGE)
450     return TopAbs_FACE;
451   return TopAbs_VERTEX; // bad case
452 }
453
454 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
455                                            const GeomShapePtr& theOldShape,
456                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
457                                            const std::string& theName)
458 {
459   GeomShapePtr aResultShape = shape();
460   GeomShapePtr aShapeToExplore = theOldShape;
461   if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
462     // use optimized set of old shapes for this
463     GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
464                                                       aResultShape,
465                                                       theShapeTypeToExplore);
466     if (aCompound.get()) aShapeToExplore = aCompound;
467   }
468
469   TopTools_MapOfShape anAlreadyProcessedShapes;
470   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
471   for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
472        anOldShapeExp.more();
473        anOldShapeExp.next())
474   {
475     GeomShapePtr anOldSubShape = anOldShapeExp.current();
476     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
477
478     // There is no sense to write history if shape already processed
479     // or old shape does not exist in the document.
480     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
481     bool anOldSubShapeNotInTree = TNaming_Tool::NamedShape(anOldSubShape_, aData->shapeLab())
482                                   .IsNull();
483     if (anOldSubShapeAlreadyProcessed
484         || anOldSubShapeNotInTree)
485     {
486       continue;
487     }
488
489     // Get new shapes.
490     ListOfShape aNewShapes;
491     theAlgo->modified(anOldSubShape, aNewShapes);
492
493     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
494          aNewShapesIt != aNewShapes.cend();
495          ++aNewShapesIt)
496     {
497       GeomShapePtr aNewShape = *aNewShapesIt;
498       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
499       bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
500
501       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
502       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
503       if (aNewShapeIsSameAsOldShape
504           || aNewShapeIsNotInResultShape)
505       {
506         continue;
507       }
508
509       TNaming_Builder* aBuilder;
510       if (aResultShape->isSame(aNewShape)) {
511         // keep the modification evolution on the root level (2241 - history propagation issue)
512         aBuilder = builder(0);
513         TDF_Label aShapeLab = aBuilder->NamedShape()->Label();
514         Handle(TDF_Reference) aRef;
515         if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
516           // Store only in case if it does not have reference.
517           continue;
518         }
519
520         // Check if new shape was already stored.
521         if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
522
523         if (!aBuilder->NamedShape().IsNull() &&
524             ((isGenerated && aBuilder->NamedShape()->Evolution() != TNaming_GENERATED)
525               || (!isGenerated && aBuilder->NamedShape()->Evolution() != TNaming_MODIFY)))
526         {
527           myBuilders.erase(0); // clear old builder to avoid different evolutions crash
528           aBuilder = builder(0);
529         }
530       } else {
531         int aTag = isGenerated ? getGenerationTag(aNewShape_)
532                                : getModificationTag(aNewShape_);
533         aBuilder = builder(aTag);
534
535         // Check if new shape was already stored.
536         if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
537
538         buildName(aTag, theName);
539       }
540
541       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
542                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
543     }
544   }
545 }
546
547 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
548                                             const GeomShapePtr& theOldShape,
549                                             const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
550                                             const std::string& theName)
551 {
552   TopTools_MapOfShape anAlreadyProcessedShapes;
553   for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
554        anOldShapeExp.more();
555        anOldShapeExp.next())
556   {
557     GeomShapePtr anOldSubShape = anOldShapeExp.current();
558     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
559
560     // There is no sense to write history if shape already processed.
561     if (!anAlreadyProcessedShapes.Add(anOldSubShape_)) continue;
562
563     // Get new shapes.
564     ListOfShape aNewShapes;
565     theAlgo->generated(anOldSubShape, aNewShapes);
566
567     keepTopLevelShapes(aNewShapes, anOldSubShape_);
568
569     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
570          aNewShapesIt != aNewShapes.cend();
571          ++aNewShapesIt)
572     {
573       GeomShapePtr aNewShape = *aNewShapesIt;
574       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
575
576       TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
577       if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
578         // TODO: This is a workaround. New shape should be only edge or face.
579         TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
580                                                                             : TopAbs_FACE;
581         int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
582         for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
583           builder(aTag)->Generated(anOldSubShape_, anExp.Current());
584         }
585         buildName(aTag, theName);
586       }
587       else {
588         int aTag = getGenerationTag(aNewShape_);
589         if (aTag == INVALID_TAG) return;
590         builder(aTag)->Generated(anOldSubShape_, aNewShape_);
591         buildName(aTag, theName);
592       }
593     }
594   }
595 }
596
597 //=======================================================================
598 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
599   const TopAbs_ShapeEnum        theGeneratedFrom,
600   TopTools_DataMapOfShapeShape& theDangles)
601 {
602   theDangles.Clear();
603   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
604   TopAbs_ShapeEnum GeneratedTo;
605   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
606   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
607   else return Standard_False;
608   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
609   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
610     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
611     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
612     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
613   }
614   return theDangles.Extent();
615 }
616
617 //=======================================================================
618 void loadGeneratedDangleShapes(
619   const TopoDS_Shape&      theShapeIn,
620   const TopAbs_ShapeEnum   theGeneratedFrom,
621   TNaming_Builder *        theBuilder)
622 {
623   TopTools_DataMapOfShapeShape dangles;
624   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
625   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
626   for (; itr.More(); itr.Next())
627     theBuilder->Generated(itr.Key(), itr.Value());
628 }
629
630 //=======================================================================
631 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
632                                        const std::string& theName)
633 {
634   if(theShape->isNull()) return;
635   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
636   std::string aName;
637   if (aShape.ShapeType() == TopAbs_SOLID) {
638     TopExp_Explorer expl(aShape, TopAbs_FACE);
639     for (; expl.More(); expl.Next()) {
640       builder(myFreePrimitiveTag)->Generated(expl.Current());
641       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
642       aName = theName + "_" + aStr.ToCString();
643       buildName(myFreePrimitiveTag, aName);
644       ++myFreePrimitiveTag;
645     }
646   }
647   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
648     // load faces and all the free edges
649     TopTools_IndexedMapOfShape Faces;
650     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
651     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
652       TopExp_Explorer expl(aShape, TopAbs_FACE);
653       for (; expl.More(); expl.Next()) {
654         builder(myFreePrimitiveTag)->Generated(expl.Current());
655         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
656         aName = theName + "_" + aStr.ToCString();
657         buildName(myFreePrimitiveTag, aName);
658         ++myFreePrimitiveTag;
659       }
660     }
661     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
662     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
663     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
664     {
665       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
666       if (aLL.Extent() < 2) {
667         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
668           continue;
669         builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
670         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
671         aName = theName + "_" + aStr.ToCString();
672         buildName(myFreePrimitiveTag, aName);
673         ++myFreePrimitiveTag;
674       } else {
675         TopTools_ListIteratorOfListOfShape anIter(aLL);
676         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
677         anIter.Next();
678         if(aFace.IsEqual(anIter.Value())) {
679           builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
680           TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
681           aName = theName + "_" + aStr.ToCString();
682           buildName(myFreePrimitiveTag, aName);
683           ++myFreePrimitiveTag;
684         }
685       }
686     }
687   } else if (aShape.ShapeType() == TopAbs_WIRE) {
688     TopTools_IndexedMapOfShape Edges;
689     BRepTools::Map3DEdges(aShape, Edges);
690     if (Edges.Extent() == 1) {
691       builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
692       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
693       for (; expl.More(); expl.Next()) {
694         builder(myFreePrimitiveTag)->Generated(expl.Current());
695         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
696         aName = theName + "_" + aStr.ToCString();
697         buildName(myFreePrimitiveTag, aName);
698         ++myFreePrimitiveTag;
699       }
700     } else {
701       TopExp_Explorer expl(aShape, TopAbs_EDGE);
702       for (; expl.More(); expl.Next()) {
703         builder(myFreePrimitiveTag)->Generated(expl.Current());
704         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
705         aName = theName + "_" + aStr.ToCString();
706         buildName(myFreePrimitiveTag, aName);
707         ++myFreePrimitiveTag;
708       }
709       // and load generated vertices.
710       TopTools_DataMapOfShapeShape generated;
711       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
712       {
713         TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
714         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
715       }
716     }
717   } else if (aShape.ShapeType() == TopAbs_EDGE) {
718     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
719     for (; expl.More(); expl.Next()) {
720       builder(myFreePrimitiveTag)->Generated(expl.Current());
721       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
722       aName = theName + "_" + aStr.ToCString();
723       buildName(myFreePrimitiveTag, aName);
724       ++myFreePrimitiveTag;
725     }
726   }
727 }
728
729 //=======================================================================
730 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
731   TopTools_ListOfShape&   theList)
732 {
733   theList.Clear();
734   // edges -> ancestor faces list
735   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
736   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
737   // keeps the shapes which are already in the resulting list
738   TopTools_MapOfShape alreadyThere;
739   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
740   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
741
742   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
743   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
744     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
745     if (ancestors.Extent() < 2)
746       continue;
747     Standard_Integer anID = 0;
748     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
749       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
750     }
751     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
752       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
753         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
754       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
755       for(; aSameEdge.More(); aSameEdge.Next()) {
756         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
757           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
758         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
759           break;
760
761         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
762         for(; aFaceIter1.More(); aFaceIter1.Next()) {
763           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
764           for(; aFaceIter2.More(); aFaceIter2.Next()) {
765             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
766               break;
767           }
768           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
769             break;
770         }
771         if (!aFaceIter1.More()) { // all the faces are same => put to the result
772           if (alreadyThere.Add(aSameEdge.Value()))
773             theList.Append(aSameEdge.Value());
774           if (alreadyThere.Add(anAncestorsIter.Key()))
775             theList.Append(anAncestorsIter.Key());
776         }
777       }
778     } else { // ID is unique, just add this edge
779       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
780     }
781     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
782   }
783   return theList.Extent();
784 }
785
786 //=======================================================================
787 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
788 {
789   if(theShape->isNull()) return;
790   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
791   std::string aName;
792   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
793     TopoDS_Iterator itr(aShape);
794     for (; itr.More(); itr.Next()) {
795       builder(myFreePrimitiveTag)->Generated(itr.Value());
796       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
797       aName = theName + "_" + aStr.ToCString();
798       buildName(myFreePrimitiveTag, aName);
799       ++myFreePrimitiveTag;
800       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
801         itr.Value().ShapeType() == TopAbs_COMPSOLID)
802       {
803         GeomShapePtr itrShape(new GeomAPI_Shape());
804         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
805         loadFirstLevel(itrShape, theName);
806       } else {
807         GeomShapePtr itrShape(new GeomAPI_Shape());
808         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
809         loadNextLevels(itrShape, theName);
810       }
811     }
812   } else {
813     GeomShapePtr itrShape(new GeomAPI_Shape());
814     itrShape->setImpl(new TopoDS_Shape(aShape));
815     loadNextLevels(itrShape, theName);
816   }
817   TopTools_ListOfShape   aList;
818   if(findAmbiguities(aShape, aList)) {
819     TopTools_ListIteratorOfListOfShape it(aList);
820     for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
821       builder(myFreePrimitiveTag)->Generated(it.Value());
822       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
823       aName = theName + "_" + aStr.ToCString();
824       buildName(myFreePrimitiveTag, aName);
825     }
826   }
827 }
828
829 //=======================================================================
830 void Model_BodyBuilder::loadDisconnectedEdges(GeomShapePtr theShape, const std::string& theName)
831 {
832   if(theShape->isNull()) return;
833   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
834   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
835   TopTools_ListOfShape empty;
836   TopExp_Explorer explF(aShape, TopAbs_FACE);
837   for (; explF.More(); explF.Next()) {
838     const TopoDS_Shape& aFace = explF.Current();
839     TopExp_Explorer explV(aFace, TopAbs_EDGE);
840     for (; explV.More(); explV.Next()) {
841       const TopoDS_Shape& anEdge = explV.Current();
842       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
843       Standard_Boolean faceIsNew = Standard_True;
844       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
845       for (; itrF.More(); itrF.Next()) {
846         if (itrF.Value().IsSame(aFace)) {
847           faceIsNew = Standard_False;
848           break;
849         }
850       }
851       if (faceIsNew)
852         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
853     }
854   }
855
856   TopTools_MapOfShape anEdgesToDelete;
857   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
858   std::string aName;
859   for(;anEx.More();anEx.Next()) {
860     Standard_Boolean aC0 = Standard_False;
861     TopoDS_Shape anEdge1 = anEx.Current();
862     if (edgeNaborFaces.IsBound(anEdge1)) {
863       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
864       if (aList1.Extent()<2) continue;
865       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
866       for (; itr.More(); itr.Next()) {
867         TopoDS_Shape anEdge2 = itr.Key();
868         if(anEdgesToDelete.Contains(anEdge2)) continue;
869         if (anEdge1.IsSame(anEdge2)) continue;
870         const TopTools_ListOfShape& aList2 = itr.Value();
871         // compare lists of the neighbour faces of edge1 and edge2
872         if (aList1.Extent() == aList2.Extent()) {
873           Standard_Integer aMatches = 0;
874           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
875             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
876               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
877           if (aMatches == aList1.Extent()) {
878             aC0=Standard_True;
879             builder(myFreePrimitiveTag)->Generated(anEdge2);
880             anEdgesToDelete.Add(anEdge2);
881             TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
882             aName = theName + "_" + aStr.ToCString();
883             buildName(myFreePrimitiveTag, aName);
884             ++myFreePrimitiveTag;
885           }
886         }
887       }
888       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
889       for(;itDelete.More();itDelete.Next())
890         edgeNaborFaces.UnBind(itDelete.Key());
891       edgeNaborFaces.UnBind(anEdge1);
892     }
893     if (aC0) {
894       builder(myFreePrimitiveTag)->Generated(anEdge1);
895       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
896       aName = theName + "_" + aStr.ToCString();
897       buildName(myFreePrimitiveTag, aName);
898       ++myFreePrimitiveTag;
899     }
900   }
901 }
902
903 void Model_BodyBuilder::loadDisconnectedVertexes(GeomShapePtr theShape,
904                                                  const std::string& theName)
905 {
906   if(theShape->isNull()) return;
907   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
908   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
909   TopTools_ListOfShape empty;
910   TopExp_Explorer explF(aShape, TopAbs_EDGE);
911   for (; explF.More(); explF.Next()) {
912     const TopoDS_Shape& anEdge = explF.Current();
913     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
914     for (; explV.More(); explV.Next()) {
915       const TopoDS_Shape& aVertex = explV.Current();
916       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
917       Standard_Boolean faceIsNew = Standard_True;
918       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
919       for (; itrF.More(); itrF.Next()) {
920         if (itrF.Value().IsSame(anEdge)) {
921           faceIsNew = Standard_False;
922           break;
923         }
924       }
925       if (faceIsNew) {
926         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
927       }
928     }
929   }
930   std::string aName;
931   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
932   for (; itr.More(); itr.Next()) {
933     const TopTools_ListOfShape& naborEdges = itr.Value();
934     if (naborEdges.Extent() < 2) {
935       builder(myFreePrimitiveTag)->Generated(itr.Key());
936       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
937       aName = theName + "_" + aStr.ToCString();
938       buildName(myFreePrimitiveTag, aName);
939       ++myFreePrimitiveTag;
940     }
941   }
942 }
943
944 GeomShapePtr Model_BodyBuilder::shape()
945 {
946   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
947   if (aData && aData->isValid()) {
948     TDF_Label aShapeLab = aData->shapeLab();
949     Handle(TDF_Reference) aRef;
950     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
951       aShapeLab = aRef->Get();
952     }
953     Handle(TNaming_NamedShape) aName;
954     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
955       TopoDS_Shape aShape = aName->Get();
956       if (!aShape.IsNull()) {
957         GeomShapePtr aRes(new GeomAPI_Shape);
958         aRes->setImpl(new TopoDS_Shape(aShape));
959         return aRes;
960       }
961     }
962   }
963   return GeomShapePtr();
964 }
965
966 bool Model_BodyBuilder::isLatestEqual(const GeomShapePtr& theShape)
967 {
968   if (theShape.get()) {
969     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
970     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
971     if (aData) {
972       TDF_Label aShapeLab = aData->shapeLab();
973       Handle(TNaming_NamedShape) aName;
974       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
975         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
976         if (aLatest.IsNull())
977           return false;
978         if (aLatest.IsEqual(aShape))
979           return true;
980         // check sub-shapes for comp-solids:
981         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
982           if (aLatest.IsEqual(anExp.Current()))
983             return true;
984         }
985       }
986     }
987   }
988   return false;
989 }