Salome HOME
Fix for the issue #2753 : error when dump/load script
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
index c17c9b8d56c3ea2cf4870d67825bb84db2679001..212d9d1b4d1f8a0251845ffb2b74d7124ba0a7da 100755 (executable)
 
 #include <Model_Data.h>
 #include <Model_Document.h>
+#include <ModelAPI_Session.h>
 #include <TNaming_Builder.hxx>
 #include <TNaming_NamedShape.hxx>
 #include <TNaming_Iterator.hxx>
 #include <TNaming_Tool.hxx>
+#include <TNaming_SameShapeIterator.hxx>
 #include <TDataStd_Name.hxx>
 #include <TDataStd_Integer.hxx>
+#include <TDataStd_ExtStringList.hxx>
 #include <TopoDS.hxx>
 #include <TopoDS_Face.hxx>
 #include <TDF_ChildIterator.hxx>
 #include <TDF_ChildIDIterator.hxx>
 #include <TDF_Reference.hxx>
+#include <TDF_Tool.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopTools_ListOfShape.hxx>
 #include <Config_PropManager.h>
 // DEB
 //#include <TCollection_AsciiString.hxx>
-//#include <TDF_Tool.hxx>
 //#define DEB_IMPORT 1
 
+/// reference to the shape in external document: sting list attribute identifier
+static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
+
 static const int INVALID_TAG            = -1;
 static const int GENERATED_VERTICES_TAG = 1;
 static const int GENERATED_EDGES_TAG    = 2;
@@ -125,81 +131,8 @@ static bool isAlreadyStored(const TNaming_Builder* theBuilder,
 
 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
 : ModelAPI_BodyBuilder(theOwner),
-  myPrimitiveTag(PRIMITIVES_START_TAG),
-  myDividedIndex(1),
-  myVIndex(1),
-  myEIndex(1),
-  myFIndex(1)
-{
-}
-
-// Converts evolution of naming shape to selection evelution and back to avoid
-// naming support on the disabled results. Deeply in the labels tree, recursively.
-static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
-  std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
-  Handle(TNaming_NamedShape) aName;
-  int anEvolution = -1;
-  if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
-    TNaming_Evolution aNSEvol = aName->Evolution();
-    if ((aNSEvol == TNaming_SELECTED && theFlag) ||
-        (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
-      return;
-    }
-    anEvolution = (int)(aNSEvol);
-    if (!theFlag) {
-      Handle(TDataStd_Integer) anAttrEvol;
-      if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
-        anEvolution = anAttrEvol->Get();
-      }
-    } else {
-      TDataStd_Integer::Set(theLab, anEvolution);
-    }
-
-    for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
-      // iterator goes in reversed order relatively to the Builder, to, make the list reversed
-      aShapePairs.push_front(std::pair<TopoDS_Shape, TopoDS_Shape>
-        (anIter.OldShape(), anIter.NewShape()));
-    }
-
-    // create new
-    TNaming_Builder aBuilder(theLab);
-    TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
-    std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
-    for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
-      if (theFlag) { // disabled => make selection
-        if (anEvolution == TNaming_DELETE) // issue 2274 : don't put too many same null shapes
-          aBuilder.Select(aPairsIter->first, aPairsIter->first);
-        else if (anEvolution == TNaming_PRIMITIVE)
-          aBuilder.Select(aPairsIter->second, aPairsIter->second);
-        else
-          aBuilder.Select(aPairsIter->second, aPairsIter->first);
-      } else if (anEvol == TNaming_GENERATED) {
-        aBuilder.Generated(aPairsIter->first, aPairsIter->second);
-      } else if (anEvol == TNaming_MODIFY) {
-        aBuilder.Modify(aPairsIter->first, aPairsIter->second);
-      } else if (anEvol == TNaming_DELETE) {
-        aBuilder.Delete(aPairsIter->first);
-      } else if (anEvol == TNaming_PRIMITIVE) {
-        aBuilder.Generated(aPairsIter->second);
-      } else if (anEvol == TNaming_SELECTED) {
-        aBuilder.Select(aPairsIter->second, aPairsIter->first);
-      }
-    }
-  }
-  // recursive call for all sub-labels
-  TDF_ChildIterator anIter(theLab, Standard_False);
-  for(; anIter.More(); anIter.Next()) {
-    evolutionToSelectionRec(anIter.Value(), theFlag);
-  }
-}
-
-void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
+  myFreePrimitiveTag(PRIMITIVES_START_TAG)
 {
-  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-  if (!aData || !aData->isValid()) // unknown case
-    return;
-  TDF_Label& aShapeLab = aData->shapeLab();
-  evolutionToSelectionRec(aShapeLab, theFlag);
 }
 
 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
