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 "Model_Data.h"
11 #include <ModelAPI_Feature.h>
12 #include <Events_InfoMessage.h>
13 #include <ModelAPI_Session.h>
14 #include <ModelAPI_ResultPart.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_CompositeFeature.h>
17 #include <ModelAPI_ResultBody.h>
18 #include <GeomAPI_Wire.h>
20 #include <TopoDS_Iterator.hxx>
22 #include <TopoDS_Compound.hxx>
24 #include <TopExp_Explorer.hxx>
25 #include <TopTools_ListOfShape.hxx>
26 #include <TopTools_MapOfShape.hxx>
27 #include <TopTools_IndexedMapOfShape.hxx>
28 #include <TopTools_ListIteratorOfListOfShape.hxx>
29 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
30 #include <TopTools_MapIteratorOfMapOfShape.hxx>
31 #include <BRep_Builder.hxx>
32 #include <TNaming_Iterator.hxx>
33 #include <TNaming_Tool.hxx>
34 #include <TNaming_NamedShape.hxx>
35 #include <TNaming_Localizer.hxx>
36 #include <TDataStd_Name.hxx>
37 #include <TColStd_MapOfTransient.hxx>
42 #include <BRepTools.hxx>
45 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
47 myLab = theSelectionLab;
50 std::string Model_SelectionNaming::getShapeName(
51 std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
52 ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
55 // add the result name to the name of the shape
56 // (it was in BodyBuilder, but did not work on Result rename)
57 bool isNeedContextName = theContext->shape().get() != NULL;
58 // && !theContext->shape()->isEqual(theSubSh);
59 // check if the subShape is already in DF
60 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
61 Handle(TDataStd_Name) anAttr;
62 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
63 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
64 std::shared_ptr<Model_Data> aData =
65 std::dynamic_pointer_cast<Model_Data>(theContext->data());
66 if (isNeedContextName && aData && aData->label().IsEqual(aNS->Label())) {
67 // do nothing because this context name will be added later in this method
69 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
70 // indexes are added to sub-shapes not primitives
71 // (primitives must not be located at the same label)
72 if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && isNeedContextName) {
73 const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
74 static const std::string aPostFix("_");
75 TNaming_Iterator anItL(aNS);
76 for(int i = 1; anItL.More(); anItL.Next(), i++) {
77 // in #1766 IsEqual produced no index of the face
78 if(anItL.NewShape().IsSame(theShape)) {
80 aName += TCollection_AsciiString (i).ToCString();
85 // if a shape is under another context, use this name, not theContext
86 std::shared_ptr<Model_Data> aContextData =
87 std::dynamic_pointer_cast<Model_Data>(theContext->data());
88 // for constructions the naming is in arguments and has no evolution, so, apply this only
90 if (isNeedContextName && theContext->groupName() == ModelAPI_ResultBody::group() &&
91 !aNS->Label().IsDescendant(aContextData->label())) {
92 isNeedContextName = false;
93 TDF_Label aNSDataLab = aNS->Label();
94 while(aNSDataLab.Depth() != 7 && aNSDataLab.Depth() > 5)
95 aNSDataLab = aNSDataLab.Father();
96 ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
97 if (!aNewContext.get() && aNSDataLab.Depth() == 7) {
98 aNSDataLab = aNSDataLab.Father().Father();
99 aNewContext = theDoc->objects()->object(aNSDataLab);
101 if (aNewContext.get()) {
102 aName = aNewContext->data()->name() + "/" + aName;
109 // Name is empty and this is full context, it just add the whole context name that must be added
110 bool isEmptyName = aName.empty();
111 if (isNeedContextName && (!isEmptyName || theWholeContext)) {
112 aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
114 aName = theContext->document()->kind() + "/" + aName; // PartSet
119 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
121 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
122 TopoDS_Compound aCmp;
124 BB.MakeCompound(aCmp);
125 TopTools_ListIteratorOfListOfShape it(theAncestors);
126 for(;it.More();it.Next()) {
127 BB.Add(aCmp, it.Value());
128 theSMap.Add(it.Value());
131 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
132 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
133 for (int i = 1; i <= aMap2.Extent(); i++) {
134 const TopoDS_Shape& aKey = aMap2.FindKey(i);
135 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
136 if(anAncestors.Extent() > 1) aNumber++;
138 if(aNumber > 1) return false;
142 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
143 std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
144 const bool theAnotherDoc)
146 std::string aName("Undefined name");
147 if(!theContext.get() || theContext->shape()->isNull())
148 return !theDefaultName.empty() ? theDefaultName : aName;
150 // if it is in result of another part
151 std::shared_ptr<Model_Document> aDoc =
152 std::dynamic_pointer_cast<Model_Document>(theContext->document());
153 if (theContext->groupName() == ModelAPI_ResultPart::group()) {
154 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
157 return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
159 return aPart->data()->name();
162 if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
163 // but if it is in another Part, add this part name
164 std::string aPartName;
166 aPartName = theContext->document()->kind() + "/"; // PartSet
167 return aPartName + theContext->data()->name();
169 TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
170 TopoDS_Shape aContext = theContext->shape()->impl<TopoDS_Shape>();
172 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
173 BRepTools::Write(aSubShape, "Selection.brep");
174 BRepTools::Write(aContext, "Context.brep");
177 aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
178 theContext->shape()->isEqual(theSubSh));
180 if(aName.empty() ) { // not in the document!
181 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
184 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
188 // name structure: F1 & F2 [& F3 & F4],
189 // where F1 & F2 the faces which gives the Edge in trivial case
190 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
191 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
192 aName = "Degenerated_Edge";
195 TopTools_IndexedDataMapOfShapeListOfShape aMap;
196 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
197 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
198 bool isTrivialCase(true);
199 if(aMap.Contains(aSubShape)) {
200 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
201 // check that it is not a trivial case (F1 & F2: aNumber = 1)
202 isTrivialCase = isTrivial(anAncestors, aSMap);
205 TopTools_ListOfShape aListOfNbs;
206 if(!isTrivialCase) { // find Neighbors
207 TNaming_Localizer aLocalizer;
208 TopTools_MapOfShape aMap3;
209 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
210 //int n = aMap3.Extent();
211 TopTools_MapIteratorOfMapOfShape it(aMap3);
212 for(;it.More();it.Next()) {
213 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
214 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
215 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
216 TopTools_ListIteratorOfListOfShape it2(aList);
217 for(;it2.More();it2.Next()) {
218 if(aSMap.Contains(it2.Value())) continue; // skip this Face
219 aListOfNbs.Append(it2.Value());
222 } // else a trivial case
224 // build name of the sub-shape Edge
225 for(int i=1; i <= aSMap.Extent(); i++) {
226 const TopoDS_Shape& aFace = aSMap.FindKey(i);
227 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
231 aName += "&" + aFaceName;
233 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
234 for (;itl.More();itl.Next()) {
235 std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
236 aName += "&" + aFaceName;
242 // name structure (Monifold Topology):
243 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
244 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
245 // but it should be kept as is to obtain safe recomputation
246 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
247 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
248 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
249 // or compound of 2 open faces.
250 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
251 // two independent edges (wire or compound)
252 // implemented 2 first cases
254 TopTools_IndexedDataMapOfShapeListOfShape aMap;
255 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
256 TopTools_ListOfShape aList;
257 TopTools_MapOfShape aFMap;
258 // simetimes when group is moved in history, naming may be badly updated, so
259 // avoid crash in FindFromKey (issue 1842)
260 if (aMap.Contains(aSubShape)) {
261 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
263 TopTools_ListIteratorOfListOfShape itl2(aList2);
264 for (int i = 1;itl2.More();itl2.Next(),i++) {
265 if(aFMap.Add(itl2.Value()))
266 aList.Append(itl2.Value());
270 int n = aList.Extent();
271 bool isByFaces = n >= 3;
272 if(!isByFaces) { // open topology case or Compound case => via edges
273 TopTools_IndexedDataMapOfShapeListOfShape aMap;
274 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
275 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
276 if(aList22.Extent() >= 2) { // regular solution
278 // bug! duplication; fix is below
280 TopTools_ListOfShape aListE;
281 TopTools_ListIteratorOfListOfShape itl2(aList22);
282 for (int i = 1;itl2.More();itl2.Next(),i++) {
283 if(aFMap.Add(itl2.Value()))
284 aListE.Append(itl2.Value());
287 TopTools_ListIteratorOfListOfShape itl(aListE);
288 for (int i = 1;itl.More();itl.Next(),i++) {
289 const TopoDS_Shape& anEdge = itl.Value();
290 std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
291 if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
299 aName += "&" + anEdgeName;
302 else { // dangle vertex: if(aList22.Extent() == 1)
303 //it should be already in DF
307 TopTools_ListIteratorOfListOfShape itl(aList);
308 for (int i = 1;itl.More();itl.Next(),i++) {
309 const TopoDS_Shape& aFace = itl.Value();
310 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
314 aName += "&" + aFaceName;
325 TopAbs_ShapeEnum translateType (const std::string& theType)
327 // map from the textual shape types to OCCT enumeration
328 static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
330 if(aShapeTypes.size() == 0) {
331 aShapeTypes["compound"] = TopAbs_COMPOUND;
332 aShapeTypes["compounds"] = TopAbs_COMPOUND;
333 aShapeTypes["compsolid"] = TopAbs_COMPSOLID;
334 aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
335 aShapeTypes["solid"] = TopAbs_SOLID;
336 aShapeTypes["solids"] = TopAbs_SOLID;
337 aShapeTypes["shell"] = TopAbs_SHELL;
338 aShapeTypes["shells"] = TopAbs_SHELL;
339 aShapeTypes["face"] = TopAbs_FACE;
340 aShapeTypes["faces"] = TopAbs_FACE;
341 aShapeTypes["wire"] = TopAbs_WIRE;
342 aShapeTypes["wires"] = TopAbs_WIRE;
343 aShapeTypes["edge"] = TopAbs_EDGE;
344 aShapeTypes["edges"] = TopAbs_EDGE;
345 aShapeTypes["vertex"] = TopAbs_VERTEX;
346 aShapeTypes["vertices"] = TopAbs_VERTEX;
347 aShapeTypes["COMPOUND"] = TopAbs_COMPOUND;
348 aShapeTypes["COMPOUNDS"] = TopAbs_COMPOUND;
349 aShapeTypes["COMPSOLID"] = TopAbs_COMPSOLID;
350 aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
351 aShapeTypes["SOLID"] = TopAbs_SOLID;
352 aShapeTypes["SOLIDS"] = TopAbs_SOLID;
353 aShapeTypes["SHELL"] = TopAbs_SHELL;
354 aShapeTypes["SHELLS"] = TopAbs_SHELL;
355 aShapeTypes["FACE"] = TopAbs_FACE;
356 aShapeTypes["FACES"] = TopAbs_FACE;
357 aShapeTypes["WIRE"] = TopAbs_WIRE;
358 aShapeTypes["WIRES"] = TopAbs_WIRE;
359 aShapeTypes["EDGE"] = TopAbs_EDGE;
360 aShapeTypes["EDGES"] = TopAbs_EDGE;
361 aShapeTypes["VERTEX"] = TopAbs_VERTEX;
362 aShapeTypes["VERTICES"] = TopAbs_VERTEX;
364 if (aShapeTypes.find(theType) != aShapeTypes.end())
365 return aShapeTypes[theType];
366 Events_InfoMessage("Model_SelectionNaming",
367 "Shape type defined in XML is not implemented!").send();
371 const TopoDS_Shape getShapeFromNS(
372 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
374 TopoDS_Shape aSelection;
375 std::string::size_type n = theSubShapeName.rfind('/');
376 if (n == std::string::npos) n = -1;
377 std::string aSubString = theSubShapeName.substr(n + 1);
378 n = aSubString.rfind('_');
380 if (n != std::string::npos) {// for primitives this is a first
381 // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
382 Handle(TDataStd_Name) aName;
383 if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
384 aName->Get() != aSubString.c_str()) {
385 aSubString = aSubString.substr(n+1);
386 indx = atoi(aSubString.c_str());
390 TNaming_Iterator anItL(theNS);
391 for(int i = 1; anItL.More(); anItL.Next(), i++) {
393 return anItL.NewShape();
399 const TopoDS_Shape findFaceByName(
400 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
403 //std::string::size_type n, nb = theSubShapeName.rfind('/');
404 //if (nb == std::string::npos) nb = 0;
405 //std::string aSubString = theSubShapeName.substr(nb + 1);
406 std::string aSubString = theSubShapeName;
408 TDF_Label aLabel = theDoc->findNamingName(aSubString);
409 if (aLabel.IsNull()) { // try to remove additional artificial suffix
410 std::string::size_type n = aSubString.rfind('_');
411 if (n != std::string::npos) {
412 aSubString = aSubString.substr(0, n);
413 aLabel = theDoc->findNamingName(aSubString);
416 if(aLabel.IsNull()) return aFace;
417 Handle(TNaming_NamedShape) aNS;
418 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
419 aFace = getShapeFromNS(theSubShapeName, aNS);
424 size_t ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
426 std::string aName = theSubShapeName;
427 std::string aLastName;
428 size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
429 while ((n2 = aName.find('&', n1)) != std::string::npos) {
430 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
431 theList.push_back(aName1);
433 aLastName = aName.substr(n1);
435 if(!aLastName.empty())
436 theList.push_back(aLastName);
437 return theList.size();
440 const TopoDS_Shape findCommonShape(
441 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
443 if(theList.IsEmpty() || theList.Extent() == 1) {
444 return TopoDS_Shape();
448 std::vector<TopTools_MapOfShape> aVec;
449 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
450 if(theList.Extent() > 1) {
451 aVec.push_back(aMap1);
452 aVec.push_back(aMap2);
454 if(theList.Extent() > 2)
455 aVec.push_back(aMap3);
456 if(theList.Extent() == 4)
457 aVec.push_back(aMap4);
460 TopTools_ListIteratorOfListOfShape it(theList);
461 for(int i = 0;it.More();it.Next(),i++) {
462 const TopoDS_Shape& aFace = it.Value();
464 TopExp_Explorer anExp (aFace, theType);
465 for(;anExp.More();anExp.Next()) {
466 const TopoDS_Shape& anEdge = anExp.Current();
467 if (!anEdge.IsNull())
468 aVec[i].Add(anExp.Current());
471 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
472 for(;anExp.More();anExp.Next()) {
473 const TopoDS_Shape& aVertex = anExp.Current();
474 if (!aVertex.IsNull())
475 aVec[i].Add(anExp.Current());
479 //trivial case: 2 faces
480 TopTools_ListOfShape aList;
481 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
482 for(;it2.More();it2.Next()) {
483 if(aVec[1].Contains(it2.Key())) {
485 if(theList.Extent() == 2)
488 aList.Append(it2.Key());
491 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
492 if(aVec[2].Extent() && aVec[3].Extent()) {
493 TopTools_ListIteratorOfListOfShape it(aList);
494 for(;it.More();it.Next()) {
495 const TopoDS_Shape& aCand = it.Value();
496 // not yet completelly implemented, to be rechecked
497 TopoDS_Vertex aV1, aV2;
498 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
500 if(aVec[2].Contains(aV1)) aNum++;
501 else if(aVec[2].Contains(aV2)) aNum++;
502 if(aVec[3].Contains(aV1)) aNum++;
503 else if(aVec[3].Contains(aV2)) aNum++;
512 if(aList.Extent() && aVec.size() == 3) {
514 TopTools_ListIteratorOfListOfShape it(aList);
515 for(;it.More();it.Next()) {
516 const TopoDS_Shape& aCand = it.Value();
517 if(aVec[2].Contains(aCand)) {
526 std::string getContextName(const std::string& theSubShapeName)
529 std::string::size_type n = theSubShapeName.find('/');
530 if (n == std::string::npos) return theSubShapeName;
531 aName = theSubShapeName.substr(0, n);
535 /// Parses naming name of sketch sub-elements: takes indices and orientation
536 /// (if theOriented = true) from this name. Map theIDs constains indices ->
537 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
538 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
539 const std::string& theName, const char* theShapeType,
540 std::map<int, int>& theIDs, const bool theOriented = false)
542 // collect all IDs in the name
543 std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
544 const int aSubNum = theComp->numberOfSubs();
545 for(int a = 0; a < aSubNum; a++) {
546 FeaturePtr aSub = theComp->subFeature(a);
547 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
548 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
549 // there may be many shapes (circle and center)
550 for(; aRes != aResults.cend(); aRes++) {
551 ResultConstructionPtr aConstr =
552 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
554 aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
559 size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
560 bool isShape = false; // anyway the first world must be 'Vertex'
562 aLastNamePos = theName.find('-', aPrevPos);
563 std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
565 if (anID != theShapeType)
569 int anOrientation = 1; // default
570 if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
571 std::string::iterator aSymbol = anID.end() - 1;
572 if (*aSymbol == 'r') anOrientation = -1;
573 anID.erase(aSymbol); // remove last symbol
575 // check start/end symbols
576 std::string::iterator aBack = anID.end() - 1;
579 anID.erase(aBack); // remove last symbol
580 } else if (*aBack == 'e') {
582 anID.erase(aBack); // remove last symbol
585 if (aNames.find(anID) != aNames.end()) {
586 theIDs[aNames[anID]] = anOrientation;
589 aPrevPos = aLastNamePos + 1;
590 } while (aLastNamePos != std::string::npos);
594 /// produces theEdge orientation relatively to theContext face
595 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
597 if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
599 if (theEdge.Orientation() == TopAbs_FORWARD)
601 if (theEdge.Orientation() == TopAbs_REVERSED)
606 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
607 std::shared_ptr<ModelAPI_Result>& theConstr,
608 NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
610 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
611 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
612 std::shared_ptr<GeomAPI_Shape> aResult;
613 ResultConstructionPtr aConstructionContext =
614 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
615 if (!aConstructionContext.get())
617 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
618 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
620 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
621 std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
623 for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
624 aFacesWires.push_back(aWires.Current());
627 aFacesWires.push_back(aFace);
629 std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
630 for(; aFW != aFacesWires.end(); aFW++) {
631 TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
632 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
633 for(; anEdgesExp.More(); anEdgesExp.Next()) {
634 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
635 if (!anEdge.IsNull()) {
636 Standard_Real aFirst, aLast;
637 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
638 if (alreadyProcessed.Contains(aCurve))
640 alreadyProcessed.Add(aCurve);
641 if (theCurves.IsBound(aCurve)) {
643 int anOrient = theCurves.Find(aCurve);
644 if (anOrient != 0) { // extra comparision score is orientation
645 if (edgeOrientation(aFace, anEdge) == anOrient)
653 if (aFound + aNotFound != 0) {
654 if (aFound > aBestFound ||
655 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
657 aBestOrient = aSameOrientation;
659 std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
660 aWire->setImpl(new TopoDS_Shape(*aFW));
663 aResult = aConstructionContext->face(aFaceIndex);
672 std::string Model_SelectionNaming::shortName(
673 std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
675 std::string aName = theConstr->data()->name();
676 // remove "-", "/" and "&" command-symbols
677 aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
678 aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
679 aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
680 // remove the last 's', 'e', 'f' and 'r' symbols:
681 // they are used as markers of start/end/forward/rewersed indicators
682 static const std::string aSyms("sefr");
683 std::string::iterator aSuffix = aName.end() - 1;
684 while(aSyms.find(*aSuffix) != std::string::npos) {
687 aName.erase(aSuffix + 1, aName.end());
689 if (theEdgeVertexPos == 1) {
690 aName += "s"; // start
691 } else if (theEdgeVertexPos == 2) {
697 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
698 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
699 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
700 std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
702 if(theSubShapeName.empty() || theType.empty()) return false;
703 TopAbs_ShapeEnum aType = translateType(theType);
705 // check that it was selected in another document
706 size_t aSlash = theSubShapeName.find("/");
707 std::string aSubShapeName = theSubShapeName;
708 std::shared_ptr<Model_Document> aDoc = theDoc;
709 if (aSlash != std::string::npos) {
710 std::string aDocName = theSubShapeName.substr(0, aSlash);
711 ResultPartPtr aFoundPart;
712 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
713 if (aDocName == aRootDoc->kind()) {
714 aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
716 for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
717 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
718 aRootDoc->object(ModelAPI_ResultPart::group(), a));
719 if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
720 aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
726 if (aDoc != theDoc) {
727 // so, the first word is the document name => reduce the string for the next manips
728 aSubShapeName = theSubShapeName.substr(aSlash + 1);
729 if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
730 theCont = aFoundPart;
736 std::string aContName = getContextName(aSubShapeName);
737 if(aContName.empty()) return false;
738 ResultPtr aCont = aDoc->findByName(aContName);
739 // possible this is body where postfix is added to distinguish several shapes on the same label
740 int aSubShapeId = -1; // -1 means sub shape not found
741 // for result body the name wihtout "_" has higher priority than with it: it is always added
742 if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
743 aContName == aSubShapeName) {
744 size_t aPostIndex = aContName.rfind('_');
745 if (aPostIndex != std::string::npos) {
746 std::string aSubContName = aContName.substr(0, aPostIndex);
747 ResultPtr aSubCont = aDoc->findByName(aSubContName);
748 if (aSubCont.get()) {
750 std::string aNum = aContName.substr(aPostIndex + 1);
751 aSubShapeId = std::stoi(aNum);
752 } catch (std::invalid_argument&) {
755 if (aSubShapeId > 0) {
756 aContName = aSubContName;
764 TopoDS_Shape aSelection;
770 aSelection = findFaceByName(aSubShapeName, aDoc);
775 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
776 if(!aLabel.IsNull()) {
777 Handle(TNaming_NamedShape) aNS;
778 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
779 aSelection = getShapeFromNS(aSubShapeName, aNS);
786 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
787 if(!aLabel.IsNull()) {
788 Handle(TNaming_NamedShape) aNS;
789 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
790 aSelection = getShapeFromNS(aSubShapeName, aNS);
795 case TopAbs_COMPOUND:
796 case TopAbs_COMPSOLID:
799 default: {//TopAbs_SHAPE
800 /// case when the whole sketch is selected, so,
801 /// selection type is compound, but there is no value
802 if (aCont.get() && aCont->shape().get()) {
803 if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
806 } else if (aSubShapeId > 0) { // try to find sub-shape by the index
807 TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
808 for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
812 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
813 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
814 theShapeToBeSelected = aShapeToBeSelected;
823 // another try to find edge or vertex by faces
824 std::list<std::string> aListofNames;
825 size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
826 if (aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) {
827 if(aN > 1 && (aN < 4 || (aType == TopAbs_EDGE && aN < 5))) { // 2 || 3 or 4 for EDGE
828 TopTools_ListOfShape aList;
829 std::list<std::string>::iterator it = aListofNames.begin();
830 for(; it != aListofNames.end(); it++){
831 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
835 aSelection = findCommonShape(aType, aList);
838 // in case of construction, there is no registered names for all sub-elements,
839 // even for the main element; so, trying to find them by name (without "&" intersections)
841 size_t aConstrNamePos = aSubShapeName.find("/");
842 bool isFullName = aConstrNamePos == std::string::npos;
843 std::string aContrName = aContName;
844 ResultPtr aConstr = aDoc->findByName(aContrName);
845 if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
848 // For the full construction selection shape must be empty.
849 //theShapeToBeSelected = aConstr->shape();
852 // for sketch sub-elements selected
853 CompositeFeaturePtr aComposite =
854 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
855 if (aComposite.get()) {
856 if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
857 // collect all IDs in the name
858 std::map<int, int> anIDs;
859 if (!parseSubIndices(aComposite, aSubShapeName,
860 aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs))
863 const int aSubNum = aComposite->numberOfSubs();
864 for(int a = 0; a < aSubNum; a++) {
865 int aCompID = aComposite->subFeatureId(a);
866 if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
867 FeaturePtr aSub = aComposite->subFeature(a);
868 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
869 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
870 // there may be many shapes (circle and center)
871 for(; aRIt != aResults.cend(); aRIt++) {
872 ResultConstructionPtr aRes =
873 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
875 int anOrientation = abs(anIDs[aCompID]);
876 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
877 if (anOrientation == 1) {
878 if (aType == aShape.ShapeType()) {
879 theShapeToBeSelected = aRes->shape();
882 } else { // take first or second vertex of the edge
883 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
884 TopExp_Explorer anExp(aShape, aType);
885 for(; anExp.More() && anOrientation != 2; anOrientation--)
888 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
889 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
890 theShapeToBeSelected = aShapeToBeSelected;
898 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
899 } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
900 std::map<int, int> anIDs;
901 if (!parseSubIndices(aComposite, aSubShapeName,
902 aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
905 // curves and orientations of edges
906 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
907 const int aSubNum = aComposite->numberOfSubs();
908 for(int a = 0; a < aSubNum; a++) {
909 int aSubID = aComposite->subFeatureId(a);
910 if (anIDs.find(aSubID) != anIDs.end()) {
911 FeaturePtr aSub = aComposite->subFeature(a);
912 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
913 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
914 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
915 ResultConstructionPtr aConstr =
916 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
917 if (aConstr->shape() && aConstr->shape()->isEdge()) {
918 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
919 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
920 if (!anEdge.IsNull()) {
921 Standard_Real aFirst, aLast;
922 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
923 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
929 std::shared_ptr<GeomAPI_Shape> aFoundFW =
930 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
931 if (aFoundFW.get()) {
932 theShapeToBeSelected = aFoundFW;
935 } else if (aType == TopAbs_WIRE) {
936 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
937 std::map<int, int> anIDs;
938 if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
941 // curves and orientations of edges
942 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
943 const int aSubNum = aComposite->numberOfSubs();
944 for(int a = 0; a < aSubNum; a++) {
945 int aSubID = aComposite->subFeatureId(a);
946 if (anIDs.find(aSubID) != anIDs.end()) {
947 FeaturePtr aSub = aComposite->subFeature(a);
948 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
949 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
950 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
951 ResultConstructionPtr aConstr =
952 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
953 if (aConstr->shape() && aConstr->shape()->isEdge()) {
954 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
955 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
956 if (!anEdge.IsNull()) {
957 Standard_Real aFirst, aLast;
958 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
959 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
965 std::shared_ptr<GeomAPI_Shape> aFoundFW =
966 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
967 if (aFoundFW.get()) {
968 theShapeToBeSelected = aFoundFW;
975 if (!aSelection.IsNull()) {
976 // Select it (must be after N=0 checking,
977 // since for simple constructions the shape must be null)
978 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
979 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
980 theShapeToBeSelected = aShapeToBeSelected;