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