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