@@ -207,7 +140,7 @@ void Model_BodyBuilder::store(const GeomShapePtr& theShape,
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
   if (aData) {
-    TDF_Label& aShapeLab = aData->shapeLab();
+    TDF_Label aShapeLab = aData->shapeLab();
     // clean builders
     clean();
     // store the new shape as primitive
@@ -220,7 +153,8 @@ void Model_BodyBuilder::store(const GeomShapePtr& theShape,
 
     if(!theIsStoreSameShapes) {
       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
-      if(!aNS.IsNull() && !aNS->IsEmpty()) {
+      // the last condition is for the issue 2751 : existing shape may be found in compound-NS
+      if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
         // This shape is already in document, store reference instead of shape;
         const TDF_Label aFoundLabel = aNS->Label();
         TDF_Reference::Set(aShapeLab, aFoundLabel);
@@ -251,7 +185,7 @@ void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
   if (aData) {
-    TDF_Label& aShapeLab = aData->shapeLab();
+    TDF_Label aShapeLab = aData->shapeLab();
     // clean builders
     clean();
     // store the new shape as primitive
@@ -298,7 +232,6 @@ void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
   if (aData) {
-    TDF_Label& aShapeLab = aData->shapeLab();
     // clean builders
     if (theIsCleanStored) clean();
     // store the new shape as primitive
@@ -348,21 +281,20 @@ void Model_BodyBuilder::clean()
     return;
   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
   for(; aBuilder != myBuilders.end(); aBuilder++) {
+    Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
     delete aBuilder->second;
-    // clear also shapes on cleaned sub-labels (#2241)
-    Handle(TNaming_NamedShape) aNS;
-    if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
-      aNS->Clear();
-    }
+    if (!aNS.IsNull() && !aNS->Label().IsNull())
+      aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
   }
   myBuilders.clear();
+  myPrimitivesNamesIndexMap.clear();
   // remove the old reference (if any)
   aLab.ForgetAttribute(TDF_Reference::GetID());
-  myPrimitiveTag = PRIMITIVES_START_TAG;
-  myDividedIndex = 1;
-  myVIndex = 1;
-  myEIndex = 1;
-  myFIndex = 1;
+  myFreePrimitiveTag = PRIMITIVES_START_TAG;
+  TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
+  for(; anEntriesIter.More(); anEntriesIter.Next()) {
+    anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
+  }
 }
 
 Model_BodyBuilder::~Model_BodyBuilder()
@@ -372,29 +304,55 @@ Model_BodyBuilder::~Model_BodyBuilder()
 
 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
 {
-  std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
   std::string aName = theName;
+  std::string aPrefix = "";
   switch (theTag) {
-    case GENERATED_VERTICES_TAG: aName += aName.empty() ? "Generated_Vertex" : "_GV"; break;
-    case GENERATED_EDGES_TAG:    aName += aName.empty() ? "Generated_Edge"   : "_GE"; break;
-    case GENERATED_FACES_TAG:    aName += aName.empty() ? "Generated_Face"   : "_GF"; break;
-    case MODIFIED_VERTICES_TAG:  aName += aName.empty() ? "Modified_Vertex"  : "_MV"; break;
-    case MODIFIED_EDGES_TAG:     aName += aName.empty() ? "Modified_Edge"    : "_ME"; break;
-    case MODIFIED_FACES_TAG:     aName += aName.empty() ? "Modified_Face"    : "_MF"; break;
+    case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
+    case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
+    case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
+    case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
+    case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
+    case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
   }
+  aName.insert(0, aPrefix);
 
   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
 }
-void Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
-                                  const std::string& theName)
+bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
+                                  const std::string& theName,
+                                  const bool theCheckIsInResult)
 {
+  GeomShapePtr aResultShape = shape();
+  if (theCheckIsInResult) {
+    bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
+    if (aNewShapeIsNotInResultShape) {
+      return false;
+    }
+  }
+
   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
-  builder(myPrimitiveTag)->Generated(aShape);
+  builder(myFreePrimitiveTag)->Generated(aShape);
   if (!theName.empty()) {
-    buildName(myPrimitiveTag, theName);
-  }
+    std::string aName = theName;
+    if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
+      IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
+      aName += "_" + std::to_string(++(anIndexTags.index));
+      anIndexTags.tags.push_back(myFreePrimitiveTag);
+      if (anIndexTags.index == 2) {
+        buildName(anIndexTags.tags.front(), theName + "_1");
+      }
+    }
+    else {
+      IndexTags anIndexTags;
+      anIndexTags.index = 1;
+      anIndexTags.tags.push_back(myFreePrimitiveTag);
+      myPrimitivesNamesIndexMap[theName] = anIndexTags;
+    }
 
-  ++myPrimitiveTag;
+    buildName(myFreePrimitiveTag, aName);
+  }
+  ++myFreePrimitiveTag;
+  return true;
 }
 
 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
@@ -407,12 +365,12 @@ void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
   int aTag;
   if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
     // TODO: This is a workaround. New shape should be only vertex, edge or face.
-    TopAbs_ShapeEnum anExplodeShapeType = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
+    TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
     aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
-    for (TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
+    for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
       builder(aTag)->Generated(anOldShape, anExp.Current());
-      buildName(aTag, theName);
     }
+    buildName(aTag, theName);
   } else {
     aTag = getGenerationTag(aNewShape);
     if (aTag == INVALID_TAG) return;
@@ -489,8 +447,9 @@ static void removeBadShapes(ListOfShape& theShapes)
 }
 
 // Keep only the shapes with minimal shape type
