1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_AttributeSelection.h
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 <ModelAPI_Feature.h>
13 #include <ModelAPI_ResultBody.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <GeomAPI_Shape.h>
17 #include <GeomAPI_PlanarEdges.h>
18 #include <Events_Error.h>
20 #include <TNaming_Selector.hxx>
21 #include <TNaming_NamedShape.hxx>
22 #include <TNaming_Tool.hxx>
23 #include <TNaming_Builder.hxx>
24 #include <TNaming_Localizer.hxx>
25 #include <TopoDS_Shape.hxx>
26 #include <TopoDS_Compound.hxx>
27 #include <TDataStd_IntPackedMap.hxx>
28 #include <TDataStd_Integer.hxx>
29 #include <TDataStd_UAttribute.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TopTools_MapOfShape.hxx>
32 #include <TopTools_IndexedMapOfShape.hxx>
33 #include <TopTools_MapIteratorOfMapOfShape.hxx>
34 #include <TopTools_ListOfShape.hxx>
35 #include <TopExp_Explorer.hxx>
36 #include <TDF_LabelMap.hxx>
37 #include <BRep_Tool.hxx>
38 #include <BRep_Builder.hxx>
39 #include <TopoDS_Edge.hxx>
42 #include <TColStd_MapOfTransient.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
47 #include <Precision.hxx>
48 #include <TDF_ChildIterator.hxx>
49 #include <TDF_ChildIDIterator.hxx>
50 #include <TDataStd_Name.hxx>
51 #include <TopAbs_ShapeEnum.hxx>
52 #include <TopoDS_Iterator.hxx>
53 #include <TNaming_Iterator.hxx>
55 //#define DEB_NAMING 1
57 #include <BRepTools.hxx>
59 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
60 /// (multiplied by the index of the edge)
61 static const int kSTART_VERTEX_DELTA = 1000000;
62 // identifier that there is simple reference: selection equals to context
63 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
64 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
66 // on this label is stored:
67 // TNaming_NamedShape - selected shape
68 // TNaming_Naming - topological selection information (for the body)
69 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
70 // TDataStd_Integer - type of the selected shape (for construction)
71 // TDF_Reference - from ReferenceAttribute, the context
73 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
74 const std::shared_ptr<GeomAPI_Shape>& theSubShape)
76 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
77 bool isOldContext = theContext == myRef.value();
78 bool isOldShape = isOldContext &&
79 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
80 if (isOldShape) return; // shape is the same, so context is also unchanged
81 // update the referenced object if needed
83 myRef.setValue(theContext);
85 // do noth use naming if selected shape is result shape itself, but not sub-shape
86 TDF_Label aSelLab = selectionLabel();
87 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
88 aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
90 bool isDegeneratedEdge = false;
91 // do not use the degenerated edge as a shape, a null context and shape is used in the case
92 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
93 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
94 if (aSubShape.ShapeType() == TopAbs_EDGE)
95 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
97 if (!theContext.get() || isDegeneratedEdge) {
98 // to keep the reference attribute label
99 TDF_Label aRefLab = myRef.myRef->Label();
100 aSelLab.ForgetAllAttributes(true);
101 myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
104 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
105 // do not select the whole shape for body:it is already must be in the data framework
106 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
107 aSelLab.ForgetAllAttributes(true);
108 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
110 selectBody(theContext, theSubShape);
112 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
113 if (!theSubShape.get()) {
114 // to sub, so the whole result is selected
115 aSelLab.ForgetAllAttributes(true);
116 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
118 selectConstruction(theContext, theSubShape);
121 //the attribute initialized state should be changed by sendAttributeUpdated only
122 //myIsInitialized = true;
124 owner()->data()->sendAttributeUpdated(this);
126 std::string aSelName = namingName();
127 if(!aSelName.empty())
128 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
131 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
132 //selectSubShape("FACE", "Extrusion_1/TopFace");
133 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
134 //selectSubShape("EDGE", "Sketch_1/Edge_6");
138 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
140 std::shared_ptr<GeomAPI_Shape> aResult;
141 if (myRef.isInitialized()) {
142 TDF_Label aSelLab = selectionLabel();
143 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
144 ResultPtr aContext = context();
146 return aResult; // empty result
147 return aContext->shape();
149 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
150 return aResult; // empty result
153 Handle(TNaming_NamedShape) aSelection;
154 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
155 TopoDS_Shape aSelShape = aSelection->Get();
156 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
157 aResult->setImpl(new TopoDS_Shape(aSelShape));
158 } else { // for simple construction element: just shape of this construction element
159 ResultConstructionPtr aConstr =
160 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
162 return aConstr->shape();
169 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
172 myIsInitialized = myRef.isInitialized();
175 void Model_AttributeSelection::setID(const std::string theID)
178 ModelAPI_AttributeSelection::setID(theID);
181 ResultPtr Model_AttributeSelection::context() {
182 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
186 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
188 ModelAPI_AttributeSelection::setObject(theObject);
189 myRef.setObject(theObject);
192 TDF_LabelMap& Model_AttributeSelection::scope()
194 if (myScope.IsEmpty()) { // create a new scope if not yet done
195 // gets all labels with named shapes that are bofore this feature label (before in history)
196 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
197 owner()->data())->label().Father();
198 int aFeatureID = aFeatureLab.Tag();
199 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
200 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
201 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
203 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
204 for(; aNSIter.More(); aNSIter.Next()) {
205 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
206 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
207 myScope.Add(aNS->Label());
215 bool Model_AttributeSelection::update()
217 ResultPtr aContext = context();
218 if (!aContext.get()) return false;
219 TDF_Label aSelLab = selectionLabel();
220 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
221 return aContext->shape() && !aContext->shape()->isNull();
223 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
224 return aContext->shape() && !aContext->shape()->isNull();
227 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
228 // body: just a named shape, use selection mechanism from OCCT
229 TNaming_Selector aSelector(aSelLab);
230 bool aResult = aSelector.Solve(scope()) == Standard_True;
231 owner()->data()->sendAttributeUpdated(this);
233 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
234 // construction: identification by the results indexes, recompute faces and
235 // take the face that more close by the indexes
236 ResultConstructionPtr aConstructionContext =
237 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
238 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
239 // sketch sub-element
240 if (aConstructionContext &&
241 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
243 TDF_Label aLab = myRef.myRef->Label();
244 // getting a type of selected shape
245 Handle(TDataStd_Integer) aTypeAttr;
246 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
249 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
250 // selected indexes will be needed in each "if"
251 Handle(TDataStd_IntPackedMap) aSubIds;
252 std::shared_ptr<GeomAPI_Shape> aNewSelected;
254 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
255 // for now working only with composite features
256 CompositeFeaturePtr aComposite =
257 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
258 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
262 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
263 // If this is a wire with plane defined thin it is a sketch-like object
264 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
266 // if there is no edges indexes, any face can be used: take the first
267 std::shared_ptr<GeomAPI_Shape> aNewSelected;
269 aNewSelected = aConstructionContext->face(0);
270 } else { // searching for most looks-like initial face by the indexes
271 // prepare edges of the current resut for the fast searching
272 TColStd_MapOfTransient allCurves;
273 const int aSubNum = aComposite->numberOfSubs();
274 for(int a = 0; a < aSubNum; a++) {
275 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
276 FeaturePtr aSub = aComposite->subFeature(a);
277 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
278 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
279 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
280 ResultConstructionPtr aConstr =
281 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
282 if (aConstr->shape() && aConstr->shape()->isEdge()) {
283 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
284 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
285 if (!anEdge.IsNull()) {
286 Standard_Real aFirst, aLast;
287 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
288 allCurves.Add(aCurve);
294 double aBestFound = 0; // best percentage of found edges
295 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
296 int aFound = 0, aNotFound = 0;
297 TopExp_Explorer anEdgesExp(
298 aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
299 for(; anEdgesExp.More(); anEdgesExp.Next()) {
300 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
301 if (!anEdge.IsNull()) {
302 Standard_Real aFirst, aLast;
303 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
304 if (allCurves.Contains(aCurve)) {
311 if (aFound + aNotFound != 0) {
312 double aPercentage = double(aFound) / double(aFound + aNotFound);
313 if (aPercentage > aBestFound) {
314 aBestFound = aPercentage;
315 aNewSelected = aConstructionContext->face(aFaceIndex);
320 if (aNewSelected) { // store this new selection
321 selectConstruction(aContext, aNewSelected);
322 owner()->data()->sendAttributeUpdated(this);
325 } else if (aShapeType == TopAbs_EDGE) {
326 // just reselect the edge by the id
327 const int aSubNum = aComposite->numberOfSubs();
328 for(int a = 0; a < aSubNum; a++) {
329 // if aSubIds take any, the first appropriate
330 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
331 // found the appropriate feature
332 FeaturePtr aFeature = aComposite->subFeature(a);
333 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
334 aFeature->results().cbegin();
335 for(;aResIter != aFeature->results().cend(); aResIter++) {
336 ResultConstructionPtr aRes =
337 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
338 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
339 selectConstruction(aContext, aRes->shape());
340 owner()->data()->sendAttributeUpdated(this);
346 } else if (aShapeType == TopAbs_VERTEX) {
347 // just reselect the vertex by the id of edge
348 const int aSubNum = aComposite->numberOfSubs();
349 for(int a = 0; a < aSubNum; a++) {
350 // if aSubIds take any, the first appropriate
351 int aFeatureID = aComposite->subFeatureId(a);
352 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
353 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
354 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
355 // searching for deltas
357 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
358 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
359 // found the feature with appropriate edge
360 FeaturePtr aFeature = aComposite->subFeature(a);
361 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
362 aFeature->results().cbegin();
363 for(;aResIter != aFeature->results().cend(); aResIter++) {
364 ResultConstructionPtr aRes =
365 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
366 if (aRes && aRes->shape()) {
367 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
368 selectConstruction(aContext, aRes->shape());
369 owner()->data()->sendAttributeUpdated(this);
371 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
372 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
374 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
375 if (aVIndex == aVertexNum) { // found!
376 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
377 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
378 selectConstruction(aContext, aVertex);
379 owner()->data()->sendAttributeUpdated(this);
390 } else { // simple construction element: the selected is that needed
391 selectConstruction(aContext, aContext->shape());
392 owner()->data()->sendAttributeUpdated(this);
396 return false; // unknown case
400 void Model_AttributeSelection::selectBody(
401 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
403 // perform the selection
404 TNaming_Selector aSel(selectionLabel());
405 TopoDS_Shape aContext;
407 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
409 aContext = aBody->shape()->impl<TopoDS_Shape>();
412 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
414 aContext = aResult->shape()->impl<TopoDS_Shape>();
416 Events_Error::send("A result with shape is expected");
420 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
421 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
422 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
423 if (aFeatureOwner.get())
424 aFeatureOwner->eraseResults();
425 if (!aContext.IsNull()) {
426 aSel.Select(aNewShape, aContext);
430 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
431 /// if theID is zero,
432 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
433 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
434 std::string theAdditionalName,
435 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
437 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
438 TNaming_Builder aBuilder(aLab);
439 aBuilder.Generated(theShape);
440 std::stringstream aName;
441 aName<<theContextFeature->name()<<"/";
442 if (!theAdditionalName.empty())
443 aName<<theAdditionalName<<"/";
444 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
445 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
446 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
448 if (theRefs.IsNull()) {
450 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
451 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
452 for(; aRef.More(); aRef.Next()) {
453 aName<<"-"<<aRef.Key();
457 theDoc->addNamingName(aLab, aName.str());
458 TDataStd_Name::Set(aLab, aName.str().c_str());
461 void Model_AttributeSelection::selectConstruction(
462 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
464 std::shared_ptr<Model_Document> aMyDoc =
465 std::dynamic_pointer_cast<Model_Document>(owner()->document());
466 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
467 CompositeFeaturePtr aComposite =
468 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
469 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
470 if (!aComposite || aComposite->numberOfSubs() == 0) {
471 // saving of context is enough: result construction contains exactly the needed shape
472 TNaming_Builder aBuilder(selectionLabel());
473 aBuilder.Generated(aSubShape);
474 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
475 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
478 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
479 TDF_Label aLab = myRef.myRef->Label();
480 // identify the reuslts of sub-object of the composite by edges
481 // save type of the selected shape in integer attribute
482 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
483 TDataStd_Integer::Set(aLab, (int)aShapeType);
485 TColStd_MapOfTransient allCurves;
486 if (aShapeType == TopAbs_VERTEX) { // compare positions
487 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
489 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
490 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
491 Standard_Real aFirst, aLast;
492 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
493 allCurves.Add(aCurve);
496 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
497 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
499 const int aSubNum = aComposite->numberOfSubs();
500 for(int a = 0; a < aSubNum; a++) {
501 FeaturePtr aSub = aComposite->subFeature(a);
502 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
503 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
504 // there may be many shapes (circle and center): register if at least one is in selection
505 for(; aRes != aResults.cend(); aRes++) {
506 ResultConstructionPtr aConstr =
507 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
508 if (!aConstr->shape()) {
511 if (aShapeType == TopAbs_VERTEX) {
512 if (aConstr->shape()->isVertex()) { // compare vertices positions
513 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
514 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
515 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
516 aRefs->Add(aComposite->subFeatureId(a));
518 } else { // get first or last vertex of the edge: last is stored with negative sign
519 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
520 int aDelta = kSTART_VERTEX_DELTA;
521 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
522 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
523 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
524 aRefs->Add(aDelta + aComposite->subFeatureId(a));
527 aDelta += kSTART_VERTEX_DELTA;
531 if (aConstr->shape()->isEdge()) {
532 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
533 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
534 if (!anEdge.IsNull()) {
535 Standard_Real aFirst, aLast;
536 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
537 if (allCurves.Contains(aCurve)) {
538 int anID = aComposite->subFeatureId(a);
540 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
541 // add edges to sub-label to support naming for edges selection
542 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
543 for(; anEdgeExp.More(); anEdgeExp.Next()) {
544 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
545 Standard_Real aFirst, aLast;
546 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
547 if (aFaceCurve == aCurve) {
548 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
551 } else { // put vertices of the selected edge to sub-labels
552 // add edges to sub-label to support naming for edges selection
553 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
554 int aTagIndex = anID + kSTART_VERTEX_DELTA;
555 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
556 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
558 std::stringstream anAdditionalName;
559 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
569 // store the selected as primitive
570 TNaming_Builder aBuilder(selectionLabel());
571 aBuilder.Generated(aSubShape);
572 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
575 TDF_Label Model_AttributeSelection::selectionLabel()
577 return myRef.myRef->Label().FindChild(1);
581 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
582 const TDF_Label& theLabel)
585 // check if the subShape is already in DF
586 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
587 Handle(TDataStd_Name) anAttr;
588 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
589 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
590 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
592 const TDF_Label& aLabel = theDoc->findNamingName(aName);
593 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
594 if(!aLabel.IsEqual(aNS->Label())) {
595 //aName.erase(); //something is wrong, to be checked!!!
596 aName += "_SomethingWrong";
600 static const std::string aPostFix("_");
601 TNaming_Iterator anItL(aNS);
602 for(int i = 1; anItL.More(); anItL.Next(), i++) {
603 if(anItL.NewShape() == theShape) {
605 aName += TCollection_AsciiString (i).ToCString();
609 /* MPV: the code below does not work because of TNaming_Tool.cxx line 145: aNS->Get() uses maps
610 const TopoDS_Shape& aShape = aNS->Get();
611 if(aShape.ShapeType() == TopAbs_COMPOUND) {
612 std::string aPostFix("_");
613 TopoDS_Iterator it(aShape);
614 for (int i = 1;it.More();it.Next(), i++) {
615 if(it.Value() == theShape) {
616 aPostFix += TCollection_AsciiString (i).ToCString();
630 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
632 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
633 TopoDS_Compound aCmp;
635 BB.MakeCompound(aCmp);
636 TopTools_ListIteratorOfListOfShape it(theAncestors);
637 for(;it.More();it.Next()) {
638 BB.Add(aCmp, it.Value());
639 theSMap.Add(it.Value());
642 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
643 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
644 for (int i = 1; i <= aMap2.Extent(); i++) {
645 const TopoDS_Shape& aKey = aMap2.FindKey(i);
646 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
647 if(anAncestors.Extent() > 1) aNumber++;
649 if(aNumber > 1) return false;
652 std::string Model_AttributeSelection::namingName()
654 std::string aName("");
655 if(!this->isInitialized()) return aName;
656 Handle(TDataStd_Name) anAtt;
657 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
658 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
662 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
663 ResultPtr aCont = context();
664 aName = "Undefined name";
665 if(!aCont.get() || aCont->shape()->isNull())
667 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
668 return aCont->data()->name();
670 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
671 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
673 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
674 BRepTools::Write(aSubShape, "Selection.brep");
675 BRepTools::Write(aContext, "Context.brep");
678 std::shared_ptr<Model_Document> aDoc =
679 std::dynamic_pointer_cast<Model_Document>(aCont->document());
681 // check if the subShape is already in DF
682 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
683 if(aName.empty() ) { // not in the document!
684 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
687 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
691 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
692 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
693 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
694 aName = "Degenerated_Edge";
697 TopTools_IndexedDataMapOfShapeListOfShape aMap;
698 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
699 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
700 bool isTrivialCase(true);
701 /* for (int i = 1; i <= aMap.Extent(); i++) {
702 const TopoDS_Shape& aKey = aMap.FindKey(i);
703 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
704 if (aKey.IsSame(aSubShape)) continue;
705 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
706 // check that it is not a trivial case (F1 & F2: aNumber = 1)
707 isTrivialCase = isTrivial(anAncestors, aSMap);
710 if(aMap.Contains(aSubShape)) {
711 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
712 // check that it is not a trivial case (F1 & F2: aNumber = 1)
713 isTrivialCase = isTrivial(anAncestors, aSMap);
716 TopTools_ListOfShape aListOfNbs;
717 if(!isTrivialCase) { // find Neighbors
718 TNaming_Localizer aLocalizer;
719 TopTools_MapOfShape aMap3;
720 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
721 //int n = aMap3.Extent();
722 TopTools_MapIteratorOfMapOfShape it(aMap3);
723 for(;it.More();it.Next()) {
724 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
725 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
726 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
727 TopTools_ListIteratorOfListOfShape it2(aList);
728 for(;it2.More();it2.Next()) {
729 if(aSMap.Contains(it2.Value())) continue; // skip this Face
730 aListOfNbs.Append(it2.Value());
733 } // else a trivial case
735 // build name of the sub-shape Edge
736 for(int i=1; i <= aSMap.Extent(); i++) {
737 const TopoDS_Shape& aFace = aSMap.FindKey(i);
738 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
742 aName += "|" + aFaceName;
744 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
745 for (;itl.More();itl.Next()) {
746 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
747 aName += "|" + aFaceName;
753 // name structure (Monifold Topology):
754 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
755 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
756 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
757 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
758 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
759 // or compound of 2 open faces.
760 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
761 // two independent edges (wire or compound)
762 // implemented 2 first cases
764 TopTools_IndexedDataMapOfShapeListOfShape aMap;
765 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
766 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
767 TopTools_ListOfShape aList;
768 TopTools_MapOfShape aFMap;
770 //int n = aList2.Extent(); //bug! duplication
772 TopTools_ListIteratorOfListOfShape itl2(aList2);
773 for (int i = 1;itl2.More();itl2.Next(),i++) {
774 if(aFMap.Add(itl2.Value()))
775 aList.Append(itl2.Value());
777 //n = aList.Extent();
779 int n = aList.Extent();
780 if(n < 3) { // open topology case or Compound case => via edges
781 TopTools_IndexedDataMapOfShapeListOfShape aMap;
782 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
783 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
784 if(aList22.Extent() >= 2) { // regular solution
787 // bug! duplication; fix is below
789 TopTools_ListOfShape aListE;
790 TopTools_ListIteratorOfListOfShape itl2(aList22);
791 for (int i = 1;itl2.More();itl2.Next(),i++) {
792 if(aFMap.Add(itl2.Value()))
793 aListE.Append(itl2.Value());
797 TopTools_ListIteratorOfListOfShape itl(aListE);
798 for (int i = 1;itl.More();itl.Next(),i++) {
799 const TopoDS_Shape& anEdge = itl.Value();
800 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
804 aName += "|" + anEdgeName;
807 else { // dangle vertex: if(aList22.Extent() == 1)
808 //it should be already in DF
812 TopTools_ListIteratorOfListOfShape itl(aList);
813 for (int i = 1;itl.More();itl.Next(),i++) {
814 const TopoDS_Shape& aFace = itl.Value();
815 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
819 aName += "|" + aFaceName;
826 // aDoc->addNamingName(selectionLabel(), aName);
827 // the selected sub-shape will not be shared and as result it will not require registration
832 TopAbs_ShapeEnum translateType (const std::string& theType)
834 // map from the textual shape types to OCCT enumeration
835 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
836 if (MyShapeTypes.size() == 0) {
837 MyShapeTypes["face"] = TopAbs_FACE;
838 MyShapeTypes["faces"] = TopAbs_FACE;
839 MyShapeTypes["vertex"] = TopAbs_VERTEX;
840 MyShapeTypes["vertices"] = TopAbs_VERTEX;
841 MyShapeTypes["wire"] = TopAbs_WIRE;
842 MyShapeTypes["edge"] = TopAbs_EDGE;
843 MyShapeTypes["edges"] = TopAbs_EDGE;
844 MyShapeTypes["shell"] = TopAbs_SHELL;
845 MyShapeTypes["solid"] = TopAbs_SOLID;
846 MyShapeTypes["solids"] = TopAbs_SOLID;
847 MyShapeTypes["FACE"] = TopAbs_FACE;
848 MyShapeTypes["FACES"] = TopAbs_FACE;
849 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
850 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
851 MyShapeTypes["WIRE"] = TopAbs_WIRE;
852 MyShapeTypes["EDGE"] = TopAbs_EDGE;
853 MyShapeTypes["EDGES"] = TopAbs_EDGE;
854 MyShapeTypes["SHELL"] = TopAbs_SHELL;
855 MyShapeTypes["SOLID"] = TopAbs_SOLID;
856 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
858 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
859 return MyShapeTypes[theType];
860 Events_Error::send("Shape type defined in XML is not implemented!");
864 const TopoDS_Shape getShapeFromNS(
865 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
867 TopoDS_Shape aSelection;
868 std::string::size_type n = theSubShapeName.rfind('/');
869 if (n == std::string::npos) n = 0;
870 std::string aSubString = theSubShapeName.substr(n + 1);
871 n = aSubString.rfind('_');
872 if (n == std::string::npos) return aSelection;
873 aSubString = aSubString.substr(n+1);
874 int indx = atoi(aSubString.c_str());
876 TNaming_Iterator anItL(theNS);
877 for(int i = 1; anItL.More(); anItL.Next(), i++) {
879 return anItL.NewShape();
885 const TopoDS_Shape findFaceByName(
886 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
889 std::string::size_type n, nb = theSubShapeName.rfind('/');
890 if (nb == std::string::npos) nb = 0;
891 std::string aSubString = theSubShapeName.substr(nb + 1);
892 n = aSubString.rfind('_');
893 if (n != std::string::npos) {
894 std::string aSubStr2 = aSubString.substr(0, n);
895 aSubString = theSubShapeName.substr(0, nb + 1);
896 aSubString = aSubString + aSubStr2;
898 aSubString = theSubShapeName;
900 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
901 if(aLabel.IsNull()) return aFace;
902 Handle(TNaming_NamedShape) aNS;
903 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
904 aFace = getShapeFromNS(theSubShapeName, aNS);
909 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
911 std::string aName = theSubShapeName;
912 std::string aLastName;
913 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
914 while ((n2 = aName.find('|', n1)) != std::string::npos) {
915 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
916 theList.push_back(aName1);
918 aLastName = aName.substr(n1);
920 if(!aLastName.empty())
921 theList.push_back(aLastName);
922 return theList.size();
925 const TopoDS_Shape findCommonShape(
926 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
929 std::vector<TopTools_MapOfShape> aVec;
930 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
931 if(theList.Extent() > 1) {
932 aVec.push_back(aMap1);
933 aVec.push_back(aMap2);
935 if(theList.Extent() > 2)
936 aVec.push_back(aMap3);
937 if(theList.Extent() == 4)
938 aVec.push_back(aMap4);
941 TopTools_ListIteratorOfListOfShape it(theList);
942 for(int i = 0;it.More();it.Next(),i++) {
943 const TopoDS_Shape& aFace = it.Value();
945 TopExp_Explorer anExp (aFace, theType);
946 for(;anExp.More();anExp.Next()) {
947 const TopoDS_Shape& anEdge = anExp.Current();
948 if (!anEdge.IsNull())
949 aVec[i].Add(anExp.Current());
952 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
953 for(;anExp.More();anExp.Next()) {
954 const TopoDS_Shape& aVertex = anExp.Current();
955 if (!aVertex.IsNull())
956 aVec[i].Add(anExp.Current());
960 //trivial case: 2 faces
961 TopTools_ListOfShape aList;
962 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
963 for(;it2.More();it2.Next()) {
964 if(aVec[1].Contains(it2.Key())) {
966 if(theList.Extent() == 2)
969 aList.Append(it2.Key());
972 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
973 if(aVec[2].Extent() && aVec[3].Extent()) {
974 TopTools_ListIteratorOfListOfShape it(aList);
975 for(;it.More();it.Next()) {
976 const TopoDS_Shape& aCand = it.Value();
977 // not yet completelly implemented, to be rechecked
978 TopoDS_Vertex aV1, aV2;
979 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
981 if(aVec[2].Contains(aV1)) aNum++;
982 else if(aVec[2].Contains(aV2)) aNum++;
983 if(aVec[3].Contains(aV1)) aNum++;
984 else if(aVec[3].Contains(aV2)) aNum++;
993 if(aList.Extent() && aVec.size() == 3) {
995 TopTools_ListIteratorOfListOfShape it(aList);
996 for(;it.More();it.Next()) {
997 const TopoDS_Shape& aCand = it.Value();
998 if(aVec[2].Contains(aCand)) {
1007 std::string getContextName(const std::string& theSubShapeName)
1010 std::string::size_type n = theSubShapeName.find('/');
1011 if (n == std::string::npos) return aName;
1012 aName = theSubShapeName.substr(0, n);
1015 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
1016 void Model_AttributeSelection::selectSubShape(
1017 const std::string& theType, const std::string& theSubShapeName)
1019 if(theSubShapeName.empty() || theType.empty()) return;
1020 TopAbs_ShapeEnum aType = translateType(theType);
1021 std::shared_ptr<Model_Document> aDoc =
1022 std::dynamic_pointer_cast<Model_Document>(owner()->document());
1023 std::string aContName = getContextName(theSubShapeName);
1024 if(aContName.empty()) return;
1025 //ResultPtr aCont = context();
1026 ResultPtr aCont = aDoc->findByName(aContName);
1027 if(!aCont.get() || aCont->shape()->isNull()) return;
1028 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
1029 TopAbs_ShapeEnum aContType = aContext.ShapeType();
1030 if(aType <= aContType) return; // not applicable
1033 TopoDS_Shape aSelection;
1036 case TopAbs_COMPOUND:
1038 case TopAbs_COMPSOLID:
1046 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1047 if(!aSelection.IsNull()) {// Select it
1048 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1049 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1050 setValue(aCont, aShapeToBeSelected);
1058 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1059 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1060 if(!aLabel.IsNull()) {
1061 Handle(TNaming_NamedShape) aNS;
1062 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1063 aSelection = getShapeFromNS(theSubShapeName, aNS);
1066 if(aSelection.IsNull()) {
1067 std::list<std::string> aListofNames;
1068 int n = ParseName(theSubShapeName, aListofNames);
1069 if(n > 1 && n < 5) {
1070 TopTools_ListOfShape aList;
1071 std::list<std::string>::iterator it =aListofNames.begin();
1072 for(;it != aListofNames.end();it++){
1073 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1074 aList.Append(aFace);
1076 aSelection = findCommonShape(TopAbs_EDGE, aList);
1079 if(!aSelection.IsNull()) {// Select it
1080 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1081 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1082 setValue(aCont, aShapeToBeSelected);
1088 TopoDS_Shape aSelection;
1089 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1090 if(!aLabel.IsNull()) {
1091 Handle(TNaming_NamedShape) aNS;
1092 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1093 aSelection = getShapeFromNS(theSubShapeName, aNS);
1096 if(aSelection.IsNull()) {
1097 std::list<std::string> aListofNames;
1098 int n = ParseName(theSubShapeName, aListofNames);
1099 if(n > 1 && n < 4) { // 2 || 3
1100 TopTools_ListOfShape aList;
1101 std::list<std::string>::iterator it = aListofNames.begin();
1102 for(; it != aListofNames.end(); it++){
1103 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1105 aList.Append(aFace);
1107 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1110 if(!aSelection.IsNull()) {// Select it
1111 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1112 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1113 setValue(aCont, aShapeToBeSelected);
1117 default: //TopAbs_SHAPE
1123 int Model_AttributeSelection::Id()
1125 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1126 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1127 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1128 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1130 if (aSelection && !aSelection->isNull() &&
1131 aContext && !aContext->isNull())
1133 TopTools_IndexedMapOfShape aSubShapesMap;
1134 TopExp::MapShapes(aMainShape, aSubShapesMap);
1135 anID = aSubShapesMap.FindIndex(aSubShape);