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 <GeomAlgoAPI_SketchBuilder.h>
19 #include <Events_Error.h>
21 #include <TNaming_Selector.hxx>
22 #include <TNaming_NamedShape.hxx>
23 #include <TNaming_Tool.hxx>
24 #include <TNaming_Builder.hxx>
25 #include <TNaming_Localizer.hxx>
26 #include <TopoDS_Shape.hxx>
27 #include <TopoDS_Compound.hxx>
28 #include <TDataStd_IntPackedMap.hxx>
29 #include <TDataStd_Integer.hxx>
30 #include <TDataStd_UAttribute.hxx>
31 #include <TDataStd_Name.hxx>
32 #include <TopTools_MapOfShape.hxx>
33 #include <TopTools_IndexedMapOfShape.hxx>
34 #include <TopTools_MapIteratorOfMapOfShape.hxx>
35 #include <TopTools_ListOfShape.hxx>
36 #include <TopExp_Explorer.hxx>
37 #include <TDF_LabelMap.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRep_Builder.hxx>
40 #include <TopoDS_Edge.hxx>
43 #include <TColStd_MapOfTransient.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_ListIteratorOfListOfShape.hxx>
46 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
48 #include <Precision.hxx>
49 #include <TDF_ChildIterator.hxx>
50 #include <TDF_ChildIDIterator.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TopAbs_ShapeEnum.hxx>
53 #include <TopoDS_Iterator.hxx>
54 #include <TNaming_Iterator.hxx>
56 //#define DEB_NAMING 1
58 #include <BRepTools.hxx>
60 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
61 /// (multiplied by the index of the edge)
62 static const int kSTART_VERTEX_DELTA = 1000000;
63 // identifier that there is simple reference: selection equals to context
64 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
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();
78 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
79 if (isOldShape) return; // shape is the same, so context is also unchanged
80 // update the referenced object if needed
81 bool isOldContext = theContext == myRef.value();
85 myRef.setValue(theContext);
87 // do noth use naming if selected shape is result shape itself, but not sub-shape
88 TDF_Label aSelLab = selectionLabel();
89 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
90 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
91 // do not select the whole shape for body:it is already must be in the data framework
92 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
93 aSelLab.ForgetAllAttributes(true);
94 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
96 selectBody(theContext, theSubShape);
98 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
99 selectConstruction(theContext, theSubShape);
101 myIsInitialized = true;
103 std::string aSelName = namingName();
104 if(!aSelName.empty())
105 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
108 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
109 //selectSubShape("FACE", "Extrusion_1/TopFace");
110 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
111 //selectSubShape("EDGE", "Sketch_1/Edge_6");
113 owner()->data()->sendAttributeUpdated(this);
116 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
118 std::shared_ptr<GeomAPI_Shape> aResult;
119 if (myIsInitialized) {
120 TDF_Label aSelLab = selectionLabel();
121 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
122 ResultPtr aContext = context();
124 return aResult; // empty result
125 return aContext->shape();
128 Handle(TNaming_NamedShape) aSelection;
129 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
130 TopoDS_Shape aSelShape = aSelection->Get();
131 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
132 aResult->setImpl(new TopoDS_Shape(aSelShape));
133 } else { // for simple construction element: just shape of this construction element
134 ResultConstructionPtr aConstr =
135 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
137 return aConstr->shape();
144 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
147 myIsInitialized = myRef.isInitialized();
150 ResultPtr Model_AttributeSelection::context() {
151 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
155 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
157 ModelAPI_AttributeSelection::setObject(theObject);
158 myRef.setObject(theObject);
161 TDF_LabelMap& Model_AttributeSelection::scope()
163 if (myScope.IsEmpty()) { // create a new scope if not yet done
164 // gets all labels with named shapes that are bofore this feature label (before in history)
165 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
166 owner()->data())->label().Father();
167 int aFeatureID = aFeatureLab.Tag();
168 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
169 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
170 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
172 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
173 for(; aNSIter.More(); aNSIter.Next()) {
174 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
175 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
176 myScope.Add(aNS->Label());
184 bool Model_AttributeSelection::update()
186 ResultPtr aContext = context();
187 if (!aContext.get()) return false;
188 TDF_Label aSelLab = selectionLabel();
189 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
190 return aContext->shape() && !aContext->shape()->isNull();
193 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
194 // body: just a named shape, use selection mechanism from OCCT
195 TNaming_Selector aSelector(aSelLab);
196 bool aResult = aSelector.Solve(scope()) == Standard_True;
197 owner()->data()->sendAttributeUpdated(this);
199 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
200 // construction: identification by the results indexes, recompute faces and
201 // take the face that more close by the indexes
202 std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
203 std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
204 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
205 if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
206 TDF_Label aLab = myRef.myRef->Label();
207 // getting a type of selected shape
208 Handle(TDataStd_Integer) aTypeAttr;
209 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
212 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
213 // selected indexes will be needed in each "if"
214 Handle(TDataStd_IntPackedMap) aSubIds;
215 std::shared_ptr<GeomAPI_Shape> aNewSelected;
217 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
218 // for now working only with composite features
219 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
220 CompositeFeaturePtr aComposite =
221 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
222 if (!aComposite || aComposite->numberOfSubs() == 0) {
226 if (aShapeType == TopAbs_FACE) {
227 // If this is a wire with plane defined thin it is a sketch-like object
228 std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
229 GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
230 aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
231 if (aFaces.empty()) // no faces, update can not work correctly
233 // if there is no edges indexes, any face can be used: take the first
234 std::shared_ptr<GeomAPI_Shape> aNewSelected;
236 aNewSelected = *(aFaces.begin());
237 } else { // searching for most looks-like initial face by the indexes
238 // prepare edges of the current resut for the fast searching
239 TColStd_MapOfTransient allCurves;
240 const int aSubNum = aComposite->numberOfSubs();
241 for(int a = 0; a < aSubNum; a++) {
242 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
243 FeaturePtr aSub = aComposite->subFeature(a);
244 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
245 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
246 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
247 ResultConstructionPtr aConstr =
248 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
249 if (aConstr->shape() && aConstr->shape()->isEdge()) {
250 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
251 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
252 if (!anEdge.IsNull()) {
253 Standard_Real aFirst, aLast;
254 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
255 allCurves.Add(aCurve);
261 // iterate new result faces and searching for these edges
262 std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
263 double aBestFound = 0; // best percentage of found edges
264 for(; aFacesIter != aFaces.end(); aFacesIter++) {
265 int aFound = 0, aNotFound = 0;
266 TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
267 for(; anEdgesExp.More(); anEdgesExp.Next()) {
268 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
269 if (!anEdge.IsNull()) {
270 Standard_Real aFirst, aLast;
271 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
272 if (allCurves.Contains(aCurve)) {
279 if (aFound + aNotFound != 0) {
280 double aPercentage = double(aFound) / double(aFound + aNotFound);
281 if (aPercentage > aBestFound) {
282 aBestFound = aPercentage;
283 aNewSelected = *aFacesIter;
288 if (aNewSelected) { // store this new selection
289 selectConstruction(aContext, aNewSelected);
290 owner()->data()->sendAttributeUpdated(this);
293 } else if (aShapeType == TopAbs_EDGE) {
294 // just reselect the edge by the id
295 const int aSubNum = aComposite->numberOfSubs();
296 for(int a = 0; a < aSubNum; a++) {
297 // if aSubIds take any, the first appropriate
298 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
299 // found the appropriate feature
300 FeaturePtr aFeature = aComposite->subFeature(a);
301 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
302 aFeature->results().cbegin();
303 for(;aResIter != aFeature->results().cend(); aResIter++) {
304 ResultConstructionPtr aRes =
305 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
306 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
307 selectConstruction(aContext, aRes->shape());
308 owner()->data()->sendAttributeUpdated(this);
314 } else if (aShapeType == TopAbs_VERTEX) {
315 // just reselect the vertex by the id of edge
316 const int aSubNum = aComposite->numberOfSubs();
317 for(int a = 0; a < aSubNum; a++) {
318 // if aSubIds take any, the first appropriate
319 int aFeatureID = aComposite->subFeatureId(a);
320 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
321 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
322 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
323 // searching for deltas
325 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
326 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
327 // found the feature with appropriate edge
328 FeaturePtr aFeature = aComposite->subFeature(a);
329 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
330 aFeature->results().cbegin();
331 for(;aResIter != aFeature->results().cend(); aResIter++) {
332 ResultConstructionPtr aRes =
333 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
334 if (aRes && aRes->shape()) {
335 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
336 selectConstruction(aContext, aRes->shape());
337 owner()->data()->sendAttributeUpdated(this);
339 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
340 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
342 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
343 if (aVIndex == aVertexNum) { // found!
344 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
345 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
346 selectConstruction(aContext, aVertex);
347 owner()->data()->sendAttributeUpdated(this);
358 } else { // simple construction element: the selected is that needed
359 selectConstruction(aContext, aContext->shape());
360 owner()->data()->sendAttributeUpdated(this);
364 return false; // unknown case
368 void Model_AttributeSelection::selectBody(
369 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
371 // perform the selection
372 TNaming_Selector aSel(selectionLabel());
373 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
374 TopoDS_Shape aContext;
376 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
378 aContext = aBody->shape()->impl<TopoDS_Shape>();
380 ResultConstructionPtr aConstr =
381 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
383 aContext = aConstr->shape()->impl<TopoDS_Shape>();
385 Events_Error::send("A result with shape is expected");
389 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
390 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
391 if (aFeatureOwner.get())
392 aFeatureOwner->eraseResults();
394 aSel.Select(aNewShape, aContext);
397 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
398 /// if theID is zero,
399 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
400 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
401 std::string theAdditionalName,
402 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
404 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
405 TNaming_Builder aBuilder(aLab);
406 aBuilder.Generated(theShape);
407 std::stringstream aName;
408 aName<<theContextFeature->name()<<"/";
409 if (!theAdditionalName.empty())
410 aName<<theAdditionalName<<"/";
411 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
412 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
413 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
415 if (theRefs.IsNull()) {
417 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
418 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
419 for(; aRef.More(); aRef.Next()) {
420 aName<<"-"<<aRef.Key();
424 theDoc->addNamingName(aLab, aName.str());
425 TDataStd_Name::Set(aLab, aName.str().c_str());
428 void Model_AttributeSelection::selectConstruction(
429 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
431 std::shared_ptr<Model_Document> aMyDoc =
432 std::dynamic_pointer_cast<Model_Document>(owner()->document());
433 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
434 CompositeFeaturePtr aComposite =
435 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
436 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
437 if (!aComposite || aComposite->numberOfSubs() == 0) {
438 // saving of context is enough: result construction contains exactly the needed shape
439 TNaming_Builder aBuilder(selectionLabel());
440 aBuilder.Generated(aSubShape);
441 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
442 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
445 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
446 TDF_Label aLab = myRef.myRef->Label();
447 // identify the reuslts of sub-object of the composite by edges
448 // save type of the selected shape in integer attribute
449 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
450 TDataStd_Integer::Set(aLab, (int)aShapeType);
452 TColStd_MapOfTransient allCurves;
453 if (aShapeType == TopAbs_VERTEX) { // compare positions
454 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
456 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
457 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
458 Standard_Real aFirst, aLast;
459 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
460 allCurves.Add(aCurve);
463 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
464 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
466 const int aSubNum = aComposite->numberOfSubs();
467 for(int a = 0; a < aSubNum; a++) {
468 FeaturePtr aSub = aComposite->subFeature(a);
469 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
470 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
471 // there may be many shapes (circle and center): register if at least one is in selection
472 for(; aRes != aResults.cend(); aRes++) {
473 ResultConstructionPtr aConstr =
474 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
475 if (!aConstr->shape()) {
478 if (aShapeType == TopAbs_VERTEX) {
479 if (aConstr->shape()->isVertex()) { // compare vertices positions
480 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
481 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
482 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
483 aRefs->Add(aComposite->subFeatureId(a));
485 } else { // get first or last vertex of the edge: last is stored with negative sign
486 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
487 int aDelta = kSTART_VERTEX_DELTA;
488 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
489 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
490 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
491 aRefs->Add(aDelta + aComposite->subFeatureId(a));
494 aDelta += kSTART_VERTEX_DELTA;
498 if (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 if (allCurves.Contains(aCurve)) {
505 int anID = aComposite->subFeatureId(a);
507 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
508 // add edges to sub-label to support naming for edges selection
509 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
510 for(; anEdgeExp.More(); anEdgeExp.Next()) {
511 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
512 Standard_Real aFirst, aLast;
513 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
514 if (aFaceCurve == aCurve) {
515 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
518 } else { // put vertices of the selected edge to sub-labels
519 // add edges to sub-label to support naming for edges selection
520 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
521 int aTagIndex = anID + kSTART_VERTEX_DELTA;
522 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
523 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
525 std::stringstream anAdditionalName;
526 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
536 // store the selected as primitive
537 TNaming_Builder aBuilder(selectionLabel());
538 aBuilder.Generated(aSubShape);
539 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
542 TDF_Label Model_AttributeSelection::selectionLabel()
544 return myRef.myRef->Label().FindChild(1);
548 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
549 const TDF_Label& theLabel)
552 // check if the subShape is already in DF
553 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
554 Handle(TDataStd_Name) anAttr;
555 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
556 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
557 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
559 const TDF_Label& aLabel = theDoc->findNamingName(aName);
560 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
561 if(!aLabel.IsEqual(aNS->Label())) {
562 //aName.erase(); //something is wrong, to be checked!!!
563 aName += "_SomethingWrong";
567 static const std::string aPostFix("_");
568 TNaming_Iterator anItL(aNS);
569 for(int i = 1; anItL.More(); anItL.Next(), i++) {
570 if(anItL.NewShape() == theShape) {
572 aName += TCollection_AsciiString (i).ToCString();
576 /* MPV: the code below does not work because of TNaming_Tool.cxx line 145: aNS->Get() uses maps
577 const TopoDS_Shape& aShape = aNS->Get();
578 if(aShape.ShapeType() == TopAbs_COMPOUND) {
579 std::string aPostFix("_");
580 TopoDS_Iterator it(aShape);
581 for (int i = 1;it.More();it.Next(), i++) {
582 if(it.Value() == theShape) {
583 aPostFix += TCollection_AsciiString (i).ToCString();
597 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
599 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
600 TopoDS_Compound aCmp;
602 BB.MakeCompound(aCmp);
603 TopTools_ListIteratorOfListOfShape it(theAncestors);
604 for(;it.More();it.Next()) {
605 BB.Add(aCmp, it.Value());
606 theSMap.Add(it.Value());
609 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
610 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
611 for (int i = 1; i <= aMap2.Extent(); i++) {
612 const TopoDS_Shape& aKey = aMap2.FindKey(i);
613 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
614 if(anAncestors.Extent() > 1) aNumber++;
616 if(aNumber > 1) return false;
619 std::string Model_AttributeSelection::namingName()
621 std::string aName("");
622 if(!this->isInitialized()) return aName;
623 Handle(TDataStd_Name) anAtt;
624 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
625 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
629 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
630 ResultPtr aCont = context();
631 aName = "Undefined name";
632 if(!aSubSh.get() || aSubSh->isNull() || !aCont.get() || aCont->shape()->isNull())
634 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
635 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
637 BRepTools::Write(aSubShape, "Selection.brep");
638 BRepTools::Write(aContext, "Context.brep");
640 std::shared_ptr<Model_Document> aDoc =
641 std::dynamic_pointer_cast<Model_Document>(aCont->document());
643 // check if the subShape is already in DF
644 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
645 if(aName.empty() ) { // not in the document!
646 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
649 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
653 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
654 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
655 TopTools_IndexedDataMapOfShapeListOfShape aMap;
656 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
657 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
658 bool isTrivialCase(true);
659 /* for (int i = 1; i <= aMap.Extent(); i++) {
660 const TopoDS_Shape& aKey = aMap.FindKey(i);
661 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
662 if (aKey.IsSame(aSubShape)) continue;
663 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
664 // check that it is not a trivial case (F1 & F2: aNumber = 1)
665 isTrivialCase = isTrivial(anAncestors, aSMap);
668 if(aMap.Contains(aSubShape)) {
669 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
670 // check that it is not a trivial case (F1 & F2: aNumber = 1)
671 isTrivialCase = isTrivial(anAncestors, aSMap);
674 TopTools_ListOfShape aListOfNbs;
675 if(!isTrivialCase) { // find Neighbors
676 TNaming_Localizer aLocalizer;
677 TopTools_MapOfShape aMap3;
678 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
679 //int n = aMap3.Extent();
680 TopTools_MapIteratorOfMapOfShape it(aMap3);
681 for(;it.More();it.Next()) {
682 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
683 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
684 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
685 TopTools_ListIteratorOfListOfShape it2(aList);
686 for(;it2.More();it2.Next()) {
687 if(aSMap.Contains(it2.Value())) continue; // skip this Face
688 aListOfNbs.Append(it2.Value());
691 } // else a trivial case
693 // build name of the sub-shape Edge
694 for(int i=1; i <= aSMap.Extent(); i++) {
695 const TopoDS_Shape& aFace = aSMap.FindKey(i);
696 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
700 aName += "|" + aFaceName;
702 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
703 for (;itl.More();itl.Next()) {
704 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
705 aName += "|" + aFaceName;
711 // name structure (Monifold Topology):
712 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
713 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
714 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
715 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
716 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
717 // or compound of 2 open faces.
718 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
719 // two independent edges (wire or compound)
720 // implemented 2 first cases
722 TopTools_IndexedDataMapOfShapeListOfShape aMap;
723 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
724 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
725 TopTools_ListOfShape aList;
726 TopTools_MapOfShape aFMap;
728 //int n = aList2.Extent(); //bug! duplication
730 TopTools_ListIteratorOfListOfShape itl2(aList2);
731 for (int i = 1;itl2.More();itl2.Next(),i++) {
732 if(aFMap.Add(itl2.Value()))
733 aList.Append(itl2.Value());
735 //n = aList.Extent();
737 int n = aList.Extent();
738 if(n < 3) { // open topology case => via edges
739 TopTools_IndexedDataMapOfShapeListOfShape aMap;
740 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
741 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
742 if(aList2.Extent() >= 2) { // regular solution
743 TopTools_ListIteratorOfListOfShape itl(aList2);
744 for (int i = 1;itl.More();itl.Next(),i++) {
745 const TopoDS_Shape& anEdge = itl.Value();
746 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
750 aName += "|" + anEdgeName;
755 TopTools_ListIteratorOfListOfShape itl(aList);
756 for (int i = 1;itl.More();itl.Next(),i++) {
757 const TopoDS_Shape& aFace = itl.Value();
758 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
762 aName += "|" + aFaceName;
769 // aDoc->addNamingName(selectionLabel(), aName);
770 // the selected sub-shape will not be shared and as result it will not require registration
775 TopAbs_ShapeEnum translateType (const std::string& theType)
777 TCollection_AsciiString aStr(theType.c_str());
779 if(aStr.IsEqual("COMP"))
780 return TopAbs_COMPOUND;
781 else if(aStr.IsEqual("COMS"))
782 return TopAbs_COMPSOLID;
783 else if(aStr.IsEqual("SOLD"))
785 else if(aStr.IsEqual("SHEL"))
787 else if(aStr.IsEqual("FACE"))
789 else if(aStr.IsEqual("WIRE"))
791 else if(aStr.IsEqual("EDGE"))
793 else if(aStr.IsEqual("VERT"))
794 return TopAbs_VERTEX;
799 const TopoDS_Shape getShapeFromCompound(
800 const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
802 TopoDS_Shape aSelection;
803 std::string::size_type n = theSubShapeName.rfind('/');
804 if (n == std::string::npos) n = 0;
805 std::string aSubString = theSubShapeName.substr(n + 1);
806 n = aSubString.rfind('_');
807 if (n == std::string::npos) return aSelection;
808 aSubString = aSubString.substr(n+1);
809 int indx = atoi(aSubString.c_str());
810 TopoDS_Iterator it(theCompound);
811 for (int i = 1;it.More();it.Next(), i++) {
813 aSelection = it.Value();
821 const TopoDS_Shape findFaceByName(
822 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
825 std::string::size_type n, nb = theSubShapeName.rfind('/');
826 if (nb == std::string::npos) nb = 0;
827 std::string aSubString = theSubShapeName.substr(nb + 1);
828 n = aSubString.rfind('_');
829 if (n != std::string::npos) {
830 std::string aSubStr2 = aSubString.substr(0, n);
831 aSubString = theSubShapeName.substr(0, nb + 1);
832 aSubString = aSubString + aSubStr2;
834 aSubString = theSubShapeName;
836 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
837 if(aLabel.IsNull()) return aFace;
838 Handle(TNaming_NamedShape) aNS;
839 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
840 const TopoDS_Shape& aShape = aNS->Get();
841 if(!aShape.IsNull()) {
842 if(aShape.ShapeType() == TopAbs_COMPOUND)
843 aFace = getShapeFromCompound(theSubShapeName, aShape);
851 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
853 std::string aName = theSubShapeName;
854 std::string aLastName;
855 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
856 while ((n2 = aName.find('|', n1)) != std::string::npos) {
857 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
858 theList.push_back(aName1);
860 aLastName = aName.substr(n1);
862 if(!aLastName.empty())
863 theList.push_back(aLastName);
864 return theList.size();
867 const TopoDS_Shape findCommonShape(
868 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
871 std::vector<TopTools_MapOfShape> aVec;
872 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
873 if(theList.Extent() > 1) {
874 aVec.push_back(aMap1);
875 aVec.push_back(aMap2);
877 if(theList.Extent() > 2)
878 aVec.push_back(aMap3);
879 if(theList.Extent() == 4)
880 aVec.push_back(aMap4);
883 TopTools_ListIteratorOfListOfShape it(theList);
884 for(int i = 0;it.More();it.Next(),i++) {
885 const TopoDS_Shape& aFace = it.Value();
887 TopExp_Explorer anExp (aFace, theType);
888 for(;anExp.More();anExp.Next()) {
889 const TopoDS_Shape& anEdge = anExp.Current();
890 if (!anEdge.IsNull())
891 aVec[i].Add(anExp.Current());
894 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
895 for(;anExp.More();anExp.Next()) {
896 const TopoDS_Shape& aVertex = anExp.Current();
897 if (!aVertex.IsNull())
898 aVec[i].Add(anExp.Current());
902 //trivial case: 2 faces
903 TopTools_ListOfShape aList;
904 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
905 for(;it2.More();it2.Next()) {
906 if(aVec[1].Contains(it2.Key())) {
908 if(theList.Extent() == 2)
911 aList.Append(it2.Key());
914 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
915 if(aVec[2].Extent() && aVec[3].Extent()) {
916 TopTools_ListIteratorOfListOfShape it(aList);
917 for(;it.More();it.Next()) {
918 const TopoDS_Shape& aCand = it.Value();
919 // not yet completelly implemented, to be rechecked
920 TopoDS_Vertex aV1, aV2;
921 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
923 if(aVec[2].Contains(aV1)) aNum++;
924 else if(aVec[2].Contains(aV2)) aNum++;
925 if(aVec[3].Contains(aV1)) aNum++;
926 else if(aVec[3].Contains(aV2)) aNum++;
935 if(aList.Extent() && aVec.size() == 3) {
937 TopTools_ListIteratorOfListOfShape it(aList);
938 for(;it.More();it.Next()) {
939 const TopoDS_Shape& aCand = it.Value();
940 if(aVec[2].Contains(aCand)) {
949 std::string getContextName(const std::string& theSubShapeName)
952 std::string::size_type n = theSubShapeName.find('/');
953 if (n == std::string::npos) return aName;
954 aName = theSubShapeName.substr(0, n);
957 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
958 void Model_AttributeSelection::selectSubShape(
959 const std::string& theType, const std::string& theSubShapeName)
961 if(theSubShapeName.empty() || theType.empty()) return;
962 TopAbs_ShapeEnum aType = translateType(theType);
963 std::shared_ptr<Model_Document> aDoc =
964 std::dynamic_pointer_cast<Model_Document>(owner()->document());
965 std::string aContName = getContextName(theSubShapeName);
966 if(aContName.empty()) return;
967 //ResultPtr aCont = context();
968 ResultPtr aCont = aDoc->findByName(aContName);
969 if(!aCont.get() || aCont->shape()->isNull()) return;
970 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
971 TopAbs_ShapeEnum aContType = aContext.ShapeType();
972 if(aType <= aContType) return; // not applicable
975 TopoDS_Shape aSelection;
978 case TopAbs_COMPOUND:
980 case TopAbs_COMPSOLID:
988 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
989 if(!aSelection.IsNull()) {// Select it
990 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
991 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
992 setValue(aCont, aShapeToBeSelected);
1000 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1001 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1002 if(!aLabel.IsNull()) {
1003 Handle(TNaming_NamedShape) aNS;
1004 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1005 const TopoDS_Shape& aShape = aNS->Get();
1006 if(!aShape.IsNull()) {
1007 if(aShape.ShapeType() == TopAbs_COMPOUND)
1008 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1010 aSelection = aShape;
1014 if(aSelection.IsNull()) {
1015 std::list<std::string> aListofNames;
1016 int n = ParseName(theSubShapeName, aListofNames);
1017 if(n > 1 && n < 5) {
1018 TopTools_ListOfShape aList;
1019 std::list<std::string>::iterator it =aListofNames.begin();
1020 for(;it != aListofNames.end();it++){
1021 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1022 aList.Append(aFace);
1024 aSelection = findCommonShape(TopAbs_EDGE, aList);
1027 if(!aSelection.IsNull()) {// Select it
1028 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1029 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1030 setValue(aCont, aShapeToBeSelected);
1036 TopoDS_Shape aSelection;
1037 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1038 if(!aLabel.IsNull()) {
1039 Handle(TNaming_NamedShape) aNS;
1040 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1041 const TopoDS_Shape& aShape = aNS->Get();
1042 if(!aShape.IsNull()) {
1043 if(aShape.ShapeType() == TopAbs_COMPOUND)
1044 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1046 aSelection = aShape;
1050 if(aSelection.IsNull()) {
1051 std::list<std::string> aListofNames;
1052 int n = ParseName(theSubShapeName, aListofNames);
1053 if(n > 1 && n < 4) { // 2 || 3
1054 TopTools_ListOfShape aList;
1055 std::list<std::string>::iterator it = aListofNames.begin();
1056 for(; it != aListofNames.end(); it++){
1057 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1059 aList.Append(aFace);
1061 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1064 if(!aSelection.IsNull()) {// Select it
1065 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1066 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1067 setValue(aCont, aShapeToBeSelected);
1071 default: //TopAbs_SHAPE
1077 int Model_AttributeSelection::Id()
1079 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1080 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1081 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1082 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1084 if (aSelection && !aSelection->isNull() &&
1085 aContext && !aContext->isNull())
1087 TopTools_IndexedMapOfShape aSubShapesMap;
1088 TopExp::MapShapes(aMainShape, aSubShapesMap);
1089 anID = aSubShapesMap.FindIndex(aSubShape);