-static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRoot,
-  const GeomShapePtr& theResultShape = GeomShapePtr())
+static void keepTopLevelShapes(ListOfShape& theShapes,
+                               const TopoDS_Shape& theRoot,
+                               const GeomShapePtr& theResultShape = GeomShapePtr())
 {
   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
   ListOfShape::iterator anIt = theShapes.begin();
@@ -519,7 +478,7 @@ static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRo
   }
 }
 
-// returns an ancestor shape-type thaty used for naming-definition of the sub-type
+// returns an ancestor shape-type that used for naming-definition of the sub-type
 TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
   if (theSubType == TopAbs_VERTEX)
     return TopAbs_EDGE;
@@ -528,6 +487,53 @@ TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
   return TopAbs_VERTEX; // bad case
 }
 
+/// Checks that shape is presented in the tree with not-selection evolution
+/// In theOriginalLabel it returns label where NS of old sub-shape is stored
+static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
+  TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
+{
+  bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
+  if (aResult) { //check evolution and a label of this shape
+    for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
+    {
+      static Handle(TNaming_NamedShape) aNS;
+      if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
+        if (aNS->Evolution() != TNaming_SELECTED) {
+          theOriginalLabel = aNS->Label();
+          return true;
+        }
+      }
+    }
+  }
+  if (!theAccess2.IsNull()) {
+    static const TDF_Label anEmpty;
+    return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
+  }
+  return false;
+}
+
+/// Stores entry to the external label in the entries list at this label
+static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
+{
+  // store information about the external document reference to restore old shape on open
+  if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
+    Handle(TDataStd_ExtStringList) anEntries;
+    if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
+      anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
+    }
+    TCollection_AsciiString anEntry;
+    TDF_Tool::Entry(theExternal, anEntry);
+    // check it already contains this entry
+    TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
+    for(; anIter.More(); anIter.Next())
+      if (anIter.Value() == anEntry)
+        break;
+    if (!anIter.More()) {
+      anEntries->Append(anEntry);
+    }
+  }
+}
+
 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
                                            const GeomShapePtr& theOldShape,
                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
