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 return setInvalidIfFalse(aSelLab, selectPart(aContext, aNoSelection, true));
438 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
439 // body: just a named shape, use selection mechanism from OCCT
440 TNaming_Selector aSelector(aSelLab);
441 bool aResult = aSelector.Solve(scope()) == Standard_True;
442 owner()->data()->sendAttributeUpdated(this);
443 return setInvalidIfFalse(aSelLab, aResult);
444 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
445 // construction: identification by the results indexes, recompute faces and
446 // take the face that more close by the indexes
447 ResultConstructionPtr aConstructionContext =
448 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
449 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
450 // sketch sub-element
451 if (aConstructionContext &&
452 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
454 TDF_Label aLab = myRef.myRef->Label();
455 // getting a type of selected shape
456 Handle(TDataStd_Integer) aTypeAttr;
457 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
458 return setInvalidIfFalse(aSelLab, false);
460 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
461 // selected indexes will be needed in each "if"
462 Handle(TDataStd_IntPackedMap) aSubIds;
463 std::shared_ptr<GeomAPI_Shape> aNewSelected;
465 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
466 // for now working only with composite features
467 CompositeFeaturePtr aComposite =
468 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
469 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
470 return setInvalidIfFalse(aSelLab, false);
473 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
474 // If this is a wire with plane defined thin it is a sketch-like object
475 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
476 return setInvalidIfFalse(aSelLab, false);
477 // if there is no edges indexes, any face can be used: take the first
478 std::shared_ptr<GeomAPI_Shape> aNewSelected;
480 aNewSelected = aConstructionContext->face(0);
481 } else { // searching for most looks-like initial face by the indexes
482 // prepare edges of the current result for the fast searching
483 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
484 const int aSubNum = aComposite->numberOfSubs();
485 for(int a = 0; a < aSubNum; a++) {
486 int aSubID = aComposite->subFeatureId(a);
487 if (aSubIds->Contains(aSubID)) {
488 FeaturePtr aSub = aComposite->subFeature(a);
489 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
490 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
491 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
492 ResultConstructionPtr aConstr =
493 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
494 if (aConstr->shape() && aConstr->shape()->isEdge()) {
495 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
496 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
497 if (!anEdge.IsNull()) {
498 Standard_Real aFirst, aLast;
499 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
500 // searching for orientation information
502 Handle(TDataStd_Integer) anInt;
503 if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
504 anOrient = anInt->Get();
506 allCurves.Bind(aCurve, anOrient);
512 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
513 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
514 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
515 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
517 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
518 TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
519 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
520 for(; anEdgesExp.More(); anEdgesExp.Next()) {
521 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
522 if (!anEdge.IsNull()) {
523 Standard_Real aFirst, aLast;
524 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
525 if (alreadyProcessed.Contains(aCurve))
527 alreadyProcessed.Add(aCurve);
528 if (allCurves.IsBound(aCurve)) {
530 int anOrient = allCurves.Find(aCurve);
531 if (anOrient != 0) { // extra comparision score is orientation
532 if (edgeOrientation(aFace, anEdge) == anOrient)
540 if (aFound + aNotFound != 0) {
541 if (aFound > aBestFound ||
542 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
544 aBestOrient = aSameOrientation;
545 aNewSelected = aConstructionContext->face(aFaceIndex);
550 if (aNewSelected) { // store this new selection
551 selectConstruction(aContext, aNewSelected);
552 owner()->data()->sendAttributeUpdated(this);
553 return setInvalidIfFalse(aSelLab, true);
554 } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
555 TNaming_Builder anEmptyBuilder(selectionLabel());
556 return setInvalidIfFalse(aSelLab, false);
558 } else if (aShapeType == TopAbs_EDGE) {
559 // just reselect the edge by the id
560 const int aSubNum = aComposite->numberOfSubs();
561 for(int a = 0; a < aSubNum; a++) {
562 // if aSubIds take any, the first appropriate
563 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
564 // found the appropriate feature
565 FeaturePtr aFeature = aComposite->subFeature(a);
566 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
567 aFeature->results().cbegin();
568 for(;aResIter != aFeature->results().cend(); aResIter++) {
569 ResultConstructionPtr aRes =
570 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
571 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
572 selectConstruction(aContext, aRes->shape());
573 owner()->data()->sendAttributeUpdated(this);
574 return setInvalidIfFalse(aSelLab, true);
579 } else if (aShapeType == TopAbs_VERTEX) {
580 // just reselect the vertex by the id of edge
581 const int aSubNum = aComposite->numberOfSubs();
582 for(int a = 0; a < aSubNum; a++) {
583 // if aSubIds take any, the first appropriate
584 int aFeatureID = aComposite->subFeatureId(a);
585 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
586 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
587 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
588 // searching for deltas
590 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
591 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
592 // found the feature with appropriate edge
593 FeaturePtr aFeature = aComposite->subFeature(a);
594 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
595 aFeature->results().cbegin();
596 for(;aResIter != aFeature->results().cend(); aResIter++) {
597 ResultConstructionPtr aRes =
598 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
599 if (aRes && aRes->shape()) {
600 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
601 selectConstruction(aContext, aRes->shape());
602 owner()->data()->sendAttributeUpdated(this);
603 return setInvalidIfFalse(aSelLab, true);
604 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
605 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
607 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
608 if (aVIndex == aVertexNum) { // found!
609 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
610 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
611 selectConstruction(aContext, aVertex);
612 owner()->data()->sendAttributeUpdated(this);
613 return setInvalidIfFalse(aSelLab, true);
623 } else { // simple construction element: the selected is that needed
624 selectConstruction(aContext, aContext->shape());
625 owner()->data()->sendAttributeUpdated(this);
626 return setInvalidIfFalse(aSelLab, true);
629 return setInvalidIfFalse(aSelLab, false); // unknown case
633 void Model_AttributeSelection::selectBody(
634 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
636 // perform the selection
637 TNaming_Selector aSel(selectionLabel());
638 TopoDS_Shape aContext;
640 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
642 aContext = aBody->shape()->impl<TopoDS_Shape>();
645 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
647 aContext = aResult->shape()->impl<TopoDS_Shape>();
649 Events_Error::send("A result with shape is expected");
653 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
654 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
655 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
656 if (aFeatureOwner.get())
657 aFeatureOwner->eraseResults();
658 if (!aContext.IsNull()) {
659 aSel.Select(aNewShape, aContext);
663 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
664 /// if theID is zero,
665 /// theOrientation is additional information about the positioning of edge relatively to face
666 /// it is stored in the integer attribute of the edge sub-label:
667 /// -1 is out, 1 is in, 0 is not needed
668 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
669 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
670 std::string theAdditionalName, std::map<int, int>& theOrientations,
671 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
672 const int theOrientation = 0)
674 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
675 if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
676 TDataStd_Integer::Set(aLab, theOrientation);
678 TNaming_Builder aBuilder(aLab);
679 aBuilder.Generated(theShape);
680 std::stringstream aName;
681 aName<<theContextFeature->name()<<"/";
682 if (!theAdditionalName.empty())
683 aName<<theAdditionalName<<"/";
684 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
685 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
686 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
688 if (theRefs.IsNull()) {
690 if (theOrientation == 1)
692 else if (theOrientation == -1)
694 } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
695 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
696 for(; aRef.More(); aRef.Next()) {
697 aName<<"-"<<aRef.Key();
698 if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
699 if (theOrientations[aRef.Key()] == 1)
701 else if (theOrientations[aRef.Key()] == -1)
707 theDoc->addNamingName(aLab, aName.str());
708 TDataStd_Name::Set(aLab, aName.str().c_str());
711 void Model_AttributeSelection::selectConstruction(
712 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
714 std::shared_ptr<Model_Document> aMyDoc =
715 std::dynamic_pointer_cast<Model_Document>(owner()->document());
716 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
717 CompositeFeaturePtr aComposite =
718 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
719 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
720 if (!aComposite || aComposite->numberOfSubs() == 0) {
721 // saving of context is enough: result construction contains exactly the needed shape
722 TNaming_Builder aBuilder(selectionLabel());
723 aBuilder.Generated(aSubShape);
724 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
725 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
728 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
729 TDF_Label aLab = myRef.myRef->Label();
730 // identify the results of sub-object of the composite by edges
731 // save type of the selected shape in integer attribute
732 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
733 TDataStd_Integer::Set(aLab, (int)aShapeType);
735 TColStd_MapOfTransient allCurves;
736 if (aShapeType == TopAbs_VERTEX) { // compare positions
737 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
739 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
740 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
741 Standard_Real aFirst, aLast;
742 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
743 allCurves.Add(aCurve);
746 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
747 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
748 std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
750 const int aSubNum = aComposite->numberOfSubs();
751 for(int a = 0; a < aSubNum; a++) {
752 FeaturePtr aSub = aComposite->subFeature(a);
753 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
754 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
755 // there may be many shapes (circle and center): register if at least one is in selection
756 for(; aRes != aResults.cend(); aRes++) {
757 ResultConstructionPtr aConstr =
758 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
759 if (!aConstr->shape()) {
762 if (aShapeType == TopAbs_VERTEX) {
763 if (aConstr->shape()->isVertex()) { // compare vertices positions
764 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
765 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
766 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
767 aRefs->Add(aComposite->subFeatureId(a));
769 } else { // get first or last vertex of the edge: last is stored with negative sign
770 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
771 int aDelta = kSTART_VERTEX_DELTA;
772 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
773 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
774 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
775 aRefs->Add(aDelta + aComposite->subFeatureId(a));
778 aDelta += kSTART_VERTEX_DELTA;
782 if (aConstr->shape()->isEdge()) {
783 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
784 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
785 if (!anEdge.IsNull()) {
786 Standard_Real aFirst, aLast;
787 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
788 if (allCurves.Contains(aCurve)) {
789 int anID = aComposite->subFeatureId(a);
791 if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
792 // add edges to sub-label to support naming for edges selection
793 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
794 for(; anEdgeExp.More(); anEdgeExp.Next()) {
795 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
796 Standard_Real aFirst, aLast;
797 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
798 if (aFaceCurve == aCurve) {
799 int anOrient = edgeOrientation(aSubShape, anEdge);
800 anOrientations[anID] = anOrient;
802 selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
803 Handle(TDataStd_IntPackedMap)(), anOrient);
806 } else { // put vertices of the selected edge to sub-labels
807 // add edges to sub-label to support naming for edges selection
808 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
809 int aTagIndex = anID + kSTART_VERTEX_DELTA;
810 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
811 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
813 std::stringstream anAdditionalName;
815 selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
824 // store the selected as primitive
825 TNaming_Builder aBuilder(selectionLabel());
826 aBuilder.Generated(aSubShape);
828 selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs);
831 bool Model_AttributeSelection::selectPart(
832 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
833 const bool theUpdate)
835 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
836 if (!aPart.get() || !aPart->isActivated())
837 return true; // postponed naming
839 Handle(TDataStd_Integer) anIndex;
840 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
841 if (anIndex->Get() > 0) {
842 // update the selection by index
843 return aPart->updateInPart(anIndex->Get());
845 return true; // nothing to do, referencing just by name
848 return true; // nothing to do, referencing just by name
850 // store the shape (in case part is not loaded it should be useful
852 std::string aName = theContext->data()->name();
853 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
854 aShape = theContext->shape()->impl<TopoDS_Shape>();
856 aShape = theSubShape->impl<TopoDS_Shape>();
858 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
859 TDataStd_Integer::Set(selectionLabel(), anIndex);
861 TNaming_Builder aBuilder(selectionLabel());
862 aBuilder.Select(aShape, aShape);
863 // identify by name in the part
864 TDataStd_Name::Set(selectionLabel(), aName.c_str());
865 return !aName.empty();
868 TDF_Label Model_AttributeSelection::selectionLabel()
870 return myRef.myRef->Label().FindChild(1);
873 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
875 std::string aName("");
876 if(!this->isInitialized())
877 return !theDefaultName.empty() ? theDefaultName : aName;
878 Handle(TDataStd_Name) anAtt;
879 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
880 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
884 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
885 ResultPtr aCont = context();
887 Model_SelectionNaming aSelNaming(selectionLabel());
888 return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
891 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
892 void Model_AttributeSelection::selectSubShape(
893 const std::string& theType, const std::string& theSubShapeName)
895 if(theSubShapeName.empty() || theType.empty()) return;
897 // check this is Part-name: 2 delimiters in the name
898 std::size_t aPartEnd = theSubShapeName.find('/');
899 if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
900 std::string aPartName = theSubShapeName.substr(0, aPartEnd);
901 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
902 if (aFound.get()) { // found such part, so asking it for the name
903 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
904 string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
906 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
907 if (aSelected.get()) {
908 setValue(aPart, aSelected);
909 TDataStd_Integer::Set(selectionLabel(), anIndex);
915 Model_SelectionNaming aSelNaming(selectionLabel());
916 std::shared_ptr<Model_Document> aDoc =
917 std::dynamic_pointer_cast<Model_Document>(owner()->document());
918 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
920 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
921 setValue(aCont, aShapeToBeSelected);
925 int Model_AttributeSelection::Id()
928 std::shared_ptr<GeomAPI_Shape> aSelection = value();
929 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
930 // support for compsolids:
931 if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
932 aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
935 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
936 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
937 // searching for the latest main shape
938 if (aSelection && !aSelection->isNull() &&
939 aContext && !aContext->isNull())
941 std::shared_ptr<Model_Document> aDoc =
942 std::dynamic_pointer_cast<Model_Document>(context()->document());
944 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
946 aMainShape = TNaming_Tool::CurrentShape(aNS);
950 TopTools_IndexedMapOfShape aSubShapesMap;
951 TopExp::MapShapes(aMainShape, aSubShapesMap);
952 anID = aSubShapesMap.FindIndex(aSubShape);