1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_SelectionNaming.cpp
4 // Created: 11 Aug 2015
5 // Author: Mikhail PONIKAROV
7 #include "Model_SelectionNaming.h"
8 #include "Model_Document.h"
9 #include "Model_Objects.h"
10 #include <ModelAPI_Feature.h>
11 #include <Events_InfoMessage.h>
12 #include <ModelAPI_Session.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_ResultBody.h>
17 #include <GeomAPI_Wire.h>
19 #include <TopoDS_Iterator.hxx>
21 #include <TopoDS_Compound.hxx>
23 #include <TopExp_Explorer.hxx>
24 #include <TopTools_ListOfShape.hxx>
25 #include <TopTools_MapOfShape.hxx>
26 #include <TopTools_IndexedMapOfShape.hxx>
27 #include <TopTools_ListIteratorOfListOfShape.hxx>
28 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
29 #include <TopTools_MapIteratorOfMapOfShape.hxx>
30 #include <BRep_Builder.hxx>
31 #include <TNaming_Iterator.hxx>
32 #include <TNaming_Tool.hxx>
33 #include <TNaming_NamedShape.hxx>
34 #include <TNaming_Localizer.hxx>
35 #include <TDataStd_Name.hxx>
36 #include <TColStd_MapOfTransient.hxx>
41 #include <BRepTools.hxx>
44 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
46 myLab = theSelectionLab;
49 std::string Model_SelectionNaming::getShapeName(
50 std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
51 const bool theAddContextName)
54 // check if the subShape is already in DF
55 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
56 Handle(TDataStd_Name) anAttr;
57 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
58 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
59 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
60 // indexes are added to sub-shapes not primitives (primitives must not be located at the same label)
61 if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && theAddContextName) {
62 const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
63 static const std::string aPostFix("_");
64 TNaming_Iterator anItL(aNS);
65 for(int i = 1; anItL.More(); anItL.Next(), i++) {
66 if(anItL.NewShape() == theShape) {
68 aName += TCollection_AsciiString (i).ToCString();
73 if (theAddContextName && aName.find("/") == std::string::npos) { // searching for the context object
74 for(TDF_Label anObjL = aNS->Label(); anObjL.Depth() > 4; anObjL = anObjL.Father()) {
75 int aDepth = anObjL.Depth();
76 if (aDepth == 5 || aDepth == 7) {
77 ObjectPtr anObj = theDoc->objects()->object(anObjL);
79 aName = anObj->data()->name() + "/" + aName;
89 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
91 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
94 BB.MakeCompound(aCmp);
95 TopTools_ListIteratorOfListOfShape it(theAncestors);
96 for(;it.More();it.Next()) {
97 BB.Add(aCmp, it.Value());
98 theSMap.Add(it.Value());
101 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
102 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
103 for (int i = 1; i <= aMap2.Extent(); i++) {
104 const TopoDS_Shape& aKey = aMap2.FindKey(i);
105 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
106 if(anAncestors.Extent() > 1) aNumber++;
108 if(aNumber > 1) return false;
112 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
113 std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
114 const bool theAnotherDoc)
116 std::string aName("Undefined name");
117 if(!theContext.get() || theContext->shape()->isNull())
118 return !theDefaultName.empty() ? theDefaultName : aName;
120 // if it is in result of another part
121 std::shared_ptr<Model_Document> aDoc =
122 std::dynamic_pointer_cast<Model_Document>(theContext->document());
123 if (theContext->groupName() == ModelAPI_ResultPart::group()) {
124 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
126 return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
129 if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
130 // but if it is in another Part, add this part name
131 std::string aPartName;
133 aPartName = theContext->document()->kind() + "/"; // PartSet
134 return aPartName + theContext->data()->name();
136 TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
137 TopoDS_Shape aContext = theContext->shape()->impl<TopoDS_Shape>();
139 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
140 BRepTools::Write(aSubShape, "Selection.brep");
141 BRepTools::Write(aContext, "Context.brep");
145 // add the result name to the name of the shape (it was in BodyBuilder, but did not work on Result rename)
146 bool isNeedContextName = theContext->shape().get() && !theContext->shape()->isEqual(theSubSh);
148 // check if the subShape is already in DF
149 aName = getShapeName(aDoc, aSubShape, isNeedContextName);
150 if(aName.empty() ) { // not in the document!
151 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
154 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
158 // name structure: F1 & F2 [& F3 & F4], where F1 & F2 the faces which gives the Edge in trivial case
159 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
160 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
161 aName = "Degenerated_Edge";
164 TopTools_IndexedDataMapOfShapeListOfShape aMap;
165 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
166 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
167 bool isTrivialCase(true);
168 if(aMap.Contains(aSubShape)) {
169 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
170 // check that it is not a trivial case (F1 & F2: aNumber = 1)
171 isTrivialCase = isTrivial(anAncestors, aSMap);
174 TopTools_ListOfShape aListOfNbs;
175 if(!isTrivialCase) { // find Neighbors
176 TNaming_Localizer aLocalizer;
177 TopTools_MapOfShape aMap3;
178 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
179 //int n = aMap3.Extent();
180 TopTools_MapIteratorOfMapOfShape it(aMap3);
181 for(;it.More();it.Next()) {
182 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
183 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
184 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
185 TopTools_ListIteratorOfListOfShape it2(aList);
186 for(;it2.More();it2.Next()) {
187 if(aSMap.Contains(it2.Value())) continue; // skip this Face
188 aListOfNbs.Append(it2.Value());
191 } // else a trivial case
193 // build name of the sub-shape Edge
194 for(int i=1; i <= aSMap.Extent(); i++) {
195 const TopoDS_Shape& aFace = aSMap.FindKey(i);
196 std::string aFaceName = getShapeName(aDoc, aFace, isNeedContextName);
200 aName += "&" + aFaceName;
202 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
203 for (;itl.More();itl.Next()) {
204 std::string aFaceName = getShapeName(aDoc, itl.Value(), isNeedContextName);
205 aName += "&" + aFaceName;
211 // name structure (Monifold Topology):
212 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
213 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
214 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
215 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
216 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
217 // or compound of 2 open faces.
218 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
219 // two independent edges (wire or compound)
220 // implemented 2 first cases
222 TopTools_IndexedDataMapOfShapeListOfShape aMap;
223 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
224 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
225 TopTools_ListOfShape aList;
226 TopTools_MapOfShape aFMap;
228 TopTools_ListIteratorOfListOfShape itl2(aList2);
229 for (int i = 1;itl2.More();itl2.Next(),i++) {
230 if(aFMap.Add(itl2.Value()))
231 aList.Append(itl2.Value());
233 int n = aList.Extent();
234 bool isByFaces = n >= 3;
235 if(!isByFaces) { // open topology case or Compound case => via edges
236 TopTools_IndexedDataMapOfShapeListOfShape aMap;
237 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
238 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
239 if(aList22.Extent() >= 2) { // regular solution
241 // bug! duplication; fix is below
243 TopTools_ListOfShape aListE;
244 TopTools_ListIteratorOfListOfShape itl2(aList22);
245 for (int i = 1;itl2.More();itl2.Next(),i++) {
246 if(aFMap.Add(itl2.Value()))
247 aListE.Append(itl2.Value());
250 TopTools_ListIteratorOfListOfShape itl(aListE);
251 for (int i = 1;itl.More();itl.Next(),i++) {
252 const TopoDS_Shape& anEdge = itl.Value();
253 std::string anEdgeName = getShapeName(aDoc, anEdge, isNeedContextName);
254 if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
262 aName += "&" + anEdgeName;
265 else { // dangle vertex: if(aList22.Extent() == 1)
266 //it should be already in DF
270 TopTools_ListIteratorOfListOfShape itl(aList);
271 for (int i = 1;itl.More();itl.Next(),i++) {
272 const TopoDS_Shape& aFace = itl.Value();
273 std::string aFaceName = getShapeName(aDoc, aFace, isNeedContextName);
277 aName += "&" + aFaceName;
288 TopAbs_ShapeEnum translateType (const std::string& theType)
290 // map from the textual shape types to OCCT enumeration
291 static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
293 if(aShapeTypes.size() == 0) {
294 aShapeTypes["compound"] = TopAbs_COMPOUND;
295 aShapeTypes["compounds"] = TopAbs_COMPOUND;
296 aShapeTypes["compsolid"] = TopAbs_COMPSOLID;
297 aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
298 aShapeTypes["solid"] = TopAbs_SOLID;
299 aShapeTypes["solids"] = TopAbs_SOLID;
300 aShapeTypes["shell"] = TopAbs_SHELL;
301 aShapeTypes["shells"] = TopAbs_SHELL;
302 aShapeTypes["face"] = TopAbs_FACE;
303 aShapeTypes["faces"] = TopAbs_FACE;
304 aShapeTypes["wire"] = TopAbs_WIRE;
305 aShapeTypes["wires"] = TopAbs_WIRE;
306 aShapeTypes["edge"] = TopAbs_EDGE;
307 aShapeTypes["edges"] = TopAbs_EDGE;
308 aShapeTypes["vertex"] = TopAbs_VERTEX;
309 aShapeTypes["vertices"] = TopAbs_VERTEX;
310 aShapeTypes["COMPOUND"] = TopAbs_COMPOUND;
311 aShapeTypes["COMPOUNDS"] = TopAbs_COMPOUND;
312 aShapeTypes["COMPSOLID"] = TopAbs_COMPSOLID;
313 aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
314 aShapeTypes["SOLID"] = TopAbs_SOLID;
315 aShapeTypes["SOLIDS"] = TopAbs_SOLID;
316 aShapeTypes["SHELL"] = TopAbs_SHELL;
317 aShapeTypes["SHELLS"] = TopAbs_SHELL;
318 aShapeTypes["FACE"] = TopAbs_FACE;
319 aShapeTypes["FACES"] = TopAbs_FACE;
320 aShapeTypes["WIRE"] = TopAbs_WIRE;
321 aShapeTypes["WIRES"] = TopAbs_WIRE;
322 aShapeTypes["EDGE"] = TopAbs_EDGE;
323 aShapeTypes["EDGES"] = TopAbs_EDGE;
324 aShapeTypes["VERTEX"] = TopAbs_VERTEX;
325 aShapeTypes["VERTICES"] = TopAbs_VERTEX;
327 if (aShapeTypes.find(theType) != aShapeTypes.end())
328 return aShapeTypes[theType];
329 Events_InfoMessage("Model_SelectionNaming", "Shape type defined in XML is not implemented!").send();
333 const TopoDS_Shape getShapeFromNS(
334 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
336 TopoDS_Shape aSelection;
337 std::string::size_type n = theSubShapeName.rfind('/');
338 if (n == std::string::npos) n = -1;
339 std::string aSubString = theSubShapeName.substr(n + 1);
340 n = aSubString.rfind('_');
342 if (n != std::string::npos) {// for primitives this is a first
343 // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
344 Handle(TDataStd_Name) aName;
345 if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
346 aName->Get() != theSubShapeName.c_str()) {
347 aSubString = aSubString.substr(n+1);
348 indx = atoi(aSubString.c_str());
352 TNaming_Iterator anItL(theNS);
353 for(int i = 1; anItL.More(); anItL.Next(), i++) {
355 return anItL.NewShape();
361 const TopoDS_Shape findFaceByName(
362 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
365 //std::string::size_type n, nb = theSubShapeName.rfind('/');
366 //if (nb == std::string::npos) nb = 0;
367 //std::string aSubString = theSubShapeName.substr(nb + 1);
368 std::string aSubString = theSubShapeName;
370 TDF_Label aLabel = theDoc->findNamingName(aSubString);
371 if (aLabel.IsNull()) { // try to remove additional artificial suffix
372 std::string::size_type n = aSubString.rfind('_');
373 if (n != std::string::npos) {
374 aSubString = aSubString.substr(0, n);
375 aLabel = theDoc->findNamingName(aSubString);
378 if(aLabel.IsNull()) return aFace;
379 Handle(TNaming_NamedShape) aNS;
380 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
381 aFace = getShapeFromNS(theSubShapeName, aNS);
386 size_t ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
388 std::string aName = theSubShapeName;
389 std::string aLastName;
390 size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
391 while ((n2 = aName.find('&', n1)) != std::string::npos) {
392 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
393 theList.push_back(aName1);
395 aLastName = aName.substr(n1);
397 if(!aLastName.empty())
398 theList.push_back(aLastName);
399 return theList.size();
402 const TopoDS_Shape findCommonShape(
403 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
406 std::vector<TopTools_MapOfShape> aVec;
407 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
408 if(theList.Extent() > 1) {
409 aVec.push_back(aMap1);
410 aVec.push_back(aMap2);
412 if(theList.Extent() > 2)
413 aVec.push_back(aMap3);
414 if(theList.Extent() == 4)
415 aVec.push_back(aMap4);
418 TopTools_ListIteratorOfListOfShape it(theList);
419 for(int i = 0;it.More();it.Next(),i++) {
420 const TopoDS_Shape& aFace = it.Value();
422 TopExp_Explorer anExp (aFace, theType);
423 for(;anExp.More();anExp.Next()) {
424 const TopoDS_Shape& anEdge = anExp.Current();
425 if (!anEdge.IsNull())
426 aVec[i].Add(anExp.Current());
429 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
430 for(;anExp.More();anExp.Next()) {
431 const TopoDS_Shape& aVertex = anExp.Current();
432 if (!aVertex.IsNull())
433 aVec[i].Add(anExp.Current());
437 //trivial case: 2 faces
438 TopTools_ListOfShape aList;
439 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
440 for(;it2.More();it2.Next()) {
441 if(aVec[1].Contains(it2.Key())) {
443 if(theList.Extent() == 2)
446 aList.Append(it2.Key());
449 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
450 if(aVec[2].Extent() && aVec[3].Extent()) {
451 TopTools_ListIteratorOfListOfShape it(aList);
452 for(;it.More();it.Next()) {
453 const TopoDS_Shape& aCand = it.Value();
454 // not yet completelly implemented, to be rechecked
455 TopoDS_Vertex aV1, aV2;
456 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
458 if(aVec[2].Contains(aV1)) aNum++;
459 else if(aVec[2].Contains(aV2)) aNum++;
460 if(aVec[3].Contains(aV1)) aNum++;
461 else if(aVec[3].Contains(aV2)) aNum++;
470 if(aList.Extent() && aVec.size() == 3) {
472 TopTools_ListIteratorOfListOfShape it(aList);
473 for(;it.More();it.Next()) {
474 const TopoDS_Shape& aCand = it.Value();
475 if(aVec[2].Contains(aCand)) {
484 std::string getContextName(const std::string& theSubShapeName)
487 std::string::size_type n = theSubShapeName.find('/');
488 if (n == std::string::npos) return theSubShapeName;
489 aName = theSubShapeName.substr(0, n);
493 /// Parses naming name of sketch sub-elements: takes indices and orientation
494 /// (if theOriented = true) from this name. Map theIDs constains indices ->
495 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
496 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
497 const std::string& theName, const char* theShapeType,
498 std::map<int, int>& theIDs, const bool theOriented = false)
500 // collect all IDs in the name
501 std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
502 const int aSubNum = theComp->numberOfSubs();
503 for(int a = 0; a < aSubNum; a++) {
504 FeaturePtr aSub = theComp->subFeature(a);
505 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
506 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
507 // there may be many shapes (circle and center)
508 for(; aRes != aResults.cend(); aRes++) {
509 ResultConstructionPtr aConstr =
510 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
512 aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
517 size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
518 bool isShape = false; // anyway the first world must be 'Vertex'
520 aLastNamePos = theName.find('-', aPrevPos);
521 std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
523 if (anID != theShapeType)
527 int anOrientation = 1; // default
528 if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
529 std::string::iterator aSymbol = anID.end() - 1;
530 if (*aSymbol == 'r') anOrientation = -1;
531 anID.erase(aSymbol); // remove last symbol
533 // check start/end symbols
534 std::string::iterator aBack = anID.end() - 1;
537 anID.erase(aBack); // remove last symbol
538 } else if (*aBack == 'e') {
540 anID.erase(aBack); // remove last symbol
543 if (aNames.find(anID) != aNames.end()) {
544 theIDs[aNames[anID]] = anOrientation;
547 aPrevPos = aLastNamePos + 1;
548 } while (aLastNamePos != std::string::npos);
552 /// produces theEdge orientation relatively to theContext face
553 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
555 if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
557 if (theEdge.Orientation() == TopAbs_FORWARD)
559 if (theEdge.Orientation() == TopAbs_REVERSED)
564 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
565 std::shared_ptr<ModelAPI_Result>& theConstr,
566 NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
568 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
569 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
570 std::shared_ptr<GeomAPI_Shape> aResult;
571 ResultConstructionPtr aConstructionContext =
572 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
573 if (!aConstructionContext.get())
575 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
576 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
578 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
579 std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
581 for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
582 aFacesWires.push_back(aWires.Current());
585 aFacesWires.push_back(aFace);
587 std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
588 for(; aFW != aFacesWires.end(); aFW++) {
589 TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
590 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
591 for(; anEdgesExp.More(); anEdgesExp.Next()) {
592 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
593 if (!anEdge.IsNull()) {
594 Standard_Real aFirst, aLast;
595 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
596 if (alreadyProcessed.Contains(aCurve))
598 alreadyProcessed.Add(aCurve);
599 if (theCurves.IsBound(aCurve)) {
601 int anOrient = theCurves.Find(aCurve);
602 if (anOrient != 0) { // extra comparision score is orientation
603 if (edgeOrientation(aFace, anEdge) == anOrient)
611 if (aFound + aNotFound != 0) {
612 if (aFound > aBestFound ||
613 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
615 aBestOrient = aSameOrientation;
617 std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
618 aWire->setImpl(new TopoDS_Shape(*aFW));
621 aResult = aConstructionContext->face(aFaceIndex);
630 std::string Model_SelectionNaming::shortName(
631 std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
633 std::string aName = theConstr->data()->name();
634 // remove "-", "/" and "&" command-symbols
635 aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
636 aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
637 aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
638 // remove the last 's', 'e', 'f' and 'r' symbols: they are used as markers of start/end/forward/rewersed indicators
639 static const std::string aSyms("sefr");
640 std::string::iterator aSuffix = aName.end() - 1;
641 while(aSyms.find(*aSuffix) != std::string::npos) {
644 aName.erase(aSuffix + 1, aName.end());
646 if (theEdgeVertexPos == 1) {
647 aName += "s"; // start
648 } else if (theEdgeVertexPos == 2) {
654 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
655 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
656 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
657 std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
659 if(theSubShapeName.empty() || theType.empty()) return false;
660 TopAbs_ShapeEnum aType = translateType(theType);
662 // check that it was selected in another document
663 size_t aSlash = theSubShapeName.find("/");
664 std::string aSubShapeName = theSubShapeName;
665 std::shared_ptr<Model_Document> aDoc = theDoc;
666 if (aSlash != std::string::npos) {
667 std::string aDocName = theSubShapeName.substr(0, aSlash);
668 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
669 if (aDocName == aRootDoc->kind()) {
670 aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
672 for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
673 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
674 aRootDoc->object(ModelAPI_ResultPart::group(), a));
675 if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
676 aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
680 if (aDoc != theDoc) { // so, the first word is the document name => reduce the string for the next manips
681 aSubShapeName = theSubShapeName.substr(aSlash + 1);
685 std::string aContName = getContextName(aSubShapeName);
686 if(aContName.empty()) return false;
687 ResultPtr aCont = aDoc->findByName(aContName);
688 // possible this is body where postfix is added to distinguish several shapes on the same label
689 int aSubShapeId = -1; // -1 means sub shape not found
690 // for result body the name wihtout "_" has higher priority than with it: it is always added
691 if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
692 aContName == aSubShapeName) {
693 size_t aPostIndex = aContName.rfind('_');
694 if (aPostIndex != std::string::npos) {
695 std::string aSubContName = aContName.substr(0, aPostIndex);
696 ResultPtr aSubCont = aDoc->findByName(aSubContName);
697 if (aSubCont.get()) {
699 std::string aNum = aContName.substr(aPostIndex + 1);
700 aSubShapeId = std::stoi(aNum);
701 } catch (std::invalid_argument&) {
704 if (aSubShapeId > 0) {
705 aContName = aSubContName;
713 TopoDS_Shape aSelection;
719 aSelection = findFaceByName(aSubShapeName, aDoc);
724 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
725 if(!aLabel.IsNull()) {
726 Handle(TNaming_NamedShape) aNS;
727 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
728 aSelection = getShapeFromNS(aSubShapeName, aNS);
735 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
736 if(!aLabel.IsNull()) {
737 Handle(TNaming_NamedShape) aNS;
738 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
739 aSelection = getShapeFromNS(aSubShapeName, aNS);
744 case TopAbs_COMPOUND:
745 case TopAbs_COMPSOLID:
748 default: {//TopAbs_SHAPE
749 /// case when the whole sketch is selected, so, selection type is compound, but there is no value
750 if (aCont.get() && aCont->shape().get()) {
751 if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
754 } else if (aSubShapeId > 0) { // try to find sub-shape by the index
755 TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
756 for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
760 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
761 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
762 theShapeToBeSelected = aShapeToBeSelected;
771 // another try to find edge or vertex by faces
772 std::list<std::string> aListofNames;
773 size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
774 if (aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) {
775 if(aN > 1 && (aN < 4 || (aType == TopAbs_EDGE && aN < 5))) { // 2 || 3 or 4 for EDGE
776 TopTools_ListOfShape aList;
777 std::list<std::string>::iterator it = aListofNames.begin();
778 for(; it != aListofNames.end(); it++){
779 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
783 aSelection = findCommonShape(aType, aList);
786 // in case of construction, there is no registered names for all sub-elements,
787 // even for the main element; so, trying to find them by name (without "&" intersections)
789 size_t aConstrNamePos = aSubShapeName.find("/");
790 bool isFullName = aConstrNamePos == std::string::npos;
791 std::string aContrName = aContName;
792 ResultPtr aConstr = aDoc->findByName(aContrName);
793 if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
796 // For the full construction selection shape must be empty.
797 //theShapeToBeSelected = aConstr->shape();
800 // for sketch sub-elements selected
801 CompositeFeaturePtr aComposite =
802 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
803 if (aComposite.get()) {
804 if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
805 // collect all IDs in the name
806 std::map<int, int> anIDs;
807 if (!parseSubIndices(aComposite, aSubShapeName,
808 aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs))
811 const int aSubNum = aComposite->numberOfSubs();
812 for(int a = 0; a < aSubNum; a++) {
813 int aCompID = aComposite->subFeatureId(a);
814 if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
815 FeaturePtr aSub = aComposite->subFeature(a);
816 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
817 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
818 // there may be many shapes (circle and center)
819 for(; aRIt != aResults.cend(); aRIt++) {
820 ResultConstructionPtr aRes =
821 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
823 int anOrientation = abs(anIDs[aCompID]);
824 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
825 if (anOrientation == 1) {
826 if (aType == aShape.ShapeType()) {
827 theShapeToBeSelected = aRes->shape();
830 } else { // take first or second vertex of the edge
831 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
832 TopExp_Explorer anExp(aShape, aType);
833 for(; anExp.More() && anOrientation != 2; anOrientation--)
836 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
837 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
838 theShapeToBeSelected = aShapeToBeSelected;
846 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
847 } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
848 std::map<int, int> anIDs;
849 if (!parseSubIndices(aComposite, aSubShapeName,
850 aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
853 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
854 const int aSubNum = aComposite->numberOfSubs();
855 for(int a = 0; a < aSubNum; a++) {
856 int aSubID = aComposite->subFeatureId(a);
857 if (anIDs.find(aSubID) != anIDs.end()) {
858 FeaturePtr aSub = aComposite->subFeature(a);
859 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
860 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
861 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
862 ResultConstructionPtr aConstr =
863 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
864 if (aConstr->shape() && aConstr->shape()->isEdge()) {
865 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
866 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
867 if (!anEdge.IsNull()) {
868 Standard_Real aFirst, aLast;
869 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
870 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
876 std::shared_ptr<GeomAPI_Shape> aFoundFW =
877 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
878 if (aFoundFW.get()) {
879 theShapeToBeSelected = aFoundFW;
882 } else if (aType == TopAbs_WIRE) { // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
883 std::map<int, int> anIDs;
884 if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
887 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
888 const int aSubNum = aComposite->numberOfSubs();
889 for(int a = 0; a < aSubNum; a++) {
890 int aSubID = aComposite->subFeatureId(a);
891 if (anIDs.find(aSubID) != anIDs.end()) {
892 FeaturePtr aSub = aComposite->subFeature(a);
893 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
894 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
895 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
896 ResultConstructionPtr aConstr =
897 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
898 if (aConstr->shape() && aConstr->shape()->isEdge()) {
899 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
900 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
901 if (!anEdge.IsNull()) {
902 Standard_Real aFirst, aLast;
903 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
904 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
910 std::shared_ptr<GeomAPI_Shape> aFoundFW =
911 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
912 if (aFoundFW.get()) {
913 theShapeToBeSelected = aFoundFW;
920 if (!aSelection.IsNull()) {// Select it (must be after N=0 checking, since for simple constructions the shape must be null)
921 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
922 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
923 theShapeToBeSelected = aShapeToBeSelected;