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