1 // Copyright (C) 2014-2019 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include <Model_BodyBuilder.h>
22 #include <Model_Data.h>
23 #include <Model_Document.h>
24 #include <ModelAPI_Session.h>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Iterator.hxx>
28 #include <TNaming_Tool.hxx>
29 #include <TNaming_SameShapeIterator.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_ExtStringList.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TDF_ChildIterator.hxx>
36 #include <TDF_ChildIDIterator.hxx>
37 #include <TDF_Reference.hxx>
38 #include <TDF_Tool.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_DataMapOfShapeListOfShape.hxx>
44 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
46 #include <TopTools_MapIteratorOfMapOfShape.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_IndexedMapOfShape.hxx>
49 #include <TopTools_DataMapOfShapeShape.hxx>
51 #include <BRepTools.hxx>
52 #include <BRep_Tool.hxx>
53 #include <BRepTools_History.hxx>
54 #include <GeomAPI_Shape.h>
55 #include <GeomAPI_ShapeExplorer.h>
56 #include <GeomAlgoAPI_MakeShape.h>
57 #include <GeomAlgoAPI_SortListOfShapes.h>
58 #include <Config_PropManager.h>
60 //#include <TCollection_AsciiString.hxx>
61 //#define DEB_IMPORT 1
63 /// reference to the shape in external document: sting list attribute identifier
64 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
66 static const int INVALID_TAG = -1;
67 static const int GENERATED_VERTICES_TAG = 1;
68 static const int GENERATED_EDGES_TAG = 2;
69 static const int GENERATED_FACES_TAG = 3;
70 static const int MODIFIED_VERTICES_TAG = 4;
71 static const int MODIFIED_EDGES_TAG = 5;
72 static const int MODIFIED_FACES_TAG = 6;
73 static const int DELETED_TAG = 7;
74 static const int PRIMITIVES_START_TAG = 11;
76 static int getGenerationTag(const TopoDS_Shape& theShape) {
77 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
79 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
80 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
81 case TopAbs_FACE: return GENERATED_FACES_TAG;
87 static int getModificationTag(const TopoDS_Shape& theShape) {
88 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
90 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
91 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
92 case TopAbs_FACE: return MODIFIED_FACES_TAG;
98 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
99 const TopoDS_Shape& theOldShape,
100 const TopoDS_Shape& theNewShape)
102 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
106 if (aNamingIt.NewShape().IsSame(theNewShape)
107 && aNamingIt.OldShape().IsSame(theOldShape))
116 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
117 : ModelAPI_BodyBuilder(theOwner),
118 myFreePrimitiveTag(PRIMITIVES_START_TAG)
122 /// Checks that shape is presented in the tree with not-selection evolution
123 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
124 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
125 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
127 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
128 if (aResult) { //check evolution and a label of this shape
129 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
131 static Handle(TNaming_NamedShape) aNS;
132 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
133 if (aNS->Evolution() != TNaming_SELECTED) {
134 theOriginalLabel = aNS->Label();
140 if (!theAccess2.IsNull()) {
141 static const TDF_Label anEmpty;
142 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
147 /// Stores entry to the external label in the entries list at this label
148 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
150 // store information about the external document reference to restore old shape on open
151 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
152 Handle(TDataStd_ExtStringList) anEntries;
153 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
154 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
156 TCollection_AsciiString anEntry;
157 TDF_Tool::Entry(theExternal, anEntry);
158 // check it already contains this entry
159 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
160 for(; anIter.More(); anIter.Next())
161 if (anIter.Value() == anEntry)
163 if (!anIter.More()) {
164 anEntries->Append(anEntry);
169 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
170 const bool theIsStoreSameShapes)
172 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
174 TDF_Label aShapeLab = aData->shapeLab();
177 // store the new shape as primitive
178 TNaming_Builder aBuilder(aShapeLab);
181 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
183 return; // null shape inside
185 if(!theIsStoreSameShapes) {
186 Handle(TNaming_NamedShape) aNS;
187 if (TNaming_Tool::HasLabel(aShapeLab, aShape))
188 aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
189 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
190 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
191 // This shape is already in document, store reference instead of shape;
192 const TDF_Label aFoundLabel = aNS->Label();
193 TDF_Reference::Set(aShapeLab, aFoundLabel);
194 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
199 aBuilder.Generated(aShape);
201 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
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());
207 std::shared_ptr<Model_Document> aDoc =
208 std::dynamic_pointer_cast<Model_Document>(document());
209 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
216 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
217 const GeomShapePtr& theToShape, const bool theIsCleanStored)
219 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
221 TDF_Label aShapeLab = aData->shapeLab();
223 if (theIsCleanStored)
225 TNaming_Builder* aBuilder = builder(0);
226 if (!theFromShape || !theToShape)
228 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
229 if (aShapeBasis.IsNull())
230 return; // null shape inside
231 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
232 if (aShapeNew.IsNull())
233 return; // null shape inside
235 // There is no sense to write history if old shape does not exist in the document.
236 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
237 ModelAPI_Session::get()->moduleDocument())->generalLabel();
238 TDF_Label anOriginalLabel;
239 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
240 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
241 aBuilder->Generated(aShapeNew);
244 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
246 aBuilder = builder(0);
249 aBuilder->Generated(aShapeBasis, aShapeNew);
250 // store information about the external document reference to restore old shape on open
251 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
255 if(!aBuilder->NamedShape()->IsEmpty()) {
256 Handle(TDataStd_Name) anAttr;
257 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
258 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
260 std::shared_ptr<Model_Document> aDoc =
261 std::dynamic_pointer_cast<Model_Document>(document());
262 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
269 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
270 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
272 bool aStored = false;
273 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
274 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
275 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
277 ListOfShape aNews; // check this old really generates theToShape
278 theMakeShape->generated(*anOldIter, aNews);
279 ListOfShape::iterator aNewIter = aNews.begin();
280 for (; aNewIter != aNews.end(); aNewIter++) {
281 if (theToShape->isSame(*aNewIter))
284 aStore = aNewIter != aNews.end();
287 storeGenerated(*anOldIter, theToShape, !aStored);
288 TNaming_Builder* aBuilder = builder(0);
289 aStored = !aBuilder->NamedShape()->IsEmpty();
292 if (!aStored) { // store as PRIMITIVE, but clean in any way
298 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
300 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
301 if (aFind == myBuilders.end()) {
302 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
303 myBuilders[theTag] = new TNaming_Builder(
304 theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
305 aFind = myBuilders.find(theTag);
307 return aFind->second;
310 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
311 const GeomShapePtr& theNewShape,
312 const bool theIsCleanStored)
314 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
317 if (theIsCleanStored) clean();
318 TNaming_Builder* aBuilder = builder(0);
319 if (!theOldShape || !theNewShape)
321 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
322 if (aShapeOld.IsNull())
323 return; // null shape inside
324 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
325 if (aShapeNew.IsNull())
326 return; // null shape inside
328 // There is no sense to write history if old shape does not exist in the document.
329 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
330 ModelAPI_Session::get()->moduleDocument())->generalLabel();
331 TDF_Label anOriginalLabel;
332 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
333 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
334 aBuilder->Generated(aShapeNew);
337 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
339 aBuilder = builder(0);
342 aBuilder->Modify(aShapeOld, aShapeNew);
343 // store information about the external document reference to restore old shape on open
344 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
347 if(!aBuilder->NamedShape()->IsEmpty()) {
348 Handle(TDataStd_Name) anAttr;
349 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
350 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
352 std::shared_ptr<Model_Document> aDoc =
353 std::dynamic_pointer_cast<Model_Document>(document());
354 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
361 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
362 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
364 bool aStored = false;
365 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
366 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
367 // compounds may cause crash if call "modified"
368 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
370 ListOfShape aNews; // check this old really modifies theNewShape
371 theMakeShape->modified(*anOldIter, aNews);
372 ListOfShape::iterator aNewIter = aNews.begin();
373 for(; aNewIter != aNews.end(); aNewIter++) {
374 if (theNewShape->isSame(*aNewIter))
377 aStore = aNewIter != aNews.end();
380 storeModified(*anOldIter, theNewShape, !aStored);
381 TNaming_Builder* aBuilder = builder(0);
382 aStored = !aBuilder->NamedShape()->IsEmpty();
386 // check the new shape is already in the tree, so, no need to store primitive, just reference
387 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
389 TDF_Label aShapeLab = aData->shapeLab();
390 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
391 Handle(TNaming_NamedShape) aNS;
392 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
393 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
394 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
395 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
396 // This shape is already in document, store reference instead of shape;
397 const TDF_Label aFoundLabel = aNS->Label();
398 TDF_Reference::Set(aShapeLab, aFoundLabel);
400 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
404 store(theNewShape); // store as PRIMITIVE, but clean in any way
409 void Model_BodyBuilder::clean()
411 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
414 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
415 for(; aBuilder != myBuilders.end(); aBuilder++) {
416 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
417 delete aBuilder->second;
418 if (!aNS.IsNull() && !aNS->Label().IsNull())
419 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
422 myPrimitivesNamesIndexMap.clear();
423 // remove the old reference (if any)
424 aLab.ForgetAttribute(TDF_Reference::GetID());
425 myFreePrimitiveTag = PRIMITIVES_START_TAG;
426 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
427 for(; anEntriesIter.More(); anEntriesIter.Next()) {
428 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
432 void Model_BodyBuilder::cleanCash()
434 myPrimitivesNamesIndexMap.clear();
437 Model_BodyBuilder::~Model_BodyBuilder()
442 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
444 std::string aName = theName;
445 std::string aPrefix = "";
447 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
448 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
449 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
450 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
451 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
452 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
454 aName.insert(0, aPrefix);
456 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
458 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
459 const std::string& theName,
460 const bool theCheckIsInResult)
462 GeomShapePtr aResultShape = shape();
463 if (theCheckIsInResult) {
464 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
465 if (aNewShapeIsNotInResultShape) {
470 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
471 builder(myFreePrimitiveTag)->Generated(aShape);
472 if (!theName.empty()) {
473 std::string aName = theName;
474 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
475 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
476 aName += "_" + std::to_string(++(anIndexTags.index));
477 anIndexTags.tags.push_back(myFreePrimitiveTag);
478 if (anIndexTags.index == 2) {
479 buildName(anIndexTags.tags.front(), theName + "_1");
483 IndexTags anIndexTags;
484 anIndexTags.index = 1;
485 anIndexTags.tags.push_back(myFreePrimitiveTag);
486 myPrimitivesNamesIndexMap[theName] = anIndexTags;
489 buildName(myFreePrimitiveTag, aName);
491 ++myFreePrimitiveTag;
495 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
496 const GeomShapePtr& theNewShape,
497 const std::string& theName)
499 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
500 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
501 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
503 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
504 // TODO: This is a workaround. New shape should be only vertex, edge or face.
505 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
506 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
507 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
508 builder(aTag)->Generated(anOldShape, anExp.Current());
510 buildName(aTag, theName);
512 aTag = getGenerationTag(aNewShape);
513 if (aTag == INVALID_TAG) return;
514 builder(aTag)->Generated(anOldShape, aNewShape);
515 buildName(aTag, theName);
519 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
520 const GeomShapePtr& theNewShape,
521 const std::string& theName)
523 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
524 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
525 int aTag = getModificationTag(aNewShape);
526 if (aTag == INVALID_TAG) return;
527 builder(aTag)->Modify(anOldShape, aNewShape);
528 buildName(aTag, theName);
531 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
532 const GeomShapePtr& theOldShape,
533 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
534 const GeomShapePtr& theShapesToExclude)
536 TopTools_MapOfShape anAlreadyProcessedShapes;
537 GeomShapePtr aResultShape = shape();
538 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
542 GeomShapePtr anOldSubShape = anExp.current();
543 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
544 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
545 || !theAlgo->isDeleted(anOldSubShape)
546 || aResultShape->isSubShape(anOldSubShape, false)
547 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
552 ListOfShape aNewShapes;
553 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
554 theAlgo->modified(anOldSubShape, aNewShapes);
557 if (aNewShapes.size() == 0
558 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
559 builder(DELETED_TAG)->Delete(anOldSubShape_);
564 // Keep only the shapes with minimal shape type
565 static void keepTopLevelShapes(ListOfShape& theShapes,
566 const TopoDS_Shape& theRoot,
567 const GeomShapePtr& theResultShape = GeomShapePtr())
569 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
570 ListOfShape::iterator anIt = theShapes.begin();
571 while (anIt != theShapes.end()) {
572 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
573 bool aSkip = aNewShape.IsNull() ||
574 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
575 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
576 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
577 ListOfShape::iterator aRemoveIt = anIt++;
578 theShapes.erase(aRemoveIt);
580 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
581 if (aType < aKeepShapeType) {
582 // found a shape with lesser shape type => remove all previous shapes
583 aKeepShapeType = aType;
584 theShapes.erase(theShapes.begin(), anIt);
586 } else if (aType > aKeepShapeType) {
587 // shapes with greater shape type should be removed from the list
588 ListOfShape::iterator aRemoveIt = anIt++;
589 theShapes.erase(aRemoveIt);
596 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
597 const GeomShapePtr& theOldShape,
598 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
599 const std::string& theName)
601 GeomShapePtr aResultShape = shape();
602 GeomShapePtr aShapeToExplore = theOldShape;
603 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
604 // use optimized set of old shapes for this
605 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
607 theShapeTypeToExplore);
608 if (aCompound.get()) aShapeToExplore = aCompound;
611 TopTools_MapOfShape anAlreadyProcessedShapes;
612 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
613 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
614 anOldShapeExp.more();
615 anOldShapeExp.next())
617 GeomShapePtr anOldSubShape = anOldShapeExp.current();
618 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
620 // There is no sense to write history if shape already processed
621 // or old shape does not exist in the document.
622 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
623 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
624 ModelAPI_Session::get()->moduleDocument())->generalLabel();
625 TDF_Label anOriginalLabel;
626 bool anOldSubShapeNotInTree =
627 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
628 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
633 ListOfShape aNewShapes;
634 theAlgo->modified(anOldSubShape, aNewShapes);
636 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
637 aNewShapesIt != aNewShapes.cend();
640 GeomShapePtr aNewShape = *aNewShapesIt;
641 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
642 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
644 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
645 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
646 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
649 if (aResultShape->isSame(aNewShape))
650 continue; // it is stored on the root level (2241 - history propagation issue)
652 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
653 TNaming_Builder*aBuilder = builder(aTag);
654 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
655 continue; // new shape was already stored.
657 buildName(aTag, theName);
658 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
659 : aBuilder->Modify(anOldSubShape_, aNewShape_);
660 // store information about the external document reference to restore old shape on open
661 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
666 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
667 const GeomShapePtr& theOldShape,
668 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
669 const std::string& theName,
670 const bool theSaveOldIfNotInTree)
672 GeomShapePtr aResultShape = shape();
673 TopTools_MapOfShape anAlreadyProcessedShapes;
674 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
675 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
676 anOldShapeExp.more();
677 anOldShapeExp.next())
679 GeomShapePtr anOldSubShape = anOldShapeExp.current();
680 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
682 // There is no sense to write history if shape already processed
683 // or old shape does not exist in the document.
684 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
685 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
686 ModelAPI_Session::get()->moduleDocument())->generalLabel();
687 TDF_Label anOriginalLabel;
688 bool anOldSubShapeNotInTree =
689 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
690 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
691 if (theSaveOldIfNotInTree) {
692 std::string aSelectionName = theName + "Selected";
693 generated(anOldSubShape, aSelectionName, false);
699 ListOfShape aNewShapes;
700 theAlgo->generated(anOldSubShape, aNewShapes);
702 keepTopLevelShapes(aNewShapes, anOldSubShape_);
704 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
705 aNewShapesIt != aNewShapes.cend();
708 GeomShapePtr aNewShape = *aNewShapesIt;
709 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
711 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
712 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
713 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
717 if (aResultShape->isSame(aNewShape))
718 continue; // it is stored on the root level
720 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
721 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
722 // TODO: This is a workaround. New shape should be only edge or face.
723 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
725 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
726 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
727 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
728 // store information about the external document reference to restore old shape on open
729 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
731 buildName(aTag, theName);
733 int aTag = getGenerationTag(aNewShape_);
734 if (aTag == INVALID_TAG) return;
735 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
736 buildName(aTag, theName);
737 // store information about the external document reference to restore old shape on open
738 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
745 //=======================================================================
746 int getDangleShapes(const TopoDS_Shape& theShapeIn,
747 const TopAbs_ShapeEnum theGeneratedFrom,
748 TopTools_DataMapOfShapeShape& theDangles)
751 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
752 TopAbs_ShapeEnum GeneratedTo;
753 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
754 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
755 else return Standard_False;
756 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
757 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
758 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
759 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
760 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
762 return theDangles.Extent();
765 //=======================================================================
766 void loadGeneratedDangleShapes(
767 const TopoDS_Shape& theShapeIn,
768 const TopAbs_ShapeEnum theGeneratedFrom,
769 TNaming_Builder * theBuilder)
771 TopTools_DataMapOfShapeShape dangles;
772 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
773 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
774 for (; itr.More(); itr.Next())
775 theBuilder->Generated(itr.Key(), itr.Value());
779 //=======================================================================
780 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
781 const std::string& theName)
783 if(theShape->isNull()) return;
784 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
786 if (aShape.ShapeType() == TopAbs_SOLID) {
787 TopExp_Explorer expl(aShape, TopAbs_FACE);
788 for (; expl.More(); expl.Next()) {
789 builder(myFreePrimitiveTag)->Generated(expl.Current());
790 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
791 aName = theName + "_" + aStr.ToCString();
792 buildName(myFreePrimitiveTag, aName);
793 ++myFreePrimitiveTag;
796 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
797 // load faces and all the free edges
798 TopTools_IndexedMapOfShape Faces;
799 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
800 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
801 TopExp_Explorer expl(aShape, TopAbs_FACE);
802 for (; expl.More(); expl.Next()) {
803 builder(myFreePrimitiveTag)->Generated(expl.Current());
804 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
805 aName = theName + "_" + aStr.ToCString();
806 buildName(myFreePrimitiveTag, aName);
807 ++myFreePrimitiveTag;
810 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
811 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
812 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
814 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
815 if (aLL.Extent() < 2) {
816 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
818 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
819 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
820 aName = theName + "_" + aStr.ToCString();
821 buildName(myFreePrimitiveTag, aName);
822 ++myFreePrimitiveTag;
824 TopTools_ListIteratorOfListOfShape anIter(aLL);
825 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
827 if(aFace.IsEqual(anIter.Value())) {
828 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
829 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
830 aName = theName + "_" + aStr.ToCString();
831 buildName(myFreePrimitiveTag, aName);
832 ++myFreePrimitiveTag;
836 } else if (aShape.ShapeType() == TopAbs_WIRE) {
837 TopTools_IndexedMapOfShape Edges;
838 BRepTools::Map3DEdges(aShape, Edges);
839 if (Edges.Extent() == 1) {
840 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
841 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
842 for (; expl.More(); expl.Next()) {
843 builder(myFreePrimitiveTag)->Generated(expl.Current());
844 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
845 aName = theName + "_" + aStr.ToCString();
846 buildName(myFreePrimitiveTag, aName);
847 ++myFreePrimitiveTag;
850 TopExp_Explorer expl(aShape, TopAbs_EDGE);
851 for (; expl.More(); expl.Next()) {
852 builder(myFreePrimitiveTag)->Generated(expl.Current());
853 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
854 aName = theName + "_" + aStr.ToCString();
855 buildName(myFreePrimitiveTag, aName);
856 ++myFreePrimitiveTag;
858 // and load generated vertices.
859 TopTools_DataMapOfShapeShape generated;
860 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
862 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
863 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
866 } else if (aShape.ShapeType() == TopAbs_EDGE) {
867 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
868 for (; expl.More(); expl.Next()) {
869 builder(myFreePrimitiveTag)->Generated(expl.Current());
870 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
871 aName = theName + "_" + aStr.ToCString();
872 buildName(myFreePrimitiveTag, aName);
873 ++myFreePrimitiveTag;
878 //=======================================================================
879 int findAmbiguities(const TopoDS_Shape& theShapeIn,
880 TopTools_ListOfShape& theList)
883 // edges -> ancestor faces list
884 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
885 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
886 // keeps the shapes which are already in the resulting list
887 TopTools_MapOfShape alreadyThere;
888 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
889 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
891 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
892 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
893 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
894 if (ancestors.Extent() < 2)
896 Standard_Integer anID = 0;
897 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
898 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
900 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
901 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
902 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
903 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
904 for(; aSameEdge.More(); aSameEdge.Next()) {
905 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
906 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
907 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
910 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
911 for(; aFaceIter1.More(); aFaceIter1.Next()) {
912 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
913 for(; aFaceIter2.More(); aFaceIter2.Next()) {
914 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
917 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
920 if (!aFaceIter1.More()) { // all the faces are same => put to the result
921 if (alreadyThere.Add(aSameEdge.Value()))
922 theList.Append(aSameEdge.Value());
923 if (alreadyThere.Add(anAncestorsIter.Key()))
924 theList.Append(anAncestorsIter.Key());
927 } else { // ID is unique, just add this edge
928 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
930 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
932 return theList.Extent();
935 //=======================================================================
936 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
938 if(theShape->isNull()) return;
939 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
941 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
942 TopoDS_Iterator itr(aShape);
943 for (; itr.More(); itr.Next()) {
944 builder(myFreePrimitiveTag)->Generated(itr.Value());
945 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
946 aName = theName + "_" + aStr.ToCString();
947 buildName(myFreePrimitiveTag, aName);
948 ++myFreePrimitiveTag;
949 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
950 itr.Value().ShapeType() == TopAbs_COMPSOLID)
952 GeomShapePtr itrShape(new GeomAPI_Shape());
953 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
954 loadFirstLevel(itrShape, theName);
956 GeomShapePtr itrShape(new GeomAPI_Shape());
957 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
958 loadNextLevels(itrShape, theName);
962 GeomShapePtr itrShape(new GeomAPI_Shape());
963 itrShape->setImpl(new TopoDS_Shape(aShape));
964 loadNextLevels(itrShape, theName);
966 TopTools_ListOfShape aList;
967 if(findAmbiguities(aShape, aList)) {
968 TopTools_ListIteratorOfListOfShape it(aList);
969 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
970 builder(myFreePrimitiveTag)->Generated(it.Value());
971 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
972 aName = theName + "_" + aStr.ToCString();
973 buildName(myFreePrimitiveTag, aName);
978 GeomShapePtr Model_BodyBuilder::shape()
980 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
981 if (aData && aData->isValid()) {
982 TDF_Label aShapeLab = aData->shapeLab();
983 Handle(TDF_Reference) aRef;
984 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
985 aShapeLab = aRef->Get();
987 Handle(TNaming_NamedShape) aName;
988 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
989 TopoDS_Shape aShape = aName->Get();
990 if (!aShape.IsNull()) {
991 GeomShapePtr aRes(new GeomAPI_Shape);
992 aRes->setImpl(new TopoDS_Shape(aShape));
997 return GeomShapePtr();