1 // Copyright (C) 2014-2017 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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include <Model_BodyBuilder.h>
23 #include <Model_Data.h>
24 #include <Model_Document.h>
25 #include <ModelAPI_Session.h>
26 #include <TNaming_Builder.hxx>
27 #include <TNaming_NamedShape.hxx>
28 #include <TNaming_Iterator.hxx>
29 #include <TNaming_Tool.hxx>
30 #include <TNaming_SameShapeIterator.hxx>
31 #include <TDataStd_Name.hxx>
32 #include <TDataStd_Integer.hxx>
33 #include <TDataStd_ExtStringList.hxx>
35 #include <TopoDS_Face.hxx>
36 #include <TDF_ChildIterator.hxx>
37 #include <TDF_ChildIDIterator.hxx>
38 #include <TDF_Reference.hxx>
39 #include <TDF_Tool.hxx>
40 #include <TopTools_MapOfShape.hxx>
41 #include <TopExp_Explorer.hxx>
42 #include <TopTools_ListOfShape.hxx>
43 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <TopTools_DataMapOfShapeListOfShape.hxx>
45 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
46 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
47 #include <TopTools_MapIteratorOfMapOfShape.hxx>
48 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
49 #include <TopTools_IndexedMapOfShape.hxx>
50 #include <TopTools_DataMapOfShapeShape.hxx>
52 #include <BRepTools.hxx>
53 #include <BRep_Tool.hxx>
54 #include <BRepTools_History.hxx>
55 #include <GeomAPI_Shape.h>
56 #include <GeomAPI_ShapeExplorer.h>
57 #include <GeomAlgoAPI_MakeShape.h>
58 #include <GeomAlgoAPI_SortListOfShapes.h>
59 #include <Config_PropManager.h>
61 //#include <TCollection_AsciiString.hxx>
62 //#define DEB_IMPORT 1
64 /// reference to the shape in external document: sting list attribute identifier
65 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
67 static const int INVALID_TAG = -1;
68 static const int GENERATED_VERTICES_TAG = 1;
69 static const int GENERATED_EDGES_TAG = 2;
70 static const int GENERATED_FACES_TAG = 3;
71 static const int MODIFIED_VERTICES_TAG = 4;
72 static const int MODIFIED_EDGES_TAG = 5;
73 static const int MODIFIED_FACES_TAG = 6;
74 static const int DELETED_TAG = 7;
75 static const int PRIMITIVES_START_TAG = 11;
77 static int getGenerationTag(const TopoDS_Shape& theShape) {
78 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
80 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
81 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
82 case TopAbs_FACE: return GENERATED_FACES_TAG;
88 static int getModificationTag(const TopoDS_Shape& theShape) {
89 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
91 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
92 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
93 case TopAbs_FACE: return MODIFIED_FACES_TAG;
99 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
100 const TopoDS_Shape& theOldShape,
101 const TopoDS_Shape& theNewShape)
103 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
107 if (aNamingIt.NewShape().IsSame(theNewShape)
108 && aNamingIt.OldShape().IsSame(theOldShape))
117 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
118 : ModelAPI_BodyBuilder(theOwner),
119 myFreePrimitiveTag(PRIMITIVES_START_TAG)
123 /// Checks that shape is presented in the tree with not-selection evolution
124 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
125 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
126 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
128 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
129 if (aResult) { //check evolution and a label of this shape
130 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
132 static Handle(TNaming_NamedShape) aNS;
133 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
134 if (aNS->Evolution() != TNaming_SELECTED) {
135 theOriginalLabel = aNS->Label();
141 if (!theAccess2.IsNull()) {
142 static const TDF_Label anEmpty;
143 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
148 /// Stores entry to the external label in the entries list at this label
149 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
151 // store information about the external document reference to restore old shape on open
152 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
153 Handle(TDataStd_ExtStringList) anEntries;
154 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
155 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
157 TCollection_AsciiString anEntry;
158 TDF_Tool::Entry(theExternal, anEntry);
159 // check it already contains this entry
160 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
161 for(; anIter.More(); anIter.Next())
162 if (anIter.Value() == anEntry)
164 if (!anIter.More()) {
165 anEntries->Append(anEntry);
170 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
171 const bool theIsStoreSameShapes)
173 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
175 TDF_Label aShapeLab = aData->shapeLab();
178 // store the new shape as primitive
179 TNaming_Builder aBuilder(aShapeLab);
182 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
184 return; // null shape inside
186 if(!theIsStoreSameShapes) {
187 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
188 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
189 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
190 // This shape is already in document, store reference instead of shape;
191 const TDF_Label aFoundLabel = aNS->Label();
192 TDF_Reference::Set(aShapeLab, aFoundLabel);
193 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
198 aBuilder.Generated(aShape);
200 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
201 if(!aBuilder.NamedShape()->IsEmpty()) {
202 Handle(TDataStd_Name) anAttr;
203 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
204 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
206 std::shared_ptr<Model_Document> aDoc =
207 std::dynamic_pointer_cast<Model_Document>(document());
208 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
215 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
216 const GeomShapePtr& theToShape, const bool theIsCleanStored)
218 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
220 TDF_Label aShapeLab = aData->shapeLab();
222 if (theIsCleanStored)
224 TNaming_Builder* aBuilder = builder(0);
225 if (!theFromShape || !theToShape)
227 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
228 if (aShapeBasis.IsNull())
229 return; // null shape inside
230 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
231 if (aShapeNew.IsNull())
232 return; // null shape inside
234 // There is no sense to write history if old shape does not exist in the document.
235 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
236 ModelAPI_Session::get()->moduleDocument())->generalLabel();
237 TDF_Label anOriginalLabel;
238 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
239 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
240 aBuilder->Generated(aShapeNew);
243 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
245 aBuilder = builder(0);
248 aBuilder->Generated(aShapeBasis, aShapeNew);
249 // store information about the external document reference to restore old shape on open
250 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
254 if(!aBuilder->NamedShape()->IsEmpty()) {
255 Handle(TDataStd_Name) anAttr;
256 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
257 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
259 std::shared_ptr<Model_Document> aDoc =
260 std::dynamic_pointer_cast<Model_Document>(document());
261 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
268 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
269 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
271 bool aStored = false;
272 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
273 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
274 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
276 ListOfShape aNews; // check this old really generates theToShape
277 theMakeShape->generated(*anOldIter, aNews);
278 ListOfShape::iterator aNewIter = aNews.begin();
279 for (; aNewIter != aNews.end(); aNewIter++) {
280 if (theToShape->isSame(*aNewIter))
283 aStore = aNewIter != aNews.end();
286 storeGenerated(*anOldIter, theToShape, !aStored);
287 TNaming_Builder* aBuilder = builder(0);
288 aStored = !aBuilder->NamedShape()->IsEmpty();
291 if (!aStored) { // store as PRIMITIVE, but clean in any way
297 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
299 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
300 if (aFind == myBuilders.end()) {
301 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
302 myBuilders[theTag] = new TNaming_Builder(
303 theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
304 aFind = myBuilders.find(theTag);
306 return aFind->second;
309 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
310 const GeomShapePtr& theNewShape,
311 const bool theIsCleanStored)
313 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
316 if (theIsCleanStored) clean();
317 TNaming_Builder* aBuilder = builder(0);
318 if (!theOldShape || !theNewShape)
320 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
321 if (aShapeOld.IsNull())
322 return; // null shape inside
323 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
324 if (aShapeNew.IsNull())
325 return; // null shape inside
327 // There is no sense to write history if old shape does not exist in the document.
328 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
329 ModelAPI_Session::get()->moduleDocument())->generalLabel();
330 TDF_Label anOriginalLabel;
331 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
332 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
333 aBuilder->Generated(aShapeNew);
336 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
338 aBuilder = builder(0);
341 aBuilder->Modify(aShapeOld, aShapeNew);
342 // store information about the external document reference to restore old shape on open
343 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
346 if(!aBuilder->NamedShape()->IsEmpty()) {
347 Handle(TDataStd_Name) anAttr;
348 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
349 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
351 std::shared_ptr<Model_Document> aDoc =
352 std::dynamic_pointer_cast<Model_Document>(document());
353 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
360 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
361 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
363 bool aStored = false;
364 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
365 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
366 // compounds may cause crash if call "modified"
367 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
369 ListOfShape aNews; // check this old really modifies theNewShape
370 theMakeShape->modified(*anOldIter, aNews);
371 ListOfShape::iterator aNewIter = aNews.begin();
372 for(; aNewIter != aNews.end(); aNewIter++) {
373 if (theNewShape->isSame(*aNewIter))
376 aStore = aNewIter != aNews.end();
379 storeModified(*anOldIter, theNewShape, !aStored);
380 TNaming_Builder* aBuilder = builder(0);
381 aStored = !aBuilder->NamedShape()->IsEmpty();
384 if (!aStored) { // store as PRIMITIVE, but clean in any way
390 void Model_BodyBuilder::clean()
392 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
395 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
396 for(; aBuilder != myBuilders.end(); aBuilder++) {
397 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
398 delete aBuilder->second;
399 if (!aNS.IsNull() && !aNS->Label().IsNull())
400 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
403 myPrimitivesNamesIndexMap.clear();
404 // remove the old reference (if any)
405 aLab.ForgetAttribute(TDF_Reference::GetID());
406 myFreePrimitiveTag = PRIMITIVES_START_TAG;
407 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
408 for(; anEntriesIter.More(); anEntriesIter.Next()) {
409 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
413 void Model_BodyBuilder::cleanCash()
415 myPrimitivesNamesIndexMap.clear();
418 Model_BodyBuilder::~Model_BodyBuilder()
423 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
425 std::string aName = theName;
426 std::string aPrefix = "";
428 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
429 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
430 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
431 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
432 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
433 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
435 aName.insert(0, aPrefix);
437 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
439 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
440 const std::string& theName,
441 const bool theCheckIsInResult)
443 GeomShapePtr aResultShape = shape();
444 if (theCheckIsInResult) {
445 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
446 if (aNewShapeIsNotInResultShape) {
451 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
452 builder(myFreePrimitiveTag)->Generated(aShape);
453 if (!theName.empty()) {
454 std::string aName = theName;
455 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
456 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
457 aName += "_" + std::to_string(++(anIndexTags.index));
458 anIndexTags.tags.push_back(myFreePrimitiveTag);
459 if (anIndexTags.index == 2) {
460 buildName(anIndexTags.tags.front(), theName + "_1");
464 IndexTags anIndexTags;
465 anIndexTags.index = 1;
466 anIndexTags.tags.push_back(myFreePrimitiveTag);
467 myPrimitivesNamesIndexMap[theName] = anIndexTags;
470 buildName(myFreePrimitiveTag, aName);
472 ++myFreePrimitiveTag;
476 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
477 const GeomShapePtr& theNewShape,
478 const std::string& theName)
480 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
481 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
482 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
484 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
485 // TODO: This is a workaround. New shape should be only vertex, edge or face.
486 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
487 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
488 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
489 builder(aTag)->Generated(anOldShape, anExp.Current());
491 buildName(aTag, theName);
493 aTag = getGenerationTag(aNewShape);
494 if (aTag == INVALID_TAG) return;
495 builder(aTag)->Generated(anOldShape, aNewShape);
496 buildName(aTag, theName);
500 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
501 const GeomShapePtr& theNewShape,
502 const std::string& theName)
504 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
505 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
506 int aTag = getModificationTag(aNewShape);
507 if (aTag == INVALID_TAG) return;
508 builder(aTag)->Modify(anOldShape, aNewShape);
509 buildName(aTag, theName);
512 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
513 const GeomShapePtr& theOldShape,
514 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
515 const GeomShapePtr& theShapesToExclude)
517 TopTools_MapOfShape anAlreadyProcessedShapes;
518 GeomShapePtr aResultShape = shape();
519 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
523 GeomShapePtr anOldSubShape = anExp.current();
524 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
525 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
526 || !theAlgo->isDeleted(anOldSubShape)
527 || aResultShape->isSubShape(anOldSubShape, false)
528 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
533 ListOfShape aNewShapes;
534 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
535 theAlgo->modified(anOldSubShape, aNewShapes);
538 if (aNewShapes.size() == 0
539 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
540 builder(DELETED_TAG)->Delete(anOldSubShape_);
545 // Keep only the shapes with minimal shape type
546 static void keepTopLevelShapes(ListOfShape& theShapes,
547 const TopoDS_Shape& theRoot,
548 const GeomShapePtr& theResultShape = GeomShapePtr())
550 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
551 ListOfShape::iterator anIt = theShapes.begin();
552 while (anIt != theShapes.end()) {
553 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
554 bool aSkip = aNewShape.IsNull() ||
555 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
556 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
557 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
558 ListOfShape::iterator aRemoveIt = anIt++;
559 theShapes.erase(aRemoveIt);
561 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
562 if (aType < aKeepShapeType) {
563 // found a shape with lesser shape type => remove all previous shapes
564 aKeepShapeType = aType;
565 theShapes.erase(theShapes.begin(), anIt);
567 } else if (aType > aKeepShapeType) {
568 // shapes with greater shape type should be removed from the list
569 ListOfShape::iterator aRemoveIt = anIt++;
570 theShapes.erase(aRemoveIt);
577 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
578 const GeomShapePtr& theOldShape,
579 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
580 const std::string& theName)
582 GeomShapePtr aResultShape = shape();
583 GeomShapePtr aShapeToExplore = theOldShape;
584 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
585 // use optimized set of old shapes for this
586 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
588 theShapeTypeToExplore);
589 if (aCompound.get()) aShapeToExplore = aCompound;
592 TopTools_MapOfShape anAlreadyProcessedShapes;
593 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
594 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
595 anOldShapeExp.more();
596 anOldShapeExp.next())
598 GeomShapePtr anOldSubShape = anOldShapeExp.current();
599 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
601 // There is no sense to write history if shape already processed
602 // or old shape does not exist in the document.
603 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
604 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
605 ModelAPI_Session::get()->moduleDocument())->generalLabel();
606 TDF_Label anOriginalLabel;
607 bool anOldSubShapeNotInTree =
608 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
609 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
614 ListOfShape aNewShapes;
615 theAlgo->modified(anOldSubShape, aNewShapes);
617 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
618 aNewShapesIt != aNewShapes.cend();
621 GeomShapePtr aNewShape = *aNewShapesIt;
622 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
623 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
625 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
626 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
627 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
630 if (aResultShape->isSame(aNewShape))
631 continue; // it is stored on the root level (2241 - history propagation issue)
633 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
634 TNaming_Builder*aBuilder = builder(aTag);
635 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
636 continue; // new shape was already stored.
638 buildName(aTag, theName);
639 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
640 : aBuilder->Modify(anOldSubShape_, aNewShape_);
641 // store information about the external document reference to restore old shape on open
642 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
647 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
648 const GeomShapePtr& theOldShape,
649 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
650 const std::string& theName,
651 const bool theSaveOldIfNotInTree)
653 GeomShapePtr aResultShape = shape();
654 TopTools_MapOfShape anAlreadyProcessedShapes;
655 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
656 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
657 anOldShapeExp.more();
658 anOldShapeExp.next())
660 GeomShapePtr anOldSubShape = anOldShapeExp.current();
661 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
663 // There is no sense to write history if shape already processed
664 // or old shape does not exist in the document.
665 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
666 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
667 ModelAPI_Session::get()->moduleDocument())->generalLabel();
668 TDF_Label anOriginalLabel;
669 bool anOldSubShapeNotInTree =
670 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
671 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
672 if (theSaveOldIfNotInTree) {
673 std::string aSelectionName = theName + "Selected";
674 generated(anOldSubShape, aSelectionName, false);
680 ListOfShape aNewShapes;
681 theAlgo->generated(anOldSubShape, aNewShapes);
683 keepTopLevelShapes(aNewShapes, anOldSubShape_);
685 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
686 aNewShapesIt != aNewShapes.cend();
689 GeomShapePtr aNewShape = *aNewShapesIt;
690 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
692 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
693 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
694 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
698 if (aResultShape->isSame(aNewShape))
699 continue; // it is stored on the root level
701 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
702 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
703 // TODO: This is a workaround. New shape should be only edge or face.
704 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
706 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
707 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
708 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
709 // store information about the external document reference to restore old shape on open
710 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
712 buildName(aTag, theName);
714 int aTag = getGenerationTag(aNewShape_);
715 if (aTag == INVALID_TAG) return;
716 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
717 buildName(aTag, theName);
718 // store information about the external document reference to restore old shape on open
719 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
726 //=======================================================================
727 int getDangleShapes(const TopoDS_Shape& theShapeIn,
728 const TopAbs_ShapeEnum theGeneratedFrom,
729 TopTools_DataMapOfShapeShape& theDangles)
732 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
733 TopAbs_ShapeEnum GeneratedTo;
734 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
735 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
736 else return Standard_False;
737 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
738 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
739 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
740 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
741 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
743 return theDangles.Extent();
746 //=======================================================================
747 void loadGeneratedDangleShapes(
748 const TopoDS_Shape& theShapeIn,
749 const TopAbs_ShapeEnum theGeneratedFrom,
750 TNaming_Builder * theBuilder)
752 TopTools_DataMapOfShapeShape dangles;
753 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
754 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
755 for (; itr.More(); itr.Next())
756 theBuilder->Generated(itr.Key(), itr.Value());
760 //=======================================================================
761 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
762 const std::string& theName)
764 if(theShape->isNull()) return;
765 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
767 if (aShape.ShapeType() == TopAbs_SOLID) {
768 TopExp_Explorer expl(aShape, TopAbs_FACE);
769 for (; expl.More(); expl.Next()) {
770 builder(myFreePrimitiveTag)->Generated(expl.Current());
771 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
772 aName = theName + "_" + aStr.ToCString();
773 buildName(myFreePrimitiveTag, aName);
774 ++myFreePrimitiveTag;
777 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
778 // load faces and all the free edges
779 TopTools_IndexedMapOfShape Faces;
780 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
781 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
782 TopExp_Explorer expl(aShape, TopAbs_FACE);
783 for (; expl.More(); expl.Next()) {
784 builder(myFreePrimitiveTag)->Generated(expl.Current());
785 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
786 aName = theName + "_" + aStr.ToCString();
787 buildName(myFreePrimitiveTag, aName);
788 ++myFreePrimitiveTag;
791 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
792 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
793 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
795 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
796 if (aLL.Extent() < 2) {
797 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
799 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
800 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
801 aName = theName + "_" + aStr.ToCString();
802 buildName(myFreePrimitiveTag, aName);
803 ++myFreePrimitiveTag;
805 TopTools_ListIteratorOfListOfShape anIter(aLL);
806 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
808 if(aFace.IsEqual(anIter.Value())) {
809 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
810 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
811 aName = theName + "_" + aStr.ToCString();
812 buildName(myFreePrimitiveTag, aName);
813 ++myFreePrimitiveTag;
817 } else if (aShape.ShapeType() == TopAbs_WIRE) {
818 TopTools_IndexedMapOfShape Edges;
819 BRepTools::Map3DEdges(aShape, Edges);
820 if (Edges.Extent() == 1) {
821 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
822 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
823 for (; expl.More(); expl.Next()) {
824 builder(myFreePrimitiveTag)->Generated(expl.Current());
825 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
826 aName = theName + "_" + aStr.ToCString();
827 buildName(myFreePrimitiveTag, aName);
828 ++myFreePrimitiveTag;
831 TopExp_Explorer expl(aShape, TopAbs_EDGE);
832 for (; expl.More(); expl.Next()) {
833 builder(myFreePrimitiveTag)->Generated(expl.Current());
834 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
835 aName = theName + "_" + aStr.ToCString();
836 buildName(myFreePrimitiveTag, aName);
837 ++myFreePrimitiveTag;
839 // and load generated vertices.
840 TopTools_DataMapOfShapeShape generated;
841 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
843 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
844 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
847 } else if (aShape.ShapeType() == TopAbs_EDGE) {
848 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
849 for (; expl.More(); expl.Next()) {
850 builder(myFreePrimitiveTag)->Generated(expl.Current());
851 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
852 aName = theName + "_" + aStr.ToCString();
853 buildName(myFreePrimitiveTag, aName);
854 ++myFreePrimitiveTag;
859 //=======================================================================
860 int findAmbiguities(const TopoDS_Shape& theShapeIn,
861 TopTools_ListOfShape& theList)
864 // edges -> ancestor faces list
865 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
866 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
867 // keeps the shapes which are already in the resulting list
868 TopTools_MapOfShape alreadyThere;
869 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
870 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
872 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
873 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
874 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
875 if (ancestors.Extent() < 2)
877 Standard_Integer anID = 0;
878 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
879 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
881 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
882 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
883 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
884 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
885 for(; aSameEdge.More(); aSameEdge.Next()) {
886 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
887 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
888 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
891 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
892 for(; aFaceIter1.More(); aFaceIter1.Next()) {
893 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
894 for(; aFaceIter2.More(); aFaceIter2.Next()) {
895 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
898 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
901 if (!aFaceIter1.More()) { // all the faces are same => put to the result
902 if (alreadyThere.Add(aSameEdge.Value()))
903 theList.Append(aSameEdge.Value());
904 if (alreadyThere.Add(anAncestorsIter.Key()))
905 theList.Append(anAncestorsIter.Key());
908 } else { // ID is unique, just add this edge
909 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
911 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
913 return theList.Extent();
916 //=======================================================================
917 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
919 if(theShape->isNull()) return;
920 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
922 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
923 TopoDS_Iterator itr(aShape);
924 for (; itr.More(); itr.Next()) {
925 builder(myFreePrimitiveTag)->Generated(itr.Value());
926 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
927 aName = theName + "_" + aStr.ToCString();
928 buildName(myFreePrimitiveTag, aName);
929 ++myFreePrimitiveTag;
930 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
931 itr.Value().ShapeType() == TopAbs_COMPSOLID)
933 GeomShapePtr itrShape(new GeomAPI_Shape());
934 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
935 loadFirstLevel(itrShape, theName);
937 GeomShapePtr itrShape(new GeomAPI_Shape());
938 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
939 loadNextLevels(itrShape, theName);
943 GeomShapePtr itrShape(new GeomAPI_Shape());
944 itrShape->setImpl(new TopoDS_Shape(aShape));
945 loadNextLevels(itrShape, theName);
947 TopTools_ListOfShape aList;
948 if(findAmbiguities(aShape, aList)) {
949 TopTools_ListIteratorOfListOfShape it(aList);
950 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
951 builder(myFreePrimitiveTag)->Generated(it.Value());
952 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
953 aName = theName + "_" + aStr.ToCString();
954 buildName(myFreePrimitiveTag, aName);
959 GeomShapePtr Model_BodyBuilder::shape()
961 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
962 if (aData && aData->isValid()) {
963 TDF_Label aShapeLab = aData->shapeLab();
964 Handle(TDF_Reference) aRef;
965 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
966 aShapeLab = aRef->Get();
968 Handle(TNaming_NamedShape) aName;
969 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
970 TopoDS_Shape aShape = aName->Get();
971 if (!aShape.IsNull()) {
972 GeomShapePtr aRes(new GeomAPI_Shape);
973 aRes->setImpl(new TopoDS_Shape(aShape));
978 return GeomShapePtr();