@@ -555,11 +561,12 @@ void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
     // There is no sense to write history if shape already processed
     // or old shape does not exist in the document.
     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
-    bool anOldSubShapeNotInTree = TNaming_Tool::NamedShape(anOldSubShape_, aData->shapeLab())
-                                  .IsNull();
-    if (anOldSubShapeAlreadyProcessed
-        || anOldSubShapeNotInTree)
-    {
+    TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
+      ModelAPI_Session::get()->moduleDocument())->generalLabel();
+    TDF_Label anOriginalLabel;
+    bool anOldSubShapeNotInTree =
+      !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
+    if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
       continue;
     }
 
@@ -617,62 +624,80 @@ void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
 
       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
+      // store information about the external document reference to restore old shape on open
+      storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
     }
   }
 }
 
-void Model_BodyBuilder::loadAndOrientGeneratedShapes (
-  GeomAlgoAPI_MakeShape* theMS,
-  GeomShapePtr  theShapeIn,
-  const int  theKindOfShape,
-  const int  theTag,
-  const std::string& theName,
-  GeomAPI_DataMapOfShapeShape& theSubShapes)
+void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
+                                            const GeomShapePtr& theOldShape,
+                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
+                                            const std::string& theName)
 {
-  TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
-  TopTools_MapOfShape aView;
-  bool isBuilt = !theName.empty();
-  TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
-  for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
-    const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
-    if (!aView.Add(aRoot)) continue;
-    //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
-    //  continue; // there is no sense to write history if old shape does not exist in the document
-    ListOfShape aList;
-    GeomShapePtr aRShape(new GeomAPI_Shape());
-    aRShape->setImpl((new TopoDS_Shape(aRoot)));
-    theMS->generated(aRShape, aList);
-    keepTopLevelShapes(aList, aRoot);
-    std::list<GeomShapePtr >::const_iterator
-      anIt = aList.begin(), aLast = aList.end();
-    for (; anIt != aLast; anIt++) {
-      TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
-      if (theSubShapes.isBound(*anIt)) {
-        GeomShapePtr aMapShape(theSubShapes.find(*anIt));
-        aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
-      }
-      if (!aRoot.IsSame (aNewShape)) {
-        builder(theTag)->Generated(aRoot,aNewShape);
-        if(isBuilt)
-          buildName(theTag, theName);
+  GeomShapePtr aResultShape = shape();
+  TopTools_MapOfShape anAlreadyProcessedShapes;
+  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
+  for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
+       anOldShapeExp.more();
+       anOldShapeExp.next())
+  {
+    GeomShapePtr anOldSubShape = anOldShapeExp.current();
+    const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
+
+    // There is no sense to write history if shape already processed
+    // or old shape does not exist in the document.
+    bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
+    TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
+      ModelAPI_Session::get()->moduleDocument())->generalLabel();
+    TDF_Label anOriginalLabel;
+    bool anOldSubShapeNotInTree =
+      !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
+    if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
+      continue;
+    }
+
+    // Get new shapes.
+    ListOfShape aNewShapes;
+    theAlgo->generated(anOldSubShape, aNewShapes);
+
+    keepTopLevelShapes(aNewShapes, anOldSubShape_);
+
+    for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
+         aNewShapesIt != aNewShapes.cend();
+         ++aNewShapesIt)
+    {
+      GeomShapePtr aNewShape = *aNewShapesIt;
+      const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
+
+      bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
+      bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
+      if (aNewShapeIsSameAsOldShape
+        || aNewShapeIsNotInResultShape)
+      {
+        continue;
       }
-      TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
-      if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
-        TopAbs_ShapeEnum anExplodeShapeType =
-          aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
-        const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
-        int aTag = 1;
-        std::shared_ptr<Model_Document> aDoc =
-          std::dynamic_pointer_cast<Model_Document>(document());
-        for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
-          TDF_Label aChildLabel = aLabel.FindChild(aTag);
-          TNaming_Builder aBuilder(aChildLabel);
-          aBuilder.Generated(aRoot, anExp.Current());
-          TCollection_AsciiString aChildName =
-            TCollection_AsciiString((theName + "_").c_str()) + aTag;
-          TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
-          aTag++;
+
+      TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
+      if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
+        // TODO: This is a workaround. New shape should be only edge or face.
+        TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
+                                                                            : TopAbs_FACE;
+        int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
+        for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
+          builder(aTag)->Generated(anOldSubShape_, anExp.Current());
+          // store information about the external document reference to restore old shape on open
+          storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
         }
