1 // Copyright (C) 2014-2024 CEA, EDF
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 <Basics_OCCTVersion.hxx>
24 #include <Locale_Convert.h>
26 #include <Model_Data.h>
27 #include <Model_Document.h>
28 #include <ModelAPI_Session.h>
29 #include <TNaming_Builder.hxx>
30 #include <TNaming_NamedShape.hxx>
31 #include <TNaming_Iterator.hxx>
32 #include <TNaming_Tool.hxx>
33 #include <TNaming_SameShapeIterator.hxx>
34 #include <TDataStd_Name.hxx>
35 #include <TDataStd_Integer.hxx>
36 #include <TDataStd_ExtStringList.hxx>
38 #include <TopoDS_Face.hxx>
39 #include <TDF_ChildIterator.hxx>
40 #include <TDF_ChildIDIterator.hxx>
41 #include <TDF_Reference.hxx>
42 #include <TDF_Tool.hxx>
43 #include <TopTools_MapOfShape.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <TopTools_ListOfShape.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopTools_DataMapOfShapeListOfShape.hxx>
48 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
49 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
50 #include <TopTools_MapIteratorOfMapOfShape.hxx>
51 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
52 #include <TopTools_IndexedMapOfShape.hxx>
53 #include <TopTools_DataMapOfShapeShape.hxx>
55 #include <BRepTools.hxx>
56 #include <BRep_Tool.hxx>
57 #include <BRepTools_History.hxx>
58 #include <GeomAPI_Shape.h>
59 #include <GeomAPI_ShapeExplorer.h>
60 #include <GeomAlgoAPI_MakeShape.h>
61 #include <GeomAlgoAPI_SortListOfShapes.h>
62 #include <Config_PropManager.h>
64 //#include <TCollection_AsciiString.hxx>
65 //#define DEB_IMPORT 1
67 /// reference to the shape in external document: sting list attribute identifier
68 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
70 static const int INVALID_TAG = -1;
71 static const int GENERATED_VERTICES_TAG = 1;
72 static const int GENERATED_EDGES_TAG = 2;
73 static const int GENERATED_FACES_TAG = 3;
74 static const int MODIFIED_VERTICES_TAG = 4;
75 static const int MODIFIED_EDGES_TAG = 5;
76 static const int MODIFIED_FACES_TAG = 6;
77 static const int DELETED_TAG = 7;
78 static const int PRIMITIVES_START_TAG = 11;
80 static int getGenerationTag(const TopoDS_Shape& theShape) {
81 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
83 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
84 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
85 case TopAbs_FACE: return GENERATED_FACES_TAG;
86 default: break; // [to avoid compilation warning]
92 static int getModificationTag(const TopoDS_Shape& theShape) {
93 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
95 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
96 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
97 case TopAbs_FACE: return MODIFIED_FACES_TAG;
98 default: break; // [to avoid compilation warning]
104 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
105 const TopoDS_Shape& theOldShape,
106 const TopoDS_Shape& theNewShape)
108 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
112 if (aNamingIt.NewShape().IsSame(theNewShape)
113 && aNamingIt.OldShape().IsSame(theOldShape))
122 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
123 : ModelAPI_BodyBuilder(theOwner),
124 myFreePrimitiveTag(PRIMITIVES_START_TAG)
128 /// Checks that shape is presented in the tree with not-selection evolution
129 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
130 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
131 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
133 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
134 if (aResult) { //check evolution and a label of this shape
135 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
137 Handle(TNaming_NamedShape) aNS;
138 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
139 if (aNS->Evolution() != TNaming_SELECTED) {
140 theOriginalLabel = aNS->Label();
146 if (!theAccess2.IsNull()) {
147 static const TDF_Label anEmpty;
148 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
153 /// Stores entry to the external label in the entries list at this label
154 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
156 // store information about the external document reference to restore old shape on open
157 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
158 Handle(TDataStd_ExtStringList) anEntries;
159 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
160 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
162 TCollection_AsciiString anEntry;
163 TDF_Tool::Entry(theExternal, anEntry);
164 // check it already contains this entry
165 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
166 for(; anIter.More(); anIter.Next())
167 if (anIter.Value() == anEntry)
169 if (!anIter.More()) {
170 anEntries->Append(anEntry);
175 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
176 const bool theIsStoreSameShapes)
178 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
180 TDF_Label aShapeLab = aData->shapeLab();
183 // store the new shape as primitive
184 TNaming_Builder aBuilder(aShapeLab);
187 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
189 return; // null shape inside
191 if(!theIsStoreSameShapes) {
192 Handle(TNaming_NamedShape) aNS;
193 if (TNaming_Tool::HasLabel(aShapeLab, aShape))
194 aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
195 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
196 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
197 // This shape is already in document, store reference instead of shape;
198 const TDF_Label aFoundLabel = aNS->Label();
199 TDF_Reference::Set(aShapeLab, aFoundLabel);
200 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
205 aBuilder.Generated(aShape);
207 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
208 if(!aBuilder.NamedShape()->IsEmpty()) {
209 Handle(TDataStd_Name) anAttr;
210 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
211 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
213 std::shared_ptr<Model_Document> aDoc =
214 std::dynamic_pointer_cast<Model_Document>(document());
215 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
222 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
223 const GeomShapePtr& theToShape, const bool theIsCleanStored)
225 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
228 if (theIsCleanStored)
230 TNaming_Builder* aBuilder = builder(0);
231 if (!theFromShape || !theToShape)
233 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
234 if (aShapeBasis.IsNull())
235 return; // null shape inside
236 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
237 if (aShapeNew.IsNull())
238 return; // null shape inside
240 // There is no sense to write history if old shape does not exist in the document.
241 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
242 ModelAPI_Session::get()->moduleDocument())->generalLabel();
243 TDF_Label anOriginalLabel;
244 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
245 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
246 aBuilder->Generated(aShapeNew);
249 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
251 aBuilder = builder(0);
254 aBuilder->Generated(aShapeBasis, aShapeNew);
255 // store information about the external document reference to restore old shape on open
256 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
260 if(!aBuilder->NamedShape()->IsEmpty()) {
261 Handle(TDataStd_Name) anAttr;
262 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
263 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
265 std::shared_ptr<Model_Document> aDoc =
266 std::dynamic_pointer_cast<Model_Document>(document());
267 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
274 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
275 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
277 bool aStored = false;
278 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
279 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
280 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
282 ListOfShape aNews; // check this old really generates theToShape
283 theMakeShape->generated(*anOldIter, aNews);
284 ListOfShape::iterator aNewIter = aNews.begin();
285 for (; aNewIter != aNews.end(); aNewIter++) {
286 if (theToShape->isSame(*aNewIter))
289 aStore = aNewIter != aNews.end();
292 storeGenerated(*anOldIter, theToShape, !aStored);
293 TNaming_Builder* aBuilder = builder(0);
294 aStored = !aBuilder->NamedShape()->IsEmpty();
297 if (!aStored) { // store as PRIMITIVE, but clean in any way
303 static TDF_Label builderLabel(DataPtr theData, const int theTag )
305 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
306 return theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
309 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
311 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
312 if (aFind == myBuilders.end()) {
313 myBuilders[theTag] = new TNaming_Builder(builderLabel(data(), theTag));
314 aFind = myBuilders.find(theTag);
316 return aFind->second;
319 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
320 const GeomShapePtr& theNewShape,
321 const bool theIsCleanStored)
323 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
326 if (theIsCleanStored) clean();
327 TNaming_Builder* aBuilder = builder(0);
328 if (!theOldShape || !theNewShape)
330 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
331 if (aShapeOld.IsNull())
332 return; // null shape inside
333 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
334 if (aShapeNew.IsNull())
335 return; // null shape inside
337 // There is no sense to write history if old shape does not exist in the document.
338 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
339 ModelAPI_Session::get()->moduleDocument())->generalLabel();
340 TDF_Label anOriginalLabel;
341 TopTools_ListOfShape anOldList;
342 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
343 // check this could be a compund by the whole feature selection
344 if (aShapeOld.ShapeType() == TopAbs_COMPOUND) {
345 for(TopoDS_Iterator aCompIter(aShapeOld); aCompIter.More(); aCompIter.Next()) {
346 if (isShapeInTree(aData->shapeLab(), anAccess2, aCompIter.Value(), anOriginalLabel)) {
347 anOldList.Append(aCompIter.Value());
355 anOldList.Append(aShapeOld);
357 if (anOldList.IsEmpty()) {
358 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
359 aBuilder->Generated(aShapeNew);
362 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
364 aBuilder = builder(0);
366 TopTools_ListIteratorOfListOfShape anOldIter(anOldList);
367 for(; anOldIter.More(); anOldIter.Next()) {
368 aBuilder->Modify(anOldIter.Value(), aShapeNew);
370 // store information about the external document reference to restore old shape on open
371 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
374 if(!aBuilder->NamedShape()->IsEmpty()) {
375 Handle(TDataStd_Name) anAttr;
376 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
377 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
379 std::shared_ptr<Model_Document> aDoc =
380 std::dynamic_pointer_cast<Model_Document>(document());
381 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
388 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
389 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
391 bool aStored = false;
392 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
393 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
394 // compounds may cause crash if call "modified"
395 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
396 (*anOldIter)->isCompSolid();
398 ListOfShape aNews; // check this old really modifies theNewShape
399 theMakeShape->modified(*anOldIter, aNews);
400 ListOfShape::iterator aNewIter = aNews.begin();
401 for(; aNewIter != aNews.end(); aNewIter++) {
402 if (theNewShape->isSame(*aNewIter))
405 aStore = aNewIter != aNews.end();
408 storeModified(*anOldIter, theNewShape, !aStored);
409 TNaming_Builder* aBuilder = builder(0);
410 aStored = !aBuilder->NamedShape()->IsEmpty();
414 // check the new shape is already in the tree, so, no need to store primitive, just reference
415 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
417 TDF_Label aShapeLab = aData->shapeLab();
418 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
419 Handle(TNaming_NamedShape) aNS;
420 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
421 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
422 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
423 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
424 // This shape is already in document, store reference instead of shape;
425 const TDF_Label aFoundLabel = aNS->Label();
426 TDF_Reference::Set(aShapeLab, aFoundLabel);
428 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
432 store(theNewShape); // store as PRIMITIVE, but clean in any way
437 void Model_BodyBuilder::clean()
439 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
442 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
443 for(; aBuilder != myBuilders.end(); aBuilder++) {
444 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
445 delete aBuilder->second;
446 if (!aNS.IsNull() && !aNS->Label().IsNull())
447 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
450 myPrimitivesNamesIndexMap.clear();
451 // remove the old reference (if any)
452 aLab.ForgetAttribute(TDF_Reference::GetID());
453 myFreePrimitiveTag = PRIMITIVES_START_TAG;
454 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
455 for(; anEntriesIter.More(); anEntriesIter.Next()) {
456 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
460 void Model_BodyBuilder::cleanCash()
462 myPrimitivesNamesIndexMap.clear();
465 Model_BodyBuilder::~Model_BodyBuilder()
470 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
472 std::string aName = theName;
473 std::string aPrefix = "";
475 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
476 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
477 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
478 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
479 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
480 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
482 aName.insert(0, aPrefix);
484 TDataStd_Name::Set(builderLabel(data(), theTag), aName.c_str());
486 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
487 const std::string& theName,
488 const bool theCheckIsInResult)
490 GeomShapePtr aResultShape = shape();
491 if (theCheckIsInResult) {
492 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
493 if (aNewShapeIsNotInResultShape) {
498 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
499 builder(myFreePrimitiveTag)->Generated(aShape);
500 if (!theName.empty()) {
501 std::string aName = theName;
502 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
503 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
504 aName += "_" + std::to_string(++(anIndexTags.index));
505 anIndexTags.tags.push_back(myFreePrimitiveTag);
506 if (anIndexTags.index == 2) {
507 buildName(anIndexTags.tags.front(), theName + "_1");
511 IndexTags anIndexTags;
512 anIndexTags.index = 1;
513 anIndexTags.tags.push_back(myFreePrimitiveTag);
514 myPrimitivesNamesIndexMap[theName] = anIndexTags;
517 buildName(myFreePrimitiveTag, aName);
519 ++myFreePrimitiveTag;
523 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
524 const GeomShapePtr& theNewShape,
525 const std::string& theName)
527 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
528 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
529 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
531 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
532 // TODO: This is a workaround. New shape should be only vertex, edge or face.
533 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
534 aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
535 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
536 builder(aTag)->Generated(anOldShape, anExp.Current());
538 buildName(aTag, theName);
540 aTag = getGenerationTag(aNewShape);
541 if (aTag == INVALID_TAG) return;
542 builder(aTag)->Generated(anOldShape, aNewShape);
543 buildName(aTag, theName);
547 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
548 const GeomShapePtr& theNewShape,
549 const std::string& theName)
551 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
552 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
553 int aTag = getModificationTag(aNewShape);
554 if (aTag == INVALID_TAG) return;
555 builder(aTag)->Modify(anOldShape, aNewShape);
556 buildName(aTag, theName);
559 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
560 const GeomShapePtr& theOldShape,
561 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
562 const GeomShapePtr& theShapesToExclude)
564 TopTools_MapOfShape anAlreadyProcessedShapes;
565 GeomShapePtr aResultShape = shape();
566 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
570 GeomShapePtr anOldSubShape = anExp.current();
571 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
572 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
573 || !theAlgo->isDeleted(anOldSubShape)
574 || aResultShape->isSubShape(anOldSubShape, false)
575 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
580 ListOfShape aNewShapes;
581 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
582 theAlgo->modified(anOldSubShape, aNewShapes);
585 if (aNewShapes.size() == 0
586 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
587 builder(DELETED_TAG)->Delete(anOldSubShape_);
592 // Keep only the shapes with minimal shape type
593 static void keepTopLevelShapes(ListOfShape& theShapes,
594 const TopoDS_Shape& theRoot,
595 const GeomShapePtr& theResultShape = GeomShapePtr())
597 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
598 ListOfShape::iterator anIt = theShapes.begin();
599 while (anIt != theShapes.end()) {
600 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
601 bool aSkip = aNewShape.IsNull() ||
602 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
603 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
604 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
605 ListOfShape::iterator aRemoveIt = anIt++;
606 theShapes.erase(aRemoveIt);
608 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
609 if (aType < aKeepShapeType) {
610 // found a shape with lesser shape type => remove all previous shapes
611 aKeepShapeType = aType;
612 theShapes.erase(theShapes.begin(), anIt);
614 } else if (aType > aKeepShapeType) {
615 // shapes with greater shape type should be removed from the list
616 ListOfShape::iterator aRemoveIt = anIt++;
617 theShapes.erase(aRemoveIt);
624 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
625 const GeomShapePtr& theOldShape,
626 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
627 const std::string& theName)
629 GeomShapePtr aResultShape = shape();
630 GeomShapePtr aShapeToExplore = theOldShape;
631 bool isAlgoHistoryCollected = theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore);
632 if (isAlgoHistoryCollected) {
633 // use optimized set of old shapes for this
634 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
636 theShapeTypeToExplore);
637 if (aCompound.get()) aShapeToExplore = aCompound;
640 // Store all types of subshapes in the map to use them for checking
641 // if the new shapes are sub-shapes of this result
642 TopTools_MapOfShape aResultShapeSubMap;
643 TopExp::MapShapes(aResultShape->impl<TopoDS_Shape>(), aResultShapeSubMap);
645 TopTools_MapOfShape anAlreadyProcessedShapes;
646 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
647 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
648 anOldShapeExp.more();
649 anOldShapeExp.next())
651 GeomShapePtr anOldSubShape = anOldShapeExp.current();
652 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
654 // There is no sense to write history if shape already processed
655 // or old shape does not exist in the document.
656 if (!anAlreadyProcessedShapes.Add(anOldSubShape_))
661 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument())->generalLabel();
662 TDF_Label anOriginalLabel;
663 if (!isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel))
669 ListOfShape aNewShapes;
670 if (isAlgoHistoryCollected) {
671 theAlgo->modifiedCached(anOldSubShape, aNewShapes);
674 theAlgo->modified(anOldSubShape, aNewShapes);
676 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
677 aNewShapesIt != aNewShapes.cend();
680 GeomShapePtr aNewShape = *aNewShapesIt;
681 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
683 if (anOldSubShape->isSame(aNewShape))
686 if (aResultShape->isSame(aNewShape))
687 continue; // it is stored on the root level (2241 - history propagation issue)
689 // Look in the map instead of aResultShape->isSubShape(aNewShape, false)
690 // to avoid many iterations of sub-shapes hierarchy that leads to performance issues
691 if (!aResultShapeSubMap.Contains(aNewShape_))
694 const bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
695 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
696 TNaming_Builder*aBuilder = builder(aTag);
697 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
698 continue; // new shape was already stored.
700 buildName(aTag, theName);
701 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
702 : aBuilder->Modify(anOldSubShape_, aNewShape_);
703 // store information about the external document reference to restore old shape on open
704 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
709 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
710 const GeomShapePtr& theOldShape,
711 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
712 const std::string& theName,
713 const bool theSaveOldIfNotInTree)
715 GeomShapePtr aResultShape = shape();
716 TopTools_MapOfShape anAlreadyProcessedShapes;
717 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
718 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
719 anOldShapeExp.more();
720 anOldShapeExp.next())
722 GeomShapePtr anOldSubShape = anOldShapeExp.current();
723 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
725 // There is no sense to write history if shape already processed
726 // or old shape does not exist in the document.
727 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
728 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
729 ModelAPI_Session::get()->moduleDocument())->generalLabel();
730 TDF_Label anOriginalLabel;
731 bool anOldSubShapeNotInTree =
732 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
733 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
734 // The second condition is added due to #20170 because sub-shape must be added to real parent
735 // shape, not the reference. The naming name of pure reference is not registered in document.
736 if (theSaveOldIfNotInTree && !aData->shapeLab().IsAttribute(TDF_Reference::GetID())) {
737 std::string aSelectionName = theName + "Selected";
738 generated(anOldSubShape, aSelectionName, false);
744 ListOfShape aNewShapes;
745 theAlgo->generated(anOldSubShape, aNewShapes);
747 keepTopLevelShapes(aNewShapes, anOldSubShape_);
749 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
750 aNewShapesIt != aNewShapes.cend();
753 GeomShapePtr aNewShape = *aNewShapesIt;
754 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
756 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
757 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
758 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
762 if (aResultShape->isSame(aNewShape))
763 continue; // it is stored on the root level
765 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
766 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
767 // TODO: This is a workaround. New shape should be only edge or face.
768 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
770 int aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
771 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
772 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
773 // store information about the external document reference to restore old shape on open
774 storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
776 buildName(aTag, theName);
778 int aTag = getGenerationTag(aNewShape_);
779 if (aTag == INVALID_TAG) return;
780 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
781 buildName(aTag, theName);
782 // store information about the external document reference to restore old shape on open
783 storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
790 //=======================================================================
791 int getDangleShapes(const TopoDS_Shape& theShapeIn,
792 const TopAbs_ShapeEnum theGeneratedFrom,
793 TopTools_DataMapOfShapeShape& theDangles)
796 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
797 TopAbs_ShapeEnum GeneratedTo;
798 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
799 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
800 else return Standard_False;
801 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
802 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
803 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
804 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
805 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
807 return theDangles.Extent();
810 //=======================================================================
811 void loadGeneratedDangleShapes(
812 const TopoDS_Shape& theShapeIn,
813 const TopAbs_ShapeEnum theGeneratedFrom,
814 TNaming_Builder * theBuilder)
816 TopTools_DataMapOfShapeShape dangles;
817 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
818 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
819 for (; itr.More(); itr.Next())
820 theBuilder->Generated(itr.Key(), itr.Value());
824 //=======================================================================
825 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
826 const std::string& theName)
828 if(theShape->isNull()) return;
829 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
831 if (aShape.ShapeType() == TopAbs_SOLID) {
832 TopExp_Explorer expl(aShape, TopAbs_FACE);
833 for (; expl.More(); expl.Next()) {
834 builder(myFreePrimitiveTag)->Generated(expl.Current());
835 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
836 aName = theName + "_" + aStr.ToCString();
837 buildName(myFreePrimitiveTag, aName);
838 ++myFreePrimitiveTag;
841 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
842 // load faces and all the free edges
843 TopTools_IndexedMapOfShape Faces;
844 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
845 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
846 TopExp_Explorer expl(aShape, TopAbs_FACE);
847 for (; expl.More(); expl.Next()) {
848 builder(myFreePrimitiveTag)->Generated(expl.Current());
849 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
850 aName = theName + "_" + aStr.ToCString();
851 buildName(myFreePrimitiveTag, aName);
852 ++myFreePrimitiveTag;
855 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
856 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
857 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
859 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
860 if (aLL.Extent() < 2) {
861 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
863 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
864 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
865 aName = theName + "_" + aStr.ToCString();
866 buildName(myFreePrimitiveTag, aName);
867 ++myFreePrimitiveTag;
869 TopTools_ListIteratorOfListOfShape anIter(aLL);
870 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
872 if(aFace.IsEqual(anIter.Value())) {
873 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
874 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
875 aName = theName + "_" + aStr.ToCString();
876 buildName(myFreePrimitiveTag, aName);
877 ++myFreePrimitiveTag;
881 } else if (aShape.ShapeType() == TopAbs_WIRE) {
882 TopTools_IndexedMapOfShape Edges;
883 BRepTools::Map3DEdges(aShape, Edges);
884 if (Edges.Extent() == 1) {
885 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
886 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
887 for (; expl.More(); expl.Next()) {
888 builder(myFreePrimitiveTag)->Generated(expl.Current());
889 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
890 aName = theName + "_" + aStr.ToCString();
891 buildName(myFreePrimitiveTag, aName);
892 ++myFreePrimitiveTag;
895 TopExp_Explorer expl(aShape, TopAbs_EDGE);
896 for (; expl.More(); expl.Next()) {
897 builder(myFreePrimitiveTag)->Generated(expl.Current());
898 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
899 aName = theName + "_" + aStr.ToCString();
900 buildName(myFreePrimitiveTag, aName);
901 ++myFreePrimitiveTag;
903 // and load generated vertices.
904 TopTools_DataMapOfShapeShape generated;
905 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
907 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
908 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
911 } else if (aShape.ShapeType() == TopAbs_EDGE) {
912 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
913 for (; expl.More(); expl.Next()) {
914 builder(myFreePrimitiveTag)->Generated(expl.Current());
915 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
916 aName = theName + "_" + aStr.ToCString();
917 buildName(myFreePrimitiveTag, aName);
918 ++myFreePrimitiveTag;
923 //=======================================================================
924 int findAmbiguities(const TopoDS_Shape& theShapeIn,
925 TopTools_ListOfShape& theList)
928 // edges -> ancestor faces list
929 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
930 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
931 // keeps the shapes which are already in the resulting list
932 TopTools_MapOfShape alreadyThere;
933 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
934 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
936 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
937 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
938 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
939 if (ancestors.Extent() < 2)
941 Standard_Integer anID = 0;
942 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
943 #if OCC_VERSION_LARGE < 0x07080000
944 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
946 anID ^= ((std::hash<TopoDS_Shape>{}(aFaceIt.ChangeValue()) & IntegerLast()) % 1990657 + 1); // Pierpont prime
949 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
950 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
951 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
952 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
953 for(; aSameEdge.More(); aSameEdge.Next()) {
954 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
955 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
956 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
959 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
960 for(; aFaceIter1.More(); aFaceIter1.Next()) {
961 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
962 for(; aFaceIter2.More(); aFaceIter2.Next()) {
963 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
966 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
969 if (!aFaceIter1.More()) { // all the faces are same => put to the result
970 if (alreadyThere.Add(aSameEdge.Value()))
971 theList.Append(aSameEdge.Value());
972 if (alreadyThere.Add(anAncestorsIter.Key()))
973 theList.Append(anAncestorsIter.Key());
976 } else { // ID is unique, just add this edge
977 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
979 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
981 return theList.Extent();
984 //=======================================================================
985 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
987 GeomShapePtr aShapePtr = shape();
988 if (theShape->isNull() || !aShapePtr.get())
990 TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
994 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
995 TopoDS_Iterator itr(aShape);
996 for (; itr.More(); itr.Next()) {
997 builder(myFreePrimitiveTag)->Generated(itr.Value());
998 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
999 aName = theName + "_" + aStr.ToCString();
1000 buildName(myFreePrimitiveTag, aName);
1001 ++myFreePrimitiveTag;
1002 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
1003 itr.Value().ShapeType() == TopAbs_COMPSOLID)
1005 GeomShapePtr itrShape(new GeomAPI_Shape());
1006 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
1007 loadFirstLevel(itrShape, theName);
1009 GeomShapePtr itrShape(new GeomAPI_Shape());
1010 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
1011 loadNextLevels(itrShape, theName);
1015 GeomShapePtr itrShape(new GeomAPI_Shape());
1016 itrShape->setImpl(new TopoDS_Shape(aShape));
1017 loadNextLevels(itrShape, theName);
1019 TopTools_ListOfShape aList;
1020 if(findAmbiguities(aShape, aList)) {
1021 TopTools_ListIteratorOfListOfShape it(aList);
1022 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
1023 builder(myFreePrimitiveTag)->Generated(it.Value());
1024 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
1025 aName = theName + "_" + aStr.ToCString();
1026 buildName(myFreePrimitiveTag, aName);
1031 GeomShapePtr Model_BodyBuilder::shape()
1033 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1034 if (aData && aData->isValid()) {
1035 TDF_Label aShapeLab = aData->shapeLab();
1036 Handle(TDF_Reference) aRef;
1037 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1038 aShapeLab = aRef->Get();
1040 Handle(TNaming_NamedShape) aName;
1041 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1042 TopoDS_Shape aShape = aName->Get();
1043 if (!aShape.IsNull()) {
1044 GeomShapePtr aRes(new GeomAPI_Shape);
1045 aRes->setImpl(new TopoDS_Shape(aShape));
1050 return GeomShapePtr();