1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_AttributeSelection.cpp
5 // Author: Mikhail PONIKAROV
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <ModelAPI_Feature.h>
14 #include <ModelAPI_ResultBody.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_ResultPart.h>
17 #include <ModelAPI_CompositeFeature.h>
18 #include <ModelAPI_Tools.h>
19 #include <GeomAPI_Shape.h>
20 #include <GeomAPI_PlanarEdges.h>
21 #include <Events_InfoMessage.h>
23 #include <TNaming_Selector.hxx>
24 #include <TNaming_NamedShape.hxx>
25 #include <TNaming_Tool.hxx>
26 #include <TNaming_Builder.hxx>
27 #include <TNaming_Localizer.hxx>
28 #include <TopoDS_Shape.hxx>
29 #include <TopoDS_Compound.hxx>
30 #include <TDataStd_IntPackedMap.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_UAttribute.hxx>
33 #include <TDataStd_Name.hxx>
34 #include <TopTools_MapOfShape.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_MapIteratorOfMapOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <NCollection_DataMap.hxx>
39 #include <TopExp_Explorer.hxx>
40 #include <TDF_LabelMap.hxx>
41 #include <BRep_Tool.hxx>
42 #include <BRep_Builder.hxx>
43 #include <TopoDS_Edge.hxx>
46 #include <TColStd_MapOfTransient.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
51 #include <Precision.hxx>
52 #include <TDF_ChildIterator.hxx>
53 #include <TDF_ChildIDIterator.hxx>
54 #include <TDataStd_Name.hxx>
55 #include <TopAbs_ShapeEnum.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <TNaming_Iterator.hxx>
58 #include <BRep_Builder.hxx>
60 //#define DEB_NAMING 1
62 #include <BRepTools.hxx>
64 /// added to the index in the packed map to signalize that the vertex of edge is selected
65 /// (multiplied by the index of the edge)
66 static const int kSTART_VERTEX_DELTA = 1000000;
67 // identifier that there is simple reference: selection equals to context
68 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
69 // simple reference in the construction
70 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
71 // reference to Part sub-object
72 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
73 // selection is invalid after recomputation
74 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
76 // on this label is stored:
77 // TNaming_NamedShape - selected shape
78 // TNaming_Naming - topological selection information (for the body)
79 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
80 // TDataStd_Integer - type of the selected shape (for construction)
81 // TDF_Reference - from ReferenceAttribute, the context
82 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
83 const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
85 if (theTemporarily) { // just keep the stored without DF update
86 myTmpContext = theContext;
87 myTmpSubShape = theSubShape;
88 owner()->data()->sendAttributeUpdated(this);
92 myTmpSubShape.reset();
95 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
96 bool isOldContext = theContext == myRef.value();
97 bool isOldShape = isOldContext &&
98 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
99 if (isOldShape) return; // shape is the same, so context is also unchanged
100 // update the referenced object if needed
102 myRef.setValue(theContext);
105 // do noth use naming if selected shape is result shape itself, but not sub-shape
106 TDF_Label aSelLab = selectionLabel();
107 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
108 aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
109 aSelLab.ForgetAttribute(kINVALID_SELECTION);
111 bool isDegeneratedEdge = false;
112 // do not use the degenerated edge as a shape, a null context and shape is used in the case
113 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
114 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
115 if (aSubShape.ShapeType() == TopAbs_EDGE)
116 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
118 if (!theContext.get() || isDegeneratedEdge) {
119 // to keep the reference attribute label
120 TDF_Label aRefLab = myRef.myRef->Label();
121 aSelLab.ForgetAllAttributes(true);
122 myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
125 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
126 // do not select the whole shape for body:it is already must be in the data framework
127 // equal and null selected objects mean the same: object is equal to context,
128 if (theContext->shape().get() &&
129 (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
130 aSelLab.ForgetAllAttributes(true);
131 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
133 selectBody(theContext, theSubShape);
135 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
136 if (!theSubShape.get()) {
137 // to sub, so the whole result is selected
138 aSelLab.ForgetAllAttributes(true);
139 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
140 ResultConstructionPtr aConstruction =
141 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
142 if (aConstruction->isInfinite()) {
143 // For correct naming selection, put the shape into the naming structure.
144 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
145 TNaming_Builder aBuilder(aSelLab);
146 aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
147 std::shared_ptr<Model_Document> aMyDoc =
148 std::dynamic_pointer_cast<Model_Document>(owner()->document());
149 std::string aName = theContext->data()->name();
150 aMyDoc->addNamingName(aSelLab, aName);
151 TDataStd_Name::Set(aSelLab, aName.c_str());
152 } else { // for sketch the naming is needed in DS
153 BRep_Builder aCompoundBuilder;
154 TopoDS_Compound aComp;
155 aCompoundBuilder.MakeCompound(aComp);
156 for(int a = 0; a < aConstruction->facesNum(); a++) {
157 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
158 aCompoundBuilder.Add(aComp, aFace);
160 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
161 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
162 selectConstruction(theContext, aShape);
165 selectConstruction(theContext, theSubShape);
167 } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
168 aSelLab.ForgetAllAttributes(true);
169 TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
170 selectPart(theContext, theSubShape);
172 //the attribute initialized state should be changed by sendAttributeUpdated only
173 //myIsInitialized = true;
175 owner()->data()->sendAttributeUpdated(this);
177 std::string aSelName = namingName();
178 if(!aSelName.empty())
179 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
182 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
184 GeomShapePtr aResult;
185 if (myTmpContext.get() || myTmpSubShape.get()) {
186 ResultConstructionPtr aResulConstruction = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
187 if(aResulConstruction.get()) {
188 // it is just reference to construction.
189 return myTmpSubShape;
191 return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
194 TDF_Label aSelLab = selectionLabel();
195 if (aSelLab.IsAttribute(kINVALID_SELECTION))
198 if (myRef.isInitialized()) {
199 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
200 ResultPtr aContext = context();
202 return aResult; // empty result
203 return aContext->shape();
205 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
206 return aResult; // empty result
208 if (aSelLab.IsAttribute(kPART_REF_ID)) {
209 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
210 if (!aPart.get() || !aPart->isActivated())
211 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
212 Handle(TDataStd_Integer) anIndex;
213 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
214 if (anIndex->Get()) { // special selection attribute was created, use it
215 return aPart->selectionValue(anIndex->Get());
216 } else { // face with name is already in the data model, so try to take it by name
217 Handle(TDataStd_Name) aName;
218 if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
219 std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
220 std::size_t aPartEnd = aSubShapeName.find('/');
221 if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
222 string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
224 std::string aType; // to reuse already existing selection the type is not needed
225 return aPart->shapeInPart(aNameInPart, aType, anIndex);
232 Handle(TNaming_NamedShape) aSelection;
233 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
234 TopoDS_Shape aSelShape = aSelection->Get();
235 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
236 aResult->setImpl(new TopoDS_Shape(aSelShape));
237 } else { // for simple construction element: just shape of this construction element
238 ResultConstructionPtr aConstr =
239 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
241 return aConstr->shape();
248 bool Model_AttributeSelection::isInvalid()
250 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
253 bool Model_AttributeSelection::isInitialized()
255 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
256 std::shared_ptr<GeomAPI_Shape> aResult;
257 if (myRef.isInitialized()) {
258 TDF_Label aSelLab = selectionLabel();
259 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
260 ResultPtr aContext = context();
261 return aContext.get() != NULL;
263 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
267 Handle(TNaming_NamedShape) aSelection;
268 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
269 return !aSelection->Get().IsNull();
270 } else { // for simple construction element: just shape of this construction element
271 ResultConstructionPtr aConstr =
272 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
274 return aConstr->shape().get() != NULL;
282 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
285 myIsInitialized = myRef.isInitialized();
288 void Model_AttributeSelection::setID(const std::string theID)
291 ModelAPI_AttributeSelection::setID(theID);
294 ResultPtr Model_AttributeSelection::context() {
295 if (myTmpContext.get() || myTmpSubShape.get()) {
299 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
300 // for parts there could be same-data result, so take the last enabled
301 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
302 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
303 for(int a = aSize - 1; a >= 0; a--) {
304 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
305 if (aPart.get() && aPart->data() == aResult->data()) {
306 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
307 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
308 // check that this result is not this-feature result (it is forbidden t oselect itself)
309 if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
319 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
321 ModelAPI_AttributeSelection::setObject(theObject);
322 myRef.setObject(theObject);
325 TDF_LabelMap& Model_AttributeSelection::scope()
327 if (myScope.IsEmpty()) { // create a new scope if not yet done
328 // gets all features with named shapes that are before this feature label (before in history)
329 DocumentPtr aMyDoc = owner()->document();
330 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
331 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
332 bool aMePassed = false;
333 CompositeFeaturePtr aComposite =
334 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
335 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
336 CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
337 if (aFeature.get()) {
338 aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
339 if (aCompositeOwner.get()) {
340 aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
343 // for group Scope is not limitet: this is always up to date objects
344 bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
345 for(; aFIter != allFeatures.end(); aFIter++) {
346 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
350 if (isGroup) aMePassed = false;
351 bool isInScope = !aMePassed;
352 if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
353 if (aComposite->isSub(*aFIter))
356 // remove the composite-owner of this feature (sketch in extrusion-cut)
357 if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
360 if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
361 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
362 (*aFIter)->data())->label().Father();
363 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
364 for(; aNSIter.More(); aNSIter.Next()) {
365 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
366 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
367 myScope.Add(aNS->Label());
376 /// produces theEdge orientation relatively to theContext face
377 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
379 if (theContext.ShapeType() != TopAbs_FACE)
381 TopoDS_Face aContext = TopoDS::Face(theContext);
382 if (theEdge.Orientation() == TopAbs_FORWARD)
384 if (theEdge.Orientation() == TopAbs_REVERSED)
389 /// Sets the invalid flag if flag is false, or removes it if "true"
391 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
393 theLab.ForgetAttribute(kINVALID_SELECTION);
395 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
400 bool Model_AttributeSelection::update()
402 TDF_Label aSelLab = selectionLabel();
403 ResultPtr aContext = context();
405 return setInvalidIfFalse(aSelLab, false);
406 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
407 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
409 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
410 // if there is a sketch, the sketch-naming must be updated
411 ResultConstructionPtr aConstruction =
412 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
413 if (!aConstruction->isInfinite()) {
414 BRep_Builder aCompoundBuilder;
415 TopoDS_Compound aComp;
416 aCompoundBuilder.MakeCompound(aComp);
417 for(int a = 0; a < aConstruction->facesNum(); a++) {
418 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
419 aCompoundBuilder.Add(aComp, aFace);
421 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
422 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
423 selectConstruction(aContext, aShape);
425 // For correct naming selection, put the shape into the naming structure.
426 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
427 TNaming_Builder aBuilder(aSelLab);
428 aBuilder.Generated(aContext->shape()->impl<TopoDS_Shape>());
429 std::shared_ptr<Model_Document> aMyDoc =
430 std::dynamic_pointer_cast<Model_Document>(owner()->document());
431 std::string aName = aContext->data()->name();
432 aMyDoc->addNamingName(aSelLab, aName);
433 TDataStd_Name::Set(aSelLab, aName.c_str());
435 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
438 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
439 std::shared_ptr<GeomAPI_Shape> aNoSelection;
440 bool aResult = selectPart(aContext, aNoSelection, true);
441 aResult = setInvalidIfFalse(aSelLab, aResult);
443 owner()->data()->sendAttributeUpdated(this);
448 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
449 // body: just a named shape, use selection mechanism from OCCT
450 TNaming_Selector aSelector(aSelLab);
451 bool aResult = aSelector.Solve(scope()) == Standard_True;
452 aResult = setInvalidIfFalse(aSelLab, aResult); // must be before sending of updated attribute (1556)
453 owner()->data()->sendAttributeUpdated(this);
455 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
456 // construction: identification by the results indexes, recompute faces and
457 // take the face that more close by the indexes
458 ResultConstructionPtr aConstructionContext =
459 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
460 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
461 // sketch sub-element
462 if (aConstructionContext &&
463 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
465 TDF_Label aLab = myRef.myRef->Label();
466 // getting a type of selected shape
467 Handle(TDataStd_Integer) aTypeAttr;
468 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
469 return setInvalidIfFalse(aSelLab, false);
471 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
472 // selected indexes will be needed in each "if"
473 Handle(TDataStd_IntPackedMap) aSubIds;
474 std::shared_ptr<GeomAPI_Shape> aNewSelected;
476 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
477 // for now working only with composite features
478 CompositeFeaturePtr aComposite =
479 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
480 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
481 return setInvalidIfFalse(aSelLab, false);
484 if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) { // compound is for the whole sketch selection
485 // If this is a wire with plane defined then it is a sketch-like object
486 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
487 return setInvalidIfFalse(aSelLab, false);
488 // if there is no edges indexes, any face can be used: take the first
489 std::shared_ptr<GeomAPI_Shape> aNewSelected;
491 aNewSelected = aConstructionContext->face(0);
492 } else { // searching for most looks-like initial face by the indexes
493 // prepare edges of the current result for the fast searching
494 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
495 const int aSubNum = aComposite->numberOfSubs();
496 for(int a = 0; a < aSubNum; a++) {
497 int aSubID = aComposite->subFeatureId(a);
498 if (aSubIds->Contains(aSubID)) {
499 FeaturePtr aSub = aComposite->subFeature(a);
500 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
501 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
502 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
503 ResultConstructionPtr aConstr =
504 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
505 if (aConstr->shape() && aConstr->shape()->isEdge()) {
506 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
507 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
508 if (!anEdge.IsNull()) {
509 Standard_Real aFirst, aLast;
510 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
511 // searching for orientation information
513 Handle(TDataStd_Integer) anInt;
514 if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
515 anOrient = anInt->Get();
517 allCurves.Bind(aCurve, anOrient);
523 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
524 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
525 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
526 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
528 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
529 TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
530 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
531 for(; anEdgesExp.More(); anEdgesExp.Next()) {
532 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
533 if (!anEdge.IsNull()) {
534 Standard_Real aFirst, aLast;
535 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
536 if (alreadyProcessed.Contains(aCurve))
538 alreadyProcessed.Add(aCurve);
539 if (allCurves.IsBound(aCurve)) {
541 int anOrient = allCurves.Find(aCurve);
542 if (anOrient != 0) { // extra comparision score is orientation
543 if (edgeOrientation(aFace, anEdge) == anOrient)
551 if (aFound + aNotFound != 0) {
552 if (aFound > aBestFound ||
553 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
555 aBestOrient = aSameOrientation;
556 aNewSelected = aConstructionContext->face(aFaceIndex);
561 if (aNewSelected) { // store this new selection
562 if (aShapeType == TopAbs_WIRE) { // just get a wire from face to have wire
563 TopExp_Explorer aWireExp(aNewSelected->impl<TopoDS_Shape>(), TopAbs_WIRE);
564 if (aWireExp.More()) {
565 aNewSelected.reset(new GeomAPI_Shape);
566 aNewSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aWireExp.Current()));
569 selectConstruction(aContext, aNewSelected);
570 setInvalidIfFalse(aSelLab, true);
571 owner()->data()->sendAttributeUpdated(this);
573 } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
574 TNaming_Builder anEmptyBuilder(selectionLabel());
575 return setInvalidIfFalse(aSelLab, false);
577 } else if (aShapeType == TopAbs_EDGE) {
578 // just reselect the edge by the id
579 const int aSubNum = aComposite->numberOfSubs();
580 for(int a = 0; a < aSubNum; a++) {
581 // if aSubIds take any, the first appropriate
582 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
583 // found the appropriate feature
584 FeaturePtr aFeature = aComposite->subFeature(a);
585 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
586 aFeature->results().cbegin();
587 for(;aResIter != aFeature->results().cend(); aResIter++) {
588 ResultConstructionPtr aRes =
589 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
590 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
591 selectConstruction(aContext, aRes->shape());
592 setInvalidIfFalse(aSelLab, true);
593 owner()->data()->sendAttributeUpdated(this);
599 } else if (aShapeType == TopAbs_VERTEX) {
600 // just reselect the vertex by the id of edge
601 const int aSubNum = aComposite->numberOfSubs();
602 for(int a = 0; a < aSubNum; a++) {
603 // if aSubIds take any, the first appropriate
604 int aFeatureID = aComposite->subFeatureId(a);
605 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
606 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
607 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
608 // searching for deltas
610 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
611 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
612 // found the feature with appropriate edge
613 FeaturePtr aFeature = aComposite->subFeature(a);
614 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
615 aFeature->results().cbegin();
616 for(;aResIter != aFeature->results().cend(); aResIter++) {
617 ResultConstructionPtr aRes =
618 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
619 if (aRes && aRes->shape()) {
620 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
621 selectConstruction(aContext, aRes->shape());
622 setInvalidIfFalse(aSelLab, true);
623 owner()->data()->sendAttributeUpdated(this);
625 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
626 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
628 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
629 if (aVIndex == aVertexNum) { // found!
630 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
631 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
632 selectConstruction(aContext, aVertex);
633 setInvalidIfFalse(aSelLab, true);
634 owner()->data()->sendAttributeUpdated(this);
645 } else { // simple construction element: the selected is that needed
646 selectConstruction(aContext, aContext->shape());
647 setInvalidIfFalse(aSelLab, true);
648 owner()->data()->sendAttributeUpdated(this);
652 return setInvalidIfFalse(aSelLab, false); // unknown case
656 void Model_AttributeSelection::selectBody(
657 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
659 // perform the selection
660 TNaming_Selector aSel(selectionLabel());
661 TopoDS_Shape aContext;
663 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
665 aContext = aBody->shape()->impl<TopoDS_Shape>();
668 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
670 aContext = aResult->shape()->impl<TopoDS_Shape>();
672 Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
676 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
677 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
678 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
679 if (aFeatureOwner.get())
680 aFeatureOwner->eraseResults();
681 if (!aContext.IsNull()) {
682 aSel.Select(aNewShape, aContext);
686 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
687 /// if theID is zero,
688 /// theOrientation is additional information about the positioning of edge relatively to face
689 /// it is stored in the integer attribute of the edge sub-label:
690 /// -1 is out, 1 is in, 0 is not needed
691 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
692 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
693 std::string theAdditionalName, std::map<int, int>& theOrientations,
694 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
695 const int theOrientation = 0)
697 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
698 if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
699 TDataStd_Integer::Set(aLab, theOrientation);
701 TNaming_Builder aBuilder(aLab);
702 aBuilder.Generated(theShape);
703 std::stringstream aName;
704 aName<<theContextFeature->name()<<"/";
705 if (!theAdditionalName.empty())
706 aName<<theAdditionalName<<"/";
707 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
708 else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
709 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
710 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
712 if (theRefs.IsNull()) {
714 if (theOrientation == 1)
716 else if (theOrientation == -1)
718 } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
719 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
720 for(; aRef.More(); aRef.Next()) {
721 aName<<"-"<<aRef.Key();
722 if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
723 if (theOrientations[aRef.Key()] == 1)
725 else if (theOrientations[aRef.Key()] == -1)
731 theDoc->addNamingName(aLab, aName.str());
732 TDataStd_Name::Set(aLab, aName.str().c_str());
735 void Model_AttributeSelection::selectConstruction(
736 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
738 std::shared_ptr<Model_Document> aMyDoc =
739 std::dynamic_pointer_cast<Model_Document>(owner()->document());
740 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
741 CompositeFeaturePtr aComposite =
742 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
743 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
744 if (!aComposite || aComposite->numberOfSubs() == 0) {
745 // saving of context is enough: result construction contains exactly the needed shape
746 TNaming_Builder aBuilder(selectionLabel());
747 aBuilder.Generated(aSubShape);
748 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
749 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
752 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
753 TDF_Label aLab = myRef.myRef->Label();
754 // identify the results of sub-object of the composite by edges
755 // save type of the selected shape in integer attribute
756 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
757 TDataStd_Integer::Set(aLab, (int)aShapeType);
759 TColStd_MapOfTransient allCurves;
760 if (aShapeType == TopAbs_VERTEX) { // compare positions
761 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
763 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
764 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
765 Standard_Real aFirst, aLast;
766 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
767 allCurves.Add(aCurve);
770 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
771 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
772 std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
774 const int aSubNum = aComposite->numberOfSubs();
775 for(int a = 0; a < aSubNum; a++) {
776 FeaturePtr aSub = aComposite->subFeature(a);
777 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
778 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
779 // there may be many shapes (circle and center): register if at least one is in selection
780 for(; aRes != aResults.cend(); aRes++) {
781 ResultConstructionPtr aConstr =
782 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
783 if (!aConstr->shape()) {
786 if (aShapeType == TopAbs_VERTEX) {
787 if (aConstr->shape()->isVertex()) { // compare vertices positions
788 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
789 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
790 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
791 aRefs->Add(aComposite->subFeatureId(a));
793 } else { // get first or last vertex of the edge: last is stored with negative sign
794 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
795 int aDelta = kSTART_VERTEX_DELTA;
796 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
797 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
798 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
799 aRefs->Add(aDelta + aComposite->subFeatureId(a));
802 aDelta += kSTART_VERTEX_DELTA;
806 if (aConstr->shape()->isEdge()) {
807 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
808 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
809 if (!anEdge.IsNull()) {
810 Standard_Real aFirst, aLast;
811 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
812 if (allCurves.Contains(aCurve)) {
813 int anID = aComposite->subFeatureId(a);
815 if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
816 // add edges to sub-label to support naming for edges selection
817 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
818 for(; anEdgeExp.More(); anEdgeExp.Next()) {
819 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
820 Standard_Real aFirst, aLast;
821 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
822 if (aFaceCurve == aCurve) {
823 int anOrient = edgeOrientation(aSubShape, anEdge);
824 anOrientations[anID] = anOrient;
826 selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
827 Handle(TDataStd_IntPackedMap)(), anOrient);
830 } else { // put vertices of the selected edge to sub-labels
831 // add edges to sub-label to support naming for edges selection
832 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
833 int aTagIndex = anID + kSTART_VERTEX_DELTA;
834 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
835 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
837 std::stringstream anAdditionalName;
839 selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
848 // store the selected as primitive
849 TNaming_Builder aBuilder(selectionLabel());
850 aBuilder.Generated(aSubShape);
852 selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs);
855 bool Model_AttributeSelection::selectPart(
856 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
857 const bool theUpdate)
859 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
860 if (!aPart.get() || !aPart->isActivated())
861 return true; // postponed naming
863 Handle(TDataStd_Integer) anIndex;
864 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
865 if (anIndex->Get() > 0) {
866 // update the selection by index
867 return aPart->updateInPart(anIndex->Get());
869 return true; // nothing to do, referencing just by name
872 return true; // nothing to do, referencing just by name
874 // store the shape (in case part is not loaded it should be useful
876 std::string aName = theContext->data()->name();
877 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
878 aShape = theContext->shape()->impl<TopoDS_Shape>();
880 aShape = theSubShape->impl<TopoDS_Shape>();
882 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
883 TDataStd_Integer::Set(selectionLabel(), anIndex);
885 TNaming_Builder aBuilder(selectionLabel());
886 aBuilder.Select(aShape, aShape);
887 // identify by name in the part
888 TDataStd_Name::Set(selectionLabel(), aName.c_str());
889 return !aName.empty();
892 TDF_Label Model_AttributeSelection::selectionLabel()
894 return myRef.myRef->Label().FindChild(1);
897 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
899 std::string aName("");
900 if(!this->isInitialized())
901 return !theDefaultName.empty() ? theDefaultName : aName;
902 Handle(TDataStd_Name) anAtt;
903 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
904 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
908 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
909 ResultPtr aCont = context();
911 Model_SelectionNaming aSelNaming(selectionLabel());
912 return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
915 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
916 void Model_AttributeSelection::selectSubShape(
917 const std::string& theType, const std::string& theSubShapeName)
919 if(theSubShapeName.empty() || theType.empty()) return;
921 // check this is Part-name: 2 delimiters in the name
922 std::size_t aPartEnd = theSubShapeName.find('/');
923 if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
924 std::string aPartName = theSubShapeName.substr(0, aPartEnd);
925 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
926 if (aFound.get()) { // found such part, so asking it for the name
927 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
928 string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
930 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
931 if (aSelected.get()) {
932 setValue(aPart, aSelected);
933 TDataStd_Integer::Set(selectionLabel(), anIndex);
939 Model_SelectionNaming aSelNaming(selectionLabel());
940 std::shared_ptr<Model_Document> aDoc =
941 std::dynamic_pointer_cast<Model_Document>(owner()->document());
942 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
944 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
945 setValue(aCont, aShapeToBeSelected);
949 int Model_AttributeSelection::Id()
952 std::shared_ptr<GeomAPI_Shape> aSelection = value();
953 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
954 // support for compsolids:
955 if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
956 aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
959 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
960 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
961 // searching for the latest main shape
962 if (aSelection && !aSelection->isNull() &&
963 aContext && !aContext->isNull())
965 std::shared_ptr<Model_Document> aDoc =
966 std::dynamic_pointer_cast<Model_Document>(context()->document());
968 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
970 aMainShape = TNaming_Tool::CurrentShape(aNS);
974 TopTools_IndexedMapOfShape aSubShapesMap;
975 TopExp::MapShapes(aMainShape, aSubShapesMap);
976 anID = aSubShapesMap.FindIndex(aSubShape);
981 void Model_AttributeSelection::setId(int theID)
983 const ResultPtr& aContext = context();
984 std::shared_ptr<GeomAPI_Shape> aSelection;
986 std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
987 // support for compsolids:
988 if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
989 aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
991 TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
992 // searching for the latest main shape
994 aContextShape && !aContextShape->isNull())
996 std::shared_ptr<Model_Document> aDoc =
997 std::dynamic_pointer_cast<Model_Document>(aContext->document());
999 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1000 if (!aNS.IsNull()) {
1001 aMainShape = TNaming_Tool::CurrentShape(aNS);
1005 TopTools_IndexedMapOfShape aSubShapesMap;
1006 TopExp::MapShapes(aMainShape, aSubShapesMap);
1007 const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1009 std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1010 aResult->setImpl(new TopoDS_Shape(aSelShape));
1012 aSelection = aResult;
1015 setValue(aContext, aSelection);