+        buildName(aTag, theName);
+      }
+      else {
+        int aTag = getGenerationTag(aNewShape_);
+        if (aTag == INVALID_TAG) return;
+        builder(aTag)->Generated(anOldSubShape_, aNewShape_);
+        buildName(aTag, theName);
+        // store information about the external document reference to restore old shape on open
+        storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
       }
     }
   }
@@ -713,7 +738,7 @@ void loadGeneratedDangleShapes(
 
 //=======================================================================
 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
-  const std::string& theName, int&  theTag)
+                                       const std::string& theName)
 {
   if(theShape->isNull()) return;
   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
@@ -721,11 +746,11 @@ void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
   if (aShape.ShapeType() == TopAbs_SOLID) {
     TopExp_Explorer expl(aShape, TopAbs_FACE);
     for (; expl.More(); expl.Next()) {
-      builder(theTag)->Generated(expl.Current());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(expl.Current());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
     }
   }
   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
@@ -735,11 +760,11 @@ void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
       TopExp_Explorer expl(aShape, TopAbs_FACE);
       for (; expl.More(); expl.Next()) {
-        builder(theTag)->Generated(expl.Current());
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(expl.Current());
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       }
     }
     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
@@ -750,21 +775,21 @@ void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
       if (aLL.Extent() < 2) {
         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
           continue;
-        builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       } else {
         TopTools_ListIteratorOfListOfShape anIter(aLL);
         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
         anIter.Next();
         if(aFace.IsEqual(anIter.Value())) {
-          builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
-          TCollection_AsciiString aStr(theTag);
-          aName = theName + aStr.ToCString();
-          buildName(theTag, aName);
-          theTag++;
+          builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
+          TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+          aName = theName + "_" + aStr.ToCString();
+          buildName(myFreePrimitiveTag, aName);
+          ++myFreePrimitiveTag;
         }
       }
     }
@@ -772,40 +797,40 @@ void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
     TopTools_IndexedMapOfShape Edges;
     BRepTools::Map3DEdges(aShape, Edges);
     if (Edges.Extent() == 1) {
-      builder(theTag++)->Generated(Edges.FindKey(1));
+      builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
       for (; expl.More(); expl.Next()) {
-        builder(theTag)->Generated(expl.Current());
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(expl.Current());
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       }
     } else {
       TopExp_Explorer expl(aShape, TopAbs_EDGE);
       for (; expl.More(); expl.Next()) {
-        builder(theTag)->Generated(expl.Current());
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(expl.Current());
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       }
       // and load generated vertices.
       TopTools_DataMapOfShapeShape generated;
       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
       {
-        TNaming_Builder* pBuilder = builder(theTag++);
+        TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
       }
     }
   } else if (aShape.ShapeType() == TopAbs_EDGE) {
     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
     for (; expl.More(); expl.Next()) {
-      builder(theTag)->Generated(expl.Current());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(expl.Current());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
     }
   }
 }
@@ -868,8 +893,7 @@ int findAmbiguities(const TopoDS_Shape&           theShapeIn,
 }
 
 //=======================================================================
-void Model_BodyBuilder::loadFirstLevel(
-  GeomShapePtr theShape, const std::string& theName, int&  theTag)
+void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
 {
   if(theShape->isNull()) return;
   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
@@ -877,44 +901,42 @@ void Model_BodyBuilder::loadFirstLevel(
   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
     TopoDS_Iterator itr(aShape);
     for (; itr.More(); itr.Next()) {
-      builder(theTag)->Generated(itr.Value());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      if(!theName.empty()) buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(itr.Value());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
         itr.Value().ShapeType() == TopAbs_COMPSOLID)
       {
         GeomShapePtr itrShape(new GeomAPI_Shape());
         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
-        loadFirstLevel(itrShape, theName, theTag);
+        loadFirstLevel(itrShape, theName);
       } else {
         GeomShapePtr itrShape(new GeomAPI_Shape());
         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
-        loadNextLevels(itrShape, theName, theTag);
+        loadNextLevels(itrShape, theName);
       }
     }
   } else {
     GeomShapePtr itrShape(new GeomAPI_Shape());
     itrShape->setImpl(new TopoDS_Shape(aShape));
-    loadNextLevels(itrShape, theName, theTag);
+    loadNextLevels(itrShape, theName);
   }
   TopTools_ListOfShape   aList;
   if(findAmbiguities(aShape, aList)) {
     TopTools_ListIteratorOfListOfShape it(aList);
-    for (; it.More(); it.Next(),theTag++) {
-      builder(theTag)->Generated(it.Value());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
+    for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
+      builder(myFreePrimitiveTag)->Generated(it.Value());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
     }
   }
 }
 
 //=======================================================================
-void Model_BodyBuilder::loadDisconnectedEdges(
-  GeomShapePtr theShape, const std::string& theName, int&  theTag)
+void Model_BodyBuilder::loadDisconnectedEdges(GeomShapePtr theShape, const std::string& theName)
 {
   if(theShape->isNull()) return;
   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
@@ -955,7 +977,7 @@ void Model_BodyBuilder::loadDisconnectedEdges(
         if(anEdgesToDelete.Contains(anEdge2)) continue;
         if (anEdge1.IsSame(anEdge2)) continue;
         const TopTools_ListOfShape& aList2 = itr.Value();
-        // compare lists of the neighbour faces of edge1 and edge2
+        // compare lists of the neighbor faces of edge1 and edge2
         if (aList1.Extent() == aList2.Extent()) {
           Standard_Integer aMatches = 0;
           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
@@ -963,12 +985,12 @@ void Model_BodyBuilder::loadDisconnectedEdges(
               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
           if (aMatches == aList1.Extent()) {
             aC0=Standard_True;
-            builder(theTag)->Generated(anEdge2);
+            builder(myFreePrimitiveTag)->Generated(anEdge2);
             anEdgesToDelete.Add(anEdge2);
-            TCollection_AsciiString aStr(theTag);
-            aName = theName + aStr.ToCString();
-            buildName(theTag, aName);
-            theTag++;
+            TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+            aName = theName + "_" + aStr.ToCString();
+            buildName(myFreePrimitiveTag, aName);
+            ++myFreePrimitiveTag;
           }
         }
       }
@@ -978,17 +1000,17 @@ void Model_BodyBuilder::loadDisconnectedEdges(
       edgeNaborFaces.UnBind(anEdge1);
     }
     if (aC0) {
-      builder(theTag)->Generated(anEdge1);
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(anEdge1);
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
     }
   }
 }
 
 void Model_BodyBuilder::loadDisconnectedVertexes(GeomShapePtr theShape,
-                                                 const std::string& theName, int&  theTag)
+                                                 const std::string& theName)
 {
   if(theShape->isNull()) return;
   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
@@ -1019,11 +1041,11 @@ void Model_BodyBuilder::loadDisconnectedVertexes(GeomShapePtr theShape,
   for (; itr.More(); itr.Next()) {
     const TopTools_ListOfShape& naborEdges = itr.Value();
     if (naborEdges.Extent() < 2) {
-      builder(theTag)->Generated(itr.Key());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(itr.Key());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
     }
   }
 }
@@ -1056,7 +1078,7 @@ bool Model_BodyBuilder::isLatestEqual(const GeomShapePtr& theShape)
     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
     if (aData) {
-      TDF_Label& aShapeLab = aData->shapeLab();
+      TDF_Label aShapeLab = aData->shapeLab();
       Handle(TNaming_NamedShape) aName;
       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);