1 // Copyright (C) 2014-2020 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 <Locale_Convert.h>
24 #include <Model_Data.h>
25 #include <Model_Document.h>
26 #include <ModelAPI_Session.h>
27 #include <TNaming_Builder.hxx>
28 #include <TNaming_NamedShape.hxx>
29 #include <TNaming_Iterator.hxx>
30 #include <TNaming_Tool.hxx>
31 #include <TNaming_SameShapeIterator.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <TDataStd_Integer.hxx>
34 #include <TDataStd_ExtStringList.hxx>
36 #include <TopoDS_Face.hxx>
37 #include <TDF_ChildIterator.hxx>
38 #include <TDF_ChildIDIterator.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_Tool.hxx>
41 #include <TopTools_MapOfShape.hxx>
42 #include <TopExp_Explorer.hxx>
43 #include <TopTools_ListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopTools_DataMapOfShapeListOfShape.hxx>
46 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
48 #include <TopTools_MapIteratorOfMapOfShape.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <TopTools_IndexedMapOfShape.hxx>
51 #include <TopTools_DataMapOfShapeShape.hxx>
53 #include <BRepTools.hxx>
54 #include <BRep_Tool.hxx>
55 #include <BRepTools_History.hxx>
56 #include <GeomAPI_Shape.h>
57 #include <GeomAPI_ShapeExplorer.h>
58 #include <GeomAlgoAPI_MakeShape.h>
59 #include <GeomAlgoAPI_SortListOfShapes.h>
60 #include <Config_PropManager.h>
62 //#include <TCollection_AsciiString.hxx>
63 //#define DEB_IMPORT 1
65 /// reference to the shape in external document: sting list attribute identifier
66 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
68 static const int INVALID_TAG = -1;
69 static const int GENERATED_VERTICES_TAG = 1;
70 static const int GENERATED_EDGES_TAG = 2;
71 static const int GENERATED_FACES_TAG = 3;
72 static const int MODIFIED_VERTICES_TAG = 4;
73 static const int MODIFIED_EDGES_TAG = 5;
74 static const int MODIFIED_FACES_TAG = 6;
75 static const int DELETED_TAG = 7;
76 static const int PRIMITIVES_START_TAG = 11;
78 static int getGenerationTag(const TopoDS_Shape& theShape) {
79 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
81 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
82 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
83 case TopAbs_FACE: return GENERATED_FACES_TAG;
84 default: break; // [to avoid compilation warning]
90 static int getModificationTag(const TopoDS_Shape& theShape) {
91 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
93 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
94 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
95 case TopAbs_FACE: return MODIFIED_FACES_TAG;
96 default: break; // [to avoid compilation warning]
102 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
103 const TopoDS_Shape& theOldShape,
104 const TopoDS_Shape& theNewShape)
106 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
110 if (aNamingIt.NewShape().IsSame(theNewShape)
111 && aNamingIt.OldShape().IsSame(theOldShape))
120 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
121 : ModelAPI_BodyBuilder(theOwner),
122 myFreePrimitiveTag(PRIMITIVES_START_TAG)
126 /// Checks that shape is presented in the tree with not-selection evolution
127 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
128 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
129 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
131 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
132 if (aResult) { //check evolution and a label of this shape
133 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
135 static Handle(TNaming_NamedShape) aNS;
136 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
137 if (aNS->Evolution() != TNaming_SELECTED) {
138 theOriginalLabel = aNS->Label();
144 if (!theAccess2.IsNull()) {
145 static const TDF_Label anEmpty;
146 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
151 /// Stores entry to the external label in the entries list at this label
152 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
154 // store information about the external document reference to restore old shape on open
155 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
156 Handle(TDataStd_ExtStringList) anEntries;
157 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
158 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
160 TCollection_AsciiString anEntry;
161 TDF_Tool::Entry(theExternal, anEntry);
162 // check it already contains this entry
163 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
164 for(; anIter.More(); anIter.Next())
165 if (anIter.Value() == anEntry)
167 if (!anIter.More()) {
168 anEntries->Append(anEntry);
173 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
174 const bool theIsStoreSameShapes)
176 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
178 TDF_Label aShapeLab = aData->shapeLab();
181 // store the new shape as primitive
182 TNaming_Builder aBuilder(aShapeLab);
185 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
187 return; // null shape inside
189 if(!theIsStoreSameShapes) {
190 Handle(TNaming_NamedShape) aNS;
191 if (TNaming_Tool::HasLabel(aShapeLab, aShape))
192 aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
193 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
194 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
195 // This shape is already in document, store reference instead of shape;
196 const TDF_Label aFoundLabel = aNS->Label();
197 TDF_Reference::Set(aShapeLab, aFoundLabel);
198 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
203 aBuilder.Generated(aShape);
205 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
206 if(!aBuilder.NamedShape()->IsEmpty()) {
207 Handle(TDataStd_Name) anAttr;
208 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
209 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
211 std::shared_ptr<Model_Document> aDoc =
212 std::dynamic_pointer_cast<Model_Document>(document());
213 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
220 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
221 const GeomShapePtr& theToShape, const bool theIsCleanStored)
223 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
226 if (theIsCleanStored)
228 TNaming_Builder* aBuilder = builder(0);
229 if (!theFromShape || !theToShape)
231 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
232 if (aShapeBasis.IsNull())
233 return; // null shape inside
234 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
235 if (aShapeNew.IsNull())
236 return; // null shape inside
238 // There is no sense to write history if old shape does not exist in the document.
239 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
240 ModelAPI_Session::get()->moduleDocument())->generalLabel();
241 TDF_Label anOriginalLabel;
242 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
243 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
244 aBuilder->Generated(aShapeNew);
247 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
249 aBuilder = builder(0);
252 aBuilder->Generated(aShapeBasis, aShapeNew);
253 // store information about the external document reference to restore old shape on open
254 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
258 if(!aBuilder->NamedShape()->IsEmpty()) {
259 Handle(TDataStd_Name) anAttr;
260 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
261 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
263 std::shared_ptr<Model_Document> aDoc =
264 std::dynamic_pointer_cast<Model_Document>(document());
265 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
272 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
273 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
275 bool aStored = false;
276 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
277 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
278 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
280 ListOfShape aNews; // check this old really generates theToShape
281 theMakeShape->generated(*anOldIter, aNews);
282 ListOfShape::iterator aNewIter = aNews.begin();
283 for (; aNewIter != aNews.end(); aNewIter++) {
284 if (theToShape->isSame(*aNewIter))
287 aStore = aNewIter != aNews.end();
290 storeGenerated(*anOldIter, theToShape, !aStored);
291 TNaming_Builder* aBuilder = builder(0);
292 aStored = !aBuilder->NamedShape()->IsEmpty();
295 if (!aStored) { // store as PRIMITIVE, but clean in any way
301 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
303 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
304 if (aFind == myBuilders.end()) {
305 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
306 TDF_Label aLab = theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
307 myBuilders[theTag] = new TNaming_Builder(aLab);
308 aFind = myBuilders.find(theTag);
310 return aFind->second;
313 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
314 const GeomShapePtr& theNewShape,
315 const bool theIsCleanStored)
317 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
320 if (theIsCleanStored) clean();
321 TNaming_Builder* aBuilder = builder(0);
322 if (!theOldShape || !theNewShape)
324 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
325 if (aShapeOld.IsNull())
326 return; // null shape inside
327 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
328 if (aShapeNew.IsNull())
329 return; // null shape inside
331 // There is no sense to write history if old shape does not exist in the document.
332 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
333 ModelAPI_Session::get()->moduleDocument())->generalLabel();
334 TDF_Label anOriginalLabel;
335 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
336 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
337 aBuilder->Generated(aShapeNew);
340 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
342 aBuilder = builder(0);
345 aBuilder->Modify(aShapeOld, aShapeNew);
346 // store information about the external document reference to restore old shape on open
347 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
350 if(!aBuilder->NamedShape()->IsEmpty()) {
351 Handle(TDataStd_Name) anAttr;
352 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
353 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
355 std::shared_ptr<Model_Document> aDoc =
356 std::dynamic_pointer_cast<Model_Document>(document());
357 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
364 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
365 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
367 bool aStored = false;
368 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
369 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
370 // compounds may cause crash if call "modified"
371 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
372 (*anOldIter)->isCompSolid();
374 ListOfShape aNews; // check this old really modifies theNewShape
375 theMakeShape->modified(*anOldIter, aNews);
376 ListOfShape::iterator aNewIter = aNews.begin();
377 for(; aNewIter != aNews.end(); aNewIter++) {
378 if (theNewShape->isSame(*aNewIter))
381 aStore = aNewIter != aNews.end();
384 storeModified(*anOldIter, theNewShape, !aStored);
385 TNaming_Builder* aBuilder = builder(0);
386 aStored = !aBuilder->NamedShape()->IsEmpty();
390 // check the new shape is already in the tree, so, no need to store primitive, just reference
391 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
393 TDF_Label aShapeLab = aData->shapeLab();
394 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
395 Handle(TNaming_NamedShape) aNS;
396 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
397 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
398 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
399 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
400 // This shape is already in document, store reference instead of shape;
401 const TDF_Label aFoundLabel = aNS->Label();
402 TDF_Reference::Set(aShapeLab, aFoundLabel);
404 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
408 store(theNewShape); // store as PRIMITIVE, but clean in any way
413 void Model_BodyBuilder::clean()
415 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
418 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
419 for(; aBuilder != myBuilders.end(); aBuilder++) {
420 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
421 delete aBuilder->second;
422 if (!aNS.IsNull() && !aNS->Label().IsNull())
423 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
426 myPrimitivesNamesIndexMap.clear();
427 // remove the old reference (if any)
428 aLab.ForgetAttribute(TDF_Reference::GetID());
429 myFreePrimitiveTag = PRIMITIVES_START_TAG;
430 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
431 for(; anEntriesIter.More(); anEntriesIter.Next()) {
432 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
434 // to clear old shapes in all sub-labels (they may be left without builders on Open)
435 TDF_ChildIDIterator aNSIter(aLab, TNaming_NamedShape::GetID(), true);
436 for(; aNSIter.More(); aNSIter.Next()) {
437 aNSIter.Value()->Label().ForgetAttribute(aNSIter.Value());
441 void Model_BodyBuilder::cleanCash()
443 myPrimitivesNamesIndexMap.clear();
446 Model_BodyBuilder::~Model_BodyBuilder()
451 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
453 std::string aName = theName;
454 std::string aPrefix = "";
456 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
457 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
458 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
459 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
460 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
461 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
463 aName.insert(0, aPrefix);
465 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
467 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
468 const std::string& theName,
469 const bool theCheckIsInResult)
471 GeomShapePtr aResultShape = shape();
472 if (theCheckIsInResult) {
473 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
474 if (aNewShapeIsNotInResultShape) {
479 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
480 builder(myFreePrimitiveTag)->Generated(aShape);
481 if (!theName.empty()) {
482 std::string aName = theName;
483 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
484 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
485 aName += "_" + std::to_string(++(anIndexTags.index));
486 anIndexTags.tags.push_back(myFreePrimitiveTag);
487 if (anIndexTags.index == 2) {
488 buildName(anIndexTags.tags.front(), theName + "_1");
492 IndexTags anIndexTags;
493 anIndexTags.index = 1;
494 anIndexTags.tags.push_back(myFreePrimitiveTag);
495 myPrimitivesNamesIndexMap[theName] = anIndexTags;
498 buildName(myFreePrimitiveTag, aName);
500 ++myFreePrimitiveTag;
504 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
505 const GeomShapePtr& theNewShape,
506 const std::string& theName)
508 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
509 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
510 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
512 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
513 // TODO: This is a workaround. New shape should be only vertex, edge or face.
514 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
515 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
516 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
517 builder(aTag)->Generated(anOldShape, anExp.Current());
519 buildName(aTag, theName);
521 aTag = getGenerationTag(aNewShape);
522 if (aTag == INVALID_TAG) return;
523 builder(aTag)->Generated(anOldShape, aNewShape);
524 buildName(aTag, theName);
528 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
529 const GeomShapePtr& theNewShape,
530 const std::string& theName)
532 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
533 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
534 int aTag = getModificationTag(aNewShape);
535 if (aTag == INVALID_TAG) return;
536 builder(aTag)->Modify(anOldShape, aNewShape);
537 buildName(aTag, theName);
540 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
541 const GeomShapePtr& theOldShape,
542 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
543 const GeomShapePtr& theShapesToExclude)
545 TopTools_MapOfShape anAlreadyProcessedShapes;
546 GeomShapePtr aResultShape = shape();
547 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
551 GeomShapePtr anOldSubShape = anExp.current();
552 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
553 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
554 || !theAlgo->isDeleted(anOldSubShape)
555 || aResultShape->isSubShape(anOldSubShape, false)
556 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
561 ListOfShape aNewShapes;
562 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
563 theAlgo->modified(anOldSubShape, aNewShapes);
566 if (aNewShapes.size() == 0
567 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
568 builder(DELETED_TAG)->Delete(anOldSubShape_);
573 // Keep only the shapes with minimal shape type
574 static void keepTopLevelShapes(ListOfShape& theShapes,
575 const TopoDS_Shape& theRoot,
576 const GeomShapePtr& theResultShape = GeomShapePtr())
578 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
579 ListOfShape::iterator anIt = theShapes.begin();
580 while (anIt != theShapes.end()) {
581 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
582 bool aSkip = aNewShape.IsNull() ||
583 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
584 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
585 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
586 ListOfShape::iterator aRemoveIt = anIt++;
587 theShapes.erase(aRemoveIt);
589 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
590 if (aType < aKeepShapeType) {
591 // found a shape with lesser shape type => remove all previous shapes
592 aKeepShapeType = aType;
593 theShapes.erase(theShapes.begin(), anIt);
595 } else if (aType > aKeepShapeType) {
596 // shapes with greater shape type should be removed from the list
597 ListOfShape::iterator aRemoveIt = anIt++;
598 theShapes.erase(aRemoveIt);
605 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
606 const GeomShapePtr& theOldShape,
607 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
608 const std::string& theName)
610 GeomShapePtr aResultShape = shape();
611 GeomShapePtr aShapeToExplore = theOldShape;
612 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
613 // use optimized set of old shapes for this
614 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
616 theShapeTypeToExplore);
617 if (aCompound.get()) aShapeToExplore = aCompound;
620 TopTools_MapOfShape anAlreadyProcessedShapes;
621 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
622 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
623 anOldShapeExp.more();
624 anOldShapeExp.next())
626 GeomShapePtr anOldSubShape = anOldShapeExp.current();
627 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
629 // There is no sense to write history if shape already processed
630 // or old shape does not exist in the document.
631 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
632 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
633 ModelAPI_Session::get()->moduleDocument())->generalLabel();
634 TDF_Label anOriginalLabel;
635 bool anOldSubShapeNotInTree =
636 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
637 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
642 ListOfShape aNewShapes;
643 theAlgo->modified(anOldSubShape, aNewShapes);
645 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
646 aNewShapesIt != aNewShapes.cend();
649 GeomShapePtr aNewShape = *aNewShapesIt;
650 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
651 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
653 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
654 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
655 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
658 if (aResultShape->isSame(aNewShape))
659 continue; // it is stored on the root level (2241 - history propagation issue)
661 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
662 TNaming_Builder*aBuilder = builder(aTag);
663 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
664 continue; // new shape was already stored.
666 buildName(aTag, theName);
667 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
668 : aBuilder->Modify(anOldSubShape_, aNewShape_);
669 // store information about the external document reference to restore old shape on open
670 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
675 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
676 const GeomShapePtr& theOldShape,
677 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
678 const std::string& theName,
679 const bool theSaveOldIfNotInTree)
681 GeomShapePtr aResultShape = shape();
682 TopTools_MapOfShape anAlreadyProcessedShapes;
683 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
684 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
685 anOldShapeExp.more();
686 anOldShapeExp.next())
688 GeomShapePtr anOldSubShape = anOldShapeExp.current();
689 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
691 // There is no sense to write history if shape already processed
692 // or old shape does not exist in the document.
693 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
694 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
695 ModelAPI_Session::get()->moduleDocument())->generalLabel();
696 TDF_Label anOriginalLabel;
697 bool anOldSubShapeNotInTree =
698 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
699 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
700 if (theSaveOldIfNotInTree) {
701 std::string aSelectionName = theName + "Selected";
702 generated(anOldSubShape, aSelectionName, false);
708 ListOfShape aNewShapes;
709 theAlgo->generated(anOldSubShape, aNewShapes);
711 keepTopLevelShapes(aNewShapes, anOldSubShape_);
713 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
714 aNewShapesIt != aNewShapes.cend();
717 GeomShapePtr aNewShape = *aNewShapesIt;
718 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
720 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
721 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
722 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
726 if (aResultShape->isSame(aNewShape))
727 continue; // it is stored on the root level
729 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
730 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
731 // TODO: This is a workaround. New shape should be only edge or face.
732 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
734 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
735 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
736 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
737 // store information about the external document reference to restore old shape on open
738 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
740 buildName(aTag, theName);
742 int aTag = getGenerationTag(aNewShape_);
743 if (aTag == INVALID_TAG) return;
744 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
745 buildName(aTag, theName);
746 // store information about the external document reference to restore old shape on open
747 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
754 //=======================================================================
755 int getDangleShapes(const TopoDS_Shape& theShapeIn,
756 const TopAbs_ShapeEnum theGeneratedFrom,
757 TopTools_DataMapOfShapeShape& theDangles)
760 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
761 TopAbs_ShapeEnum GeneratedTo;
762 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
763 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
764 else return Standard_False;
765 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
766 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
767 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
768 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
769 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
771 return theDangles.Extent();
774 //=======================================================================
775 void loadGeneratedDangleShapes(
776 const TopoDS_Shape& theShapeIn,
777 const TopAbs_ShapeEnum theGeneratedFrom,
778 TNaming_Builder * theBuilder)
780 TopTools_DataMapOfShapeShape dangles;
781 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
782 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
783 for (; itr.More(); itr.Next())
784 theBuilder->Generated(itr.Key(), itr.Value());
788 //=======================================================================
789 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
790 const std::string& theName)
792 if(theShape->isNull()) return;
793 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
795 if (aShape.ShapeType() == TopAbs_SOLID) {
796 TopExp_Explorer expl(aShape, TopAbs_FACE);
797 for (; expl.More(); expl.Next()) {
798 builder(myFreePrimitiveTag)->Generated(expl.Current());
799 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
800 aName = theName + "_" + aStr.ToCString();
801 buildName(myFreePrimitiveTag, aName);
802 ++myFreePrimitiveTag;
805 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
806 // load faces and all the free edges
807 TopTools_IndexedMapOfShape Faces;
808 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
809 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
810 TopExp_Explorer expl(aShape, TopAbs_FACE);
811 for (; expl.More(); expl.Next()) {
812 builder(myFreePrimitiveTag)->Generated(expl.Current());
813 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
814 aName = theName + "_" + aStr.ToCString();
815 buildName(myFreePrimitiveTag, aName);
816 ++myFreePrimitiveTag;
819 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
820 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
821 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
823 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
824 if (aLL.Extent() < 2) {
825 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
827 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
828 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
829 aName = theName + "_" + aStr.ToCString();
830 buildName(myFreePrimitiveTag, aName);
831 ++myFreePrimitiveTag;
833 TopTools_ListIteratorOfListOfShape anIter(aLL);
834 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
836 if(aFace.IsEqual(anIter.Value())) {
837 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
838 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
839 aName = theName + "_" + aStr.ToCString();
840 buildName(myFreePrimitiveTag, aName);
841 ++myFreePrimitiveTag;
845 } else if (aShape.ShapeType() == TopAbs_WIRE) {
846 TopTools_IndexedMapOfShape Edges;
847 BRepTools::Map3DEdges(aShape, Edges);
848 if (Edges.Extent() == 1) {
849 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
850 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
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;
859 TopExp_Explorer expl(aShape, TopAbs_EDGE);
860 for (; expl.More(); expl.Next()) {
861 builder(myFreePrimitiveTag)->Generated(expl.Current());
862 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
863 aName = theName + "_" + aStr.ToCString();
864 buildName(myFreePrimitiveTag, aName);
865 ++myFreePrimitiveTag;
867 // and load generated vertices.
868 TopTools_DataMapOfShapeShape generated;
869 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
871 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
872 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
875 } else if (aShape.ShapeType() == TopAbs_EDGE) {
876 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
877 for (; expl.More(); expl.Next()) {
878 builder(myFreePrimitiveTag)->Generated(expl.Current());
879 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
880 aName = theName + "_" + aStr.ToCString();
881 buildName(myFreePrimitiveTag, aName);
882 ++myFreePrimitiveTag;
887 //=======================================================================
888 int findAmbiguities(const TopoDS_Shape& theShapeIn,
889 TopTools_ListOfShape& theList)
892 // edges -> ancestor faces list
893 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
894 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
895 // keeps the shapes which are already in the resulting list
896 TopTools_MapOfShape alreadyThere;
897 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
898 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
900 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
901 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
902 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
903 if (ancestors.Extent() < 2)
905 Standard_Integer anID = 0;
906 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
907 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
909 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
910 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
911 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
912 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
913 for(; aSameEdge.More(); aSameEdge.Next()) {
914 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
915 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
916 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
919 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
920 for(; aFaceIter1.More(); aFaceIter1.Next()) {
921 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
922 for(; aFaceIter2.More(); aFaceIter2.Next()) {
923 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
926 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
929 if (!aFaceIter1.More()) { // all the faces are same => put to the result
930 if (alreadyThere.Add(aSameEdge.Value()))
931 theList.Append(aSameEdge.Value());
932 if (alreadyThere.Add(anAncestorsIter.Key()))
933 theList.Append(anAncestorsIter.Key());
936 } else { // ID is unique, just add this edge
937 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
939 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
941 return theList.Extent();
944 //=======================================================================
945 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
947 GeomShapePtr aShapePtr = shape();
948 if (theShape->isNull() || !aShapePtr.get())
950 TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
954 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
955 TopoDS_Iterator itr(aShape);
956 for (; itr.More(); itr.Next()) {
957 builder(myFreePrimitiveTag)->Generated(itr.Value());
958 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
959 aName = theName + "_" + aStr.ToCString();
960 buildName(myFreePrimitiveTag, aName);
961 ++myFreePrimitiveTag;
962 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
963 itr.Value().ShapeType() == TopAbs_COMPSOLID)
965 GeomShapePtr itrShape(new GeomAPI_Shape());
966 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
967 loadFirstLevel(itrShape, theName);
969 GeomShapePtr itrShape(new GeomAPI_Shape());
970 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
971 loadNextLevels(itrShape, theName);
975 GeomShapePtr itrShape(new GeomAPI_Shape());
976 itrShape->setImpl(new TopoDS_Shape(aShape));
977 loadNextLevels(itrShape, theName);
979 TopTools_ListOfShape aList;
980 if(findAmbiguities(aShape, aList)) {
981 TopTools_ListIteratorOfListOfShape it(aList);
982 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
983 builder(myFreePrimitiveTag)->Generated(it.Value());
984 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
985 aName = theName + "_" + aStr.ToCString();
986 buildName(myFreePrimitiveTag, aName);
991 GeomShapePtr Model_BodyBuilder::shape()
993 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
994 if (aData && aData->isValid()) {
995 TDF_Label aShapeLab = aData->shapeLab();
996 Handle(TDF_Reference) aRef;
997 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
998 aShapeLab = aRef->Get();
1000 Handle(TNaming_NamedShape) aName;
1001 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1002 TopoDS_Shape aShape = aName->Get();
1003 if (!aShape.IsNull()) {
1004 GeomShapePtr aRes(new GeomAPI_Shape);
1005 aRes->setImpl(new TopoDS_Shape(aShape));
1010 return GeomShapePtr();