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