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_Error.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 if (myTmpContext.get() || myTmpSubShape.get()) {
185 return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
188 std::shared_ptr<GeomAPI_Shape> aResult;
189 TDF_Label aSelLab = selectionLabel();
190 if (aSelLab.IsAttribute(kINVALID_SELECTION))
193 if (myRef.isInitialized()) {
194 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
195 ResultPtr aContext = context();
197 return aResult; // empty result
198 return aContext->shape();
200 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
201 return aResult; // empty result
203 if (aSelLab.IsAttribute(kPART_REF_ID)) {
204 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
205 if (!aPart.get() || !aPart->isActivated())
206 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
207 Handle(TDataStd_Integer) anIndex;
208 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
209 if (anIndex->Get()) { // special selection attribute was created, use it
210 return aPart->selectionValue(anIndex->Get());
211 } else { // face with name is already in the data model, so try to take it by name
212 Handle(TDataStd_Name) aName;
213 if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
214 std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
215 std::size_t aPartEnd = aSubShapeName.find('/');
216 if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
217 string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
219 std::string aType; // to reuse already existing selection the type is not needed
220 return aPart->shapeInPart(aNameInPart, aType, anIndex);
227 Handle(TNaming_NamedShape) aSelection;
228 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
229 TopoDS_Shape aSelShape = aSelection->Get();
230 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
231 aResult->setImpl(new TopoDS_Shape(aSelShape));
232 } else { // for simple construction element: just shape of this construction element
233 ResultConstructionPtr aConstr =
234 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
236 return aConstr->shape();
243 bool Model_AttributeSelection::isInvalid()
245 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
248 bool Model_AttributeSelection::isInitialized()
250 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
251 std::shared_ptr<GeomAPI_Shape> aResult;
252 if (myRef.isInitialized()) {
253 TDF_Label aSelLab = selectionLabel();
254 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
255 ResultPtr aContext = context();
256 return aContext.get() != NULL;
258 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
262 Handle(TNaming_NamedShape) aSelection;
263 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
264 return !aSelection->Get().IsNull();
265 } else { // for simple construction element: just shape of this construction element
266 ResultConstructionPtr aConstr =
267 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
269 return aConstr->shape().get() != NULL;
277 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
280 myIsInitialized = myRef.isInitialized();
283 void Model_AttributeSelection::setID(const std::string theID)
286 ModelAPI_AttributeSelection::setID(theID);
289 ResultPtr Model_AttributeSelection::context() {
290 if (myTmpContext.get() || myTmpSubShape.get()) {
294 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
295 // for parts there could be same-data result, so take the last enabled
296 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
297 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
298 for(int a = aSize - 1; a >= 0; a--) {
299 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
300 if (aPart.get() && aPart->data() == aResult->data()) {
301 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
302 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
303 // check that this result is not this-feature result (it is forbidden t oselect itself)
304 if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
314 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
316 ModelAPI_AttributeSelection::setObject(theObject);
317 myRef.setObject(theObject);
320 TDF_LabelMap& Model_AttributeSelection::scope()
322 if (myScope.IsEmpty()) { // create a new scope if not yet done
323 // gets all features with named shapes that are before this feature label (before in history)
324 DocumentPtr aMyDoc = owner()->document();
325 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
326 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
327 bool aMePassed = false;
328 CompositeFeaturePtr aComposite =
329 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
330 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
331 CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
332 if (aFeature.get()) {
333 aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
334 if (aCompositeOwner.get()) {
335 aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
338 // for group Scope is not limitet: this is always up to date objects
339 bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
340 for(; aFIter != allFeatures.end(); aFIter++) {
341 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
345 if (isGroup) aMePassed = false;
346 bool isInScope = !aMePassed;
347 if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
348 if (aComposite->isSub(*aFIter))
351 // remove the composite-owner of this feature (sketch in extrusion-cut)
352 if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
355 if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
356 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
357 (*aFIter)->data())->label().Father();
358 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
359 for(; aNSIter.More(); aNSIter.Next()) {
360 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
361 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
362 myScope.Add(aNS->Label());
371 /// produces theEdge orientation relatively to theContext face
372 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
374 if (theContext.ShapeType() != TopAbs_FACE)
376 TopoDS_Face aContext = TopoDS::Face(theContext);
377 if (theEdge.Orientation() == TopAbs_FORWARD)
379 if (theEdge.Orientation() == TopAbs_REVERSED)
384 /// Sets the invalid flag if flag is false, or removes it if "true"
386 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
388 theLab.ForgetAttribute(kINVALID_SELECTION);
390 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
395 bool Model_AttributeSelection::update()
397 TDF_Label aSelLab = selectionLabel();
398 ResultPtr aContext = context();
400 return setInvalidIfFalse(aSelLab, false);
401 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
402 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
404 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
405 // if there is a sketch, the sketch-naming must be updated
406 ResultConstructionPtr aConstruction =
407 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
408 if (!aConstruction->isInfinite()) {
409 BRep_Builder aCompoundBuilder;
410 TopoDS_Compound aComp;
411 aCompoundBuilder.MakeCompound(aComp);
412 for(int a = 0; a < aConstruction->facesNum(); a++) {
413 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
414 aCompoundBuilder.Add(aComp, aFace);
416 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
417 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
418 selectConstruction(aContext, aShape);
420 // For correct naming selection, put the shape into the naming structure.
421 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
422 TNaming_Builder aBuilder(aSelLab);
423 aBuilder.Generated(aContext->shape()->impl<TopoDS_Shape>());
424 std::shared_ptr<Model_Document> aMyDoc =
425 std::dynamic_pointer_cast<Model_Document>(owner()->document());
426 std::string aName = aContext->data()->name();
427 aMyDoc->addNamingName(aSelLab, aName);
428 TDataStd_Name::Set(aSelLab, aName.c_str());
430 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
433 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
434 std::shared_ptr<GeomAPI_Shape> aNoSelection;
435 bool aResult = selectPart(aContext, aNoSelection, true);
437 owner()->data()->sendAttributeUpdated(this);
439 return setInvalidIfFalse(aSelLab, aResult);
442 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
443 // body: just a named shape, use selection mechanism from OCCT
444 TNaming_Selector aSelector(aSelLab);
445 bool aResult = aSelector.Solve(scope()) == Standard_True;
446 owner()->data()->sendAttributeUpdated(this);
447 return setInvalidIfFalse(aSelLab, aResult);
448 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
449 // construction: identification by the results indexes, recompute faces and
450 // take the face that more close by the indexes
451 ResultConstructionPtr aConstructionContext =
452 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
453 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
454 // sketch sub-element
455 if (aConstructionContext &&
456 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
458 TDF_Label aLab = myRef.myRef->Label();
459 // getting a type of selected shape
460 Handle(TDataStd_Integer) aTypeAttr;
461 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
462 return setInvalidIfFalse(aSelLab, false);
464 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
465 // selected indexes will be needed in each "if"
466 Handle(TDataStd_IntPackedMap) aSubIds;
467 std::shared_ptr<GeomAPI_Shape> aNewSelected;
469 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
470 // for now working only with composite features
471 CompositeFeaturePtr aComposite =
472 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
473 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
474 return setInvalidIfFalse(aSelLab, false);
477 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
478 // If this is a wire with plane defined thin it is a sketch-like object
479 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
480 return setInvalidIfFalse(aSelLab, false);
481 // if there is no edges indexes, any face can be used: take the first
482 std::shared_ptr<GeomAPI_Shape> aNewSelected;
484 aNewSelected = aConstructionContext->face(0);
485 } else { // searching for most looks-like initial face by the indexes
486 // prepare edges of the current result for the fast searching
487 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
488 const int aSubNum = aComposite->numberOfSubs();
489 for(int a = 0; a < aSubNum; a++) {
490 int aSubID = aComposite->subFeatureId(a);
491 if (aSubIds->Contains(aSubID)) {
492 FeaturePtr aSub = aComposite->subFeature(a);
493 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
494 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
495 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
496 ResultConstructionPtr aConstr =
497 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
498 if (aConstr->shape() && aConstr->shape()->isEdge()) {
499 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
500 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
501 if (!anEdge.IsNull()) {
502 Standard_Real aFirst, aLast;
503 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
504 // searching for orientation information
506 Handle(TDataStd_Integer) anInt;
507 if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
508 anOrient = anInt->Get();
510 allCurves.Bind(aCurve, anOrient);
516 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
517 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
518 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
519 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
521 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
522 TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
523 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
524 for(; anEdgesExp.More(); anEdgesExp.Next()) {
525 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
526 if (!anEdge.IsNull()) {
527 Standard_Real aFirst, aLast;
528 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
529 if (alreadyProcessed.Contains(aCurve))
531 alreadyProcessed.Add(aCurve);
532 if (allCurves.IsBound(aCurve)) {
534 int anOrient = allCurves.Find(aCurve);
535 if (anOrient != 0) { // extra comparision score is orientation
536 if (edgeOrientation(aFace, anEdge) == anOrient)
544 if (aFound + aNotFound != 0) {
545 if (aFound > aBestFound ||
546 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
548 aBestOrient = aSameOrientation;
549 aNewSelected = aConstructionContext->face(aFaceIndex);
554 if (aNewSelected) { // store this new selection
555 selectConstruction(aContext, aNewSelected);
556 owner()->data()->sendAttributeUpdated(this);
557 return setInvalidIfFalse(aSelLab, true);
558 } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
559 TNaming_Builder anEmptyBuilder(selectionLabel());
560 return setInvalidIfFalse(aSelLab, false);
562 } else if (aShapeType == TopAbs_EDGE) {
563 // just reselect the edge by the id
564 const int aSubNum = aComposite->numberOfSubs();
565 for(int a = 0; a < aSubNum; a++) {
566 // if aSubIds take any, the first appropriate
567 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
568 // found the appropriate feature
569 FeaturePtr aFeature = aComposite->subFeature(a);
570 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
571 aFeature->results().cbegin();
572 for(;aResIter != aFeature->results().cend(); aResIter++) {
573 ResultConstructionPtr aRes =
574 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
575 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
576 selectConstruction(aContext, aRes->shape());
577 owner()->data()->sendAttributeUpdated(this);
578 return setInvalidIfFalse(aSelLab, true);
583 } else if (aShapeType == TopAbs_VERTEX) {
584 // just reselect the vertex by the id of edge
585 const int aSubNum = aComposite->numberOfSubs();
586 for(int a = 0; a < aSubNum; a++) {
587 // if aSubIds take any, the first appropriate
588 int aFeatureID = aComposite->subFeatureId(a);
589 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
590 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
591 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
592 // searching for deltas
594 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
595 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
596 // found the feature with appropriate edge
597 FeaturePtr aFeature = aComposite->subFeature(a);
598 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
599 aFeature->results().cbegin();
600 for(;aResIter != aFeature->results().cend(); aResIter++) {
601 ResultConstructionPtr aRes =
602 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
603 if (aRes && aRes->shape()) {
604 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
605 selectConstruction(aContext, aRes->shape());
606 owner()->data()->sendAttributeUpdated(this);
607 return setInvalidIfFalse(aSelLab, true);
608 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
609 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
611 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
612 if (aVIndex == aVertexNum) { // found!
613 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
614 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
615 selectConstruction(aContext, aVertex);
616 owner()->data()->sendAttributeUpdated(this);
617 return setInvalidIfFalse(aSelLab, true);
627 } else { // simple construction element: the selected is that needed
628 selectConstruction(aContext, aContext->shape());
629 owner()->data()->sendAttributeUpdated(this);
630 return setInvalidIfFalse(aSelLab, true);
633 return setInvalidIfFalse(aSelLab, false); // unknown case
637 void Model_AttributeSelection::selectBody(
638 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
640 // perform the selection
641 TNaming_Selector aSel(selectionLabel());
642 TopoDS_Shape aContext;
644 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
646 aContext = aBody->shape()->impl<TopoDS_Shape>();
649 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
651 aContext = aResult->shape()->impl<TopoDS_Shape>();
653 Events_Error::send("A result with shape is expected");
657 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
658 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
659 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
660 if (aFeatureOwner.get())
661 aFeatureOwner->eraseResults();
662 if (!aContext.IsNull()) {
663 aSel.Select(aNewShape, aContext);
667 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
668 /// if theID is zero,
669 /// theOrientation is additional information about the positioning of edge relatively to face
670 /// it is stored in the integer attribute of the edge sub-label:
671 /// -1 is out, 1 is in, 0 is not needed
672 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
673 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
674 std::string theAdditionalName, std::map<int, int>& theOrientations,
675 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
676 const int theOrientation = 0)
678 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
679 if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
680 TDataStd_Integer::Set(aLab, theOrientation);
682 TNaming_Builder aBuilder(aLab);
683 aBuilder.Generated(theShape);
684 std::stringstream aName;
685 aName<<theContextFeature->name()<<"/";
686 if (!theAdditionalName.empty())
687 aName<<theAdditionalName<<"/";
688 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
689 else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
690 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
691 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
693 if (theRefs.IsNull()) {
695 if (theOrientation == 1)
697 else if (theOrientation == -1)
699 } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
700 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
701 for(; aRef.More(); aRef.Next()) {
702 aName<<"-"<<aRef.Key();
703 if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
704 if (theOrientations[aRef.Key()] == 1)
706 else if (theOrientations[aRef.Key()] == -1)
712 theDoc->addNamingName(aLab, aName.str());
713 TDataStd_Name::Set(aLab, aName.str().c_str());
716 void Model_AttributeSelection::selectConstruction(
717 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
719 std::shared_ptr<Model_Document> aMyDoc =
720 std::dynamic_pointer_cast<Model_Document>(owner()->document());
721 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
722 CompositeFeaturePtr aComposite =
723 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
724 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
725 if (!aComposite || aComposite->numberOfSubs() == 0) {
726 // saving of context is enough: result construction contains exactly the needed shape
727 TNaming_Builder aBuilder(selectionLabel());
728 aBuilder.Generated(aSubShape);
729 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
730 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
733 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
734 TDF_Label aLab = myRef.myRef->Label();
735 // identify the results of sub-object of the composite by edges
736 // save type of the selected shape in integer attribute
737 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
738 TDataStd_Integer::Set(aLab, (int)aShapeType);
740 TColStd_MapOfTransient allCurves;
741 if (aShapeType == TopAbs_VERTEX) { // compare positions
742 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
744 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
745 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
746 Standard_Real aFirst, aLast;
747 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
748 allCurves.Add(aCurve);
751 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
752 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
753 std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
755 const int aSubNum = aComposite->numberOfSubs();
756 for(int a = 0; a < aSubNum; a++) {
757 FeaturePtr aSub = aComposite->subFeature(a);
758 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
759 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
760 // there may be many shapes (circle and center): register if at least one is in selection
761 for(; aRes != aResults.cend(); aRes++) {
762 ResultConstructionPtr aConstr =
763 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
764 if (!aConstr->shape()) {
767 if (aShapeType == TopAbs_VERTEX) {
768 if (aConstr->shape()->isVertex()) { // compare vertices positions
769 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
770 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
771 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
772 aRefs->Add(aComposite->subFeatureId(a));
774 } else { // get first or last vertex of the edge: last is stored with negative sign
775 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
776 int aDelta = kSTART_VERTEX_DELTA;
777 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
778 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
779 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
780 aRefs->Add(aDelta + aComposite->subFeatureId(a));
783 aDelta += kSTART_VERTEX_DELTA;
787 if (aConstr->shape()->isEdge()) {
788 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
789 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
790 if (!anEdge.IsNull()) {
791 Standard_Real aFirst, aLast;
792 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
793 if (allCurves.Contains(aCurve)) {
794 int anID = aComposite->subFeatureId(a);
796 if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
797 // add edges to sub-label to support naming for edges selection
798 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
799 for(; anEdgeExp.More(); anEdgeExp.Next()) {
800 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
801 Standard_Real aFirst, aLast;
802 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
803 if (aFaceCurve == aCurve) {
804 int anOrient = edgeOrientation(aSubShape, anEdge);
805 anOrientations[anID] = anOrient;
807 selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
808 Handle(TDataStd_IntPackedMap)(), anOrient);
811 } else { // put vertices of the selected edge to sub-labels
812 // add edges to sub-label to support naming for edges selection
813 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
814 int aTagIndex = anID + kSTART_VERTEX_DELTA;
815 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
816 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
818 std::stringstream anAdditionalName;
820 selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
829 // store the selected as primitive
830 TNaming_Builder aBuilder(selectionLabel());
831 aBuilder.Generated(aSubShape);
833 selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs);
836 bool Model_AttributeSelection::selectPart(
837 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
838 const bool theUpdate)
840 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
841 if (!aPart.get() || !aPart->isActivated())
842 return true; // postponed naming
844 Handle(TDataStd_Integer) anIndex;
845 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
846 if (anIndex->Get() > 0) {
847 // update the selection by index
848 return aPart->updateInPart(anIndex->Get());
850 return true; // nothing to do, referencing just by name
853 return true; // nothing to do, referencing just by name
855 // store the shape (in case part is not loaded it should be useful
857 std::string aName = theContext->data()->name();
858 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
859 aShape = theContext->shape()->impl<TopoDS_Shape>();
861 aShape = theSubShape->impl<TopoDS_Shape>();
863 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
864 TDataStd_Integer::Set(selectionLabel(), anIndex);
866 TNaming_Builder aBuilder(selectionLabel());
867 aBuilder.Select(aShape, aShape);
868 // identify by name in the part
869 TDataStd_Name::Set(selectionLabel(), aName.c_str());
870 return !aName.empty();
873 TDF_Label Model_AttributeSelection::selectionLabel()
875 return myRef.myRef->Label().FindChild(1);
878 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
880 std::string aName("");
881 if(!this->isInitialized())
882 return !theDefaultName.empty() ? theDefaultName : aName;
883 Handle(TDataStd_Name) anAtt;
884 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
885 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
889 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
890 ResultPtr aCont = context();
892 Model_SelectionNaming aSelNaming(selectionLabel());
893 return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
896 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
897 void Model_AttributeSelection::selectSubShape(
898 const std::string& theType, const std::string& theSubShapeName)
900 if(theSubShapeName.empty() || theType.empty()) return;
902 // check this is Part-name: 2 delimiters in the name
903 std::size_t aPartEnd = theSubShapeName.find('/');
904 if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
905 std::string aPartName = theSubShapeName.substr(0, aPartEnd);
906 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
907 if (aFound.get()) { // found such part, so asking it for the name
908 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
909 string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
911 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
912 if (aSelected.get()) {
913 setValue(aPart, aSelected);
914 TDataStd_Integer::Set(selectionLabel(), anIndex);
920 Model_SelectionNaming aSelNaming(selectionLabel());
921 std::shared_ptr<Model_Document> aDoc =
922 std::dynamic_pointer_cast<Model_Document>(owner()->document());
923 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
925 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
926 setValue(aCont, aShapeToBeSelected);
930 int Model_AttributeSelection::Id()
933 std::shared_ptr<GeomAPI_Shape> aSelection = value();
934 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
935 // support for compsolids:
936 if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
937 aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
940 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
941 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
942 // searching for the latest main shape
943 if (aSelection && !aSelection->isNull() &&
944 aContext && !aContext->isNull())
946 std::shared_ptr<Model_Document> aDoc =
947 std::dynamic_pointer_cast<Model_Document>(context()->document());
949 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
951 aMainShape = TNaming_Tool::CurrentShape(aNS);
955 TopTools_IndexedMapOfShape aSubShapesMap;
956 TopExp::MapShapes(aMainShape, aSubShapesMap);
957 anID = aSubShapesMap.FindIndex(aSubShape);