1 // Copyright (C) 2014-2017 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include "Model_SelectionNaming.h"
22 #include "Model_Document.h"
23 #include "Model_Objects.h"
24 #include "Model_Data.h"
25 #include <ModelAPI_Feature.h>
26 #include <Events_InfoMessage.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_ResultPart.h>
29 #include <ModelAPI_ResultConstruction.h>
30 #include <ModelAPI_CompositeFeature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <GeomAPI_Wire.h>
34 #include <TopoDS_Iterator.hxx>
36 #include <TopoDS_Compound.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopTools_ListOfShape.hxx>
40 #include <TopTools_MapOfShape.hxx>
41 #include <TopTools_IndexedMapOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_MapIteratorOfMapOfShape.hxx>
45 #include <BRep_Builder.hxx>
46 #include <TNaming_Iterator.hxx>
47 #include <TNaming_Tool.hxx>
48 #include <TNaming_NamedShape.hxx>
49 #include <TNaming_Localizer.hxx>
50 #include <TDataStd_Name.hxx>
51 #include <TColStd_MapOfTransient.hxx>
56 #include <BRepTools.hxx>
59 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
61 myLab = theSelectionLab;
64 std::string Model_SelectionNaming::getShapeName(
65 std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
66 ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
69 // add the result name to the name of the shape
70 // (it was in BodyBuilder, but did not work on Result rename)
71 bool isNeedContextName = theContext->shape().get() != NULL;
72 // check if the subShape is already in DF
73 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
74 Handle(TDataStd_Name) anAttr;
75 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
76 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
77 std::shared_ptr<Model_Data> aData =
78 std::dynamic_pointer_cast<Model_Data>(theContext->data());
79 if (isNeedContextName && aData && aData->label().IsEqual(aNS->Label())) {
80 // do nothing because this context name will be added later in this method
82 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
83 // indexes are added to sub-shapes not primitives
84 // (primitives must not be located at the same label)
85 if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && isNeedContextName) {
86 const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
87 static const std::string aPostFix("_");
88 TNaming_Iterator anItL(aNS);
89 for(int i = 1; anItL.More(); anItL.Next(), i++) {
90 // in #1766 IsEqual produced no index of the face
91 if(anItL.NewShape().IsSame(theShape)) {
93 aName += TCollection_AsciiString (i).ToCString();
98 // if a shape is under another context, use this name, not theContext
99 std::shared_ptr<Model_Data> aContextData =
100 std::dynamic_pointer_cast<Model_Data>(theContext->data());
101 // for constructions the naming is in arguments and has no evolution, so, apply this only
103 if (isNeedContextName && theContext->groupName() == ModelAPI_ResultBody::group() &&
104 !aNS->Label().IsDescendant(aContextData->label())) {
105 isNeedContextName = false;
106 TDF_Label aNSDataLab = aNS->Label();
107 while(aNSDataLab.Depth() != 7 && aNSDataLab.Depth() > 5)
108 aNSDataLab = aNSDataLab.Father();
109 ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
110 if (!aNewContext.get() && aNSDataLab.Depth() == 7) {
111 aNSDataLab = aNSDataLab.Father().Father();
112 aNewContext = theDoc->objects()->object(aNSDataLab);
114 if (aNewContext.get()) {
115 aName = aNewContext->data()->name() + "/" + aName;
122 // Name is empty and this is full context, it just add the whole context name that must be added
123 bool isEmptyName = aName.empty();
124 if (isNeedContextName && (!isEmptyName || theWholeContext)) {
125 aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
127 aName = theContext->document()->kind() + "/" + aName; // PartSet
132 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
134 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
135 TopoDS_Compound aCmp;
137 BB.MakeCompound(aCmp);
138 TopTools_ListIteratorOfListOfShape it(theAncestors);
139 for(;it.More();it.Next()) {
140 if (theSMap.Contains(it.Value()))
142 BB.Add(aCmp, it.Value());
143 theSMap.Add(it.Value());
146 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
147 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
148 for (int i = 1; i <= aMap2.Extent(); i++) {
149 const TopoDS_Shape& aKey = aMap2.FindKey(i);
150 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
151 if(anAncestors.Extent() > 1) aNumber++;
153 if(aNumber > 1) return false;
157 const TopoDS_Shape findCommonShape(
158 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
160 if(theList.Extent() < 1) {
161 return TopoDS_Shape();
162 } else if (theList.Extent() == 1) { // check that sub-shape is bounded by this alone shape
163 TopTools_MapOfShape aSubsInShape;
164 TopExp_Explorer anExp(theList.First(), theType);
165 for(; anExp.More(); anExp.Next()) {
166 if (aSubsInShape.Contains(anExp.Current())) { // found duplicate
167 return anExp.Current();
169 aSubsInShape.Add(anExp.Current());
173 // Store in maps sub-shapes from each face.
174 std::vector<TopTools_MapOfShape> aVec;
175 for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) {
176 const TopoDS_Shape aFace = anIt.Value();
177 TopTools_MapOfShape aMap;
178 for(TopExp_Explorer anExp(aFace, theType); anExp.More(); anExp.Next()) {
179 const TopoDS_Shape& aSubShape = anExp.Current();
180 aMap.Add(anExp.Current());
182 aVec.push_back(aMap);
185 // Find sub-shape shared between all faces.
186 TopoDS_Shape aSharedShape;
187 for(TopTools_MapIteratorOfMapOfShape anIt(aVec[0]); anIt.More(); anIt.Next()) {
188 const TopoDS_Shape& aSubShape = anIt.Value();
190 for(int anIndex = 1; anIndex < aVec.size(); ++anIndex) {
191 if(aVec[anIndex].Contains(aSubShape)) {
195 if(aSharedNb == theList.Extent()) {
196 if(aSharedShape.IsNull()) {
197 aSharedShape = aSubShape;
199 // More than one shape shared between all faces, return null shape in this case.
200 return TopoDS_Shape();
208 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
209 std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
210 const bool theAnotherDoc)
212 std::string aName("Undefined name");
214 || !theContext->shape().get()
215 || theContext->shape()->isNull()) {
216 return !theDefaultName.empty() ? theDefaultName : aName;
219 // if it is in result of another part
220 std::shared_ptr<Model_Document> aDoc =
221 std::dynamic_pointer_cast<Model_Document>(theContext->document());
222 if (theContext->groupName() == ModelAPI_ResultPart::group()) {
223 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
226 return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
228 return aPart->data()->name();
231 if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
232 // but if it is in another Part, add this part name
233 std::string aPartName;
235 aPartName = theContext->document()->kind() + "/"; // PartSet
236 return aPartName + theContext->data()->name();
238 TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
239 TopoDS_Shape aContext = theContext->shape()->impl<TopoDS_Shape>();
241 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
242 BRepTools::Write(aSubShape, "Selection.brep");
243 BRepTools::Write(aContext, "Context.brep");
246 aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
247 theContext->shape()->isEqual(theSubSh));
249 if(aName.empty() ) { // not in the document!
250 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
253 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
257 // name structure: F1 & F2 [& F3 & F4],
258 // where F1 & F2 the faces which gives the Edge in trivial case
259 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
260 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
261 aName = "Degenerated_Edge";
264 TopTools_IndexedDataMapOfShapeListOfShape aMap;
265 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
266 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
267 bool isTrivialCase(true);
268 if(aMap.Contains(aSubShape)) {
269 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
270 // check that it is not a trivial case (F1 & F2: aNumber = 1)
271 isTrivialCase = isTrivial(anAncestors, aSMap);
272 if (!isTrivialCase) { // another try: check that common shape can be processed anyway
273 isTrivialCase = !findCommonShape(TopAbs_EDGE, anAncestors).IsNull();
277 TopTools_ListOfShape aListOfNbs;
278 if(!isTrivialCase) { // find Neighbors
279 TNaming_Localizer aLocalizer;
280 TopTools_MapOfShape aMap3;
281 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
282 //int n = aMap3.Extent();
283 TopTools_MapIteratorOfMapOfShape it(aMap3);
284 for(;it.More();it.Next()) {
285 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
286 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
287 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
288 TopTools_ListIteratorOfListOfShape it2(aList);
289 for(;it2.More();it2.Next()) {
290 if(aSMap.Contains(it2.Value())) continue; // skip this Face
291 aListOfNbs.Append(it2.Value());
294 } // else a trivial case
296 // build name of the sub-shape Edge
297 for(int i=1; i <= aSMap.Extent(); i++) {
298 const TopoDS_Shape& aFace = aSMap.FindKey(i);
299 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
303 aName += "&" + aFaceName;
305 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
306 for (;itl.More();itl.Next()) {
307 std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
308 aName += "&" + aFaceName;
314 // name structure (Monifold Topology):
315 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
316 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
317 // but it should be kept as is to obtain safe recomputation
318 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
319 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
320 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
321 // or compound of 2 open faces.
322 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
323 // two independent edges (wire or compound)
324 // implemented 2 first cases
326 TopTools_IndexedDataMapOfShapeListOfShape aMap;
327 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
328 TopTools_ListOfShape aList;
329 TopTools_MapOfShape aFMap;
330 // simetimes when group is moved in history, naming may be badly updated, so
331 // avoid crash in FindFromKey (issue 1842)
332 if (aMap.Contains(aSubShape)) {
333 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
335 TopTools_ListIteratorOfListOfShape itl2(aList2);
336 for (int i = 1;itl2.More();itl2.Next(),i++) {
337 if(aFMap.Add(itl2.Value()))
338 aList.Append(itl2.Value());
342 int n = aList.Extent();
343 bool isByFaces = n >= 3;
344 if(!isByFaces) { // open topology case or Compound case => via edges
345 TopTools_IndexedDataMapOfShapeListOfShape aMap;
346 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
347 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
348 if(aList22.Extent() >= 2) { // regular solution
350 // bug! duplication; fix is below
352 TopTools_ListOfShape aListE;
353 TopTools_ListIteratorOfListOfShape itl2(aList22);
354 for (int i = 1;itl2.More();itl2.Next(),i++) {
355 if(aFMap.Add(itl2.Value()))
356 aListE.Append(itl2.Value());
359 TopTools_ListIteratorOfListOfShape itl(aListE);
360 for (int i = 1;itl.More();itl.Next(),i++) {
361 const TopoDS_Shape& anEdge = itl.Value();
362 std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
363 if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
371 aName += "&" + anEdgeName;
374 else { // dangle vertex: if(aList22.Extent() == 1)
375 //it should be already in DF
379 TopTools_ListIteratorOfListOfShape itl(aList);
380 for (int i = 1;itl.More();itl.Next(),i++) {
381 const TopoDS_Shape& aFace = itl.Value();
382 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
386 aName += "&" + aFaceName;
397 TopAbs_ShapeEnum translateType (const std::string& theType)
399 // map from the textual shape types to OCCT enumeration
400 static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
402 if(aShapeTypes.size() == 0) {
403 aShapeTypes["compound"] = TopAbs_COMPOUND;
404 aShapeTypes["compounds"] = TopAbs_COMPOUND;
405 aShapeTypes["compsolid"] = TopAbs_COMPSOLID;
406 aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
407 aShapeTypes["solid"] = TopAbs_SOLID;
408 aShapeTypes["solids"] = TopAbs_SOLID;
409 aShapeTypes["shell"] = TopAbs_SHELL;
410 aShapeTypes["shells"] = TopAbs_SHELL;
411 aShapeTypes["face"] = TopAbs_FACE;
412 aShapeTypes["faces"] = TopAbs_FACE;
413 aShapeTypes["wire"] = TopAbs_WIRE;
414 aShapeTypes["wires"] = TopAbs_WIRE;
415 aShapeTypes["edge"] = TopAbs_EDGE;
416 aShapeTypes["edges"] = TopAbs_EDGE;
417 aShapeTypes["vertex"] = TopAbs_VERTEX;
418 aShapeTypes["vertices"] = TopAbs_VERTEX;
419 aShapeTypes["COMPOUND"] = TopAbs_COMPOUND;
420 aShapeTypes["COMPOUNDS"] = TopAbs_COMPOUND;
421 aShapeTypes["COMPSOLID"] = TopAbs_COMPSOLID;
422 aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
423 aShapeTypes["SOLID"] = TopAbs_SOLID;
424 aShapeTypes["SOLIDS"] = TopAbs_SOLID;
425 aShapeTypes["SHELL"] = TopAbs_SHELL;
426 aShapeTypes["SHELLS"] = TopAbs_SHELL;
427 aShapeTypes["FACE"] = TopAbs_FACE;
428 aShapeTypes["FACES"] = TopAbs_FACE;
429 aShapeTypes["WIRE"] = TopAbs_WIRE;
430 aShapeTypes["WIRES"] = TopAbs_WIRE;
431 aShapeTypes["EDGE"] = TopAbs_EDGE;
432 aShapeTypes["EDGES"] = TopAbs_EDGE;
433 aShapeTypes["VERTEX"] = TopAbs_VERTEX;
434 aShapeTypes["VERTICES"] = TopAbs_VERTEX;
436 if (aShapeTypes.find(theType) != aShapeTypes.end())
437 return aShapeTypes[theType];
438 Events_InfoMessage("Model_SelectionNaming",
439 "Shape type defined in XML is not implemented!").send();
443 const TopoDS_Shape getShapeFromNS(
444 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
446 TopoDS_Shape aSelection;
447 std::string::size_type n = theSubShapeName.rfind('/');
448 if (n == std::string::npos) n = -1;
449 std::string aSubString = theSubShapeName.substr(n + 1);
450 n = aSubString.rfind('_');
452 if (n != std::string::npos) {// for primitives this is a first
453 // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
454 Handle(TDataStd_Name) aName;
455 if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
456 aName->Get() != aSubString.c_str()) {
457 aSubString = aSubString.substr(n+1);
458 indx = atoi(aSubString.c_str());
462 TNaming_Iterator anItL(theNS);
463 for(int i = 1; anItL.More(); anItL.Next(), i++) {
465 return anItL.NewShape();
471 const TopoDS_Shape findFaceByName(
472 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
475 //std::string::size_type n, nb = theSubShapeName.rfind('/');
476 //if (nb == std::string::npos) nb = 0;
477 //std::string aSubString = theSubShapeName.substr(nb + 1);
478 std::string aSubString = theSubShapeName;
480 TDF_Label aLabel = theDoc->findNamingName(aSubString);
481 if (aLabel.IsNull()) { // try to remove additional artificial suffix
482 std::string::size_type n = aSubString.rfind('_');
483 if (n != std::string::npos) {
484 aSubString = aSubString.substr(0, n);
485 aLabel = theDoc->findNamingName(aSubString);
488 if(aLabel.IsNull()) return aFace;
489 Handle(TNaming_NamedShape) aNS;
490 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
491 aFace = getShapeFromNS(theSubShapeName, aNS);
496 size_t ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
498 std::string aName = theSubShapeName;
499 std::string aLastName = aName;
500 size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
501 while ((n2 = aName.find('&', n1)) != std::string::npos) {
502 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
503 theList.push_back(aName1);
505 aLastName = aName.substr(n1);
507 if(!aLastName.empty())
508 theList.push_back(aLastName);
509 return theList.size();
512 std::string getContextName(const std::string& theSubShapeName)
515 std::string::size_type n = theSubShapeName.find('/');
516 if (n == std::string::npos) return theSubShapeName;
517 aName = theSubShapeName.substr(0, n);
521 /// Parses naming name of sketch sub-elements: takes indices and orientation
522 /// (if theOriented = true) from this name. Map theIDs constains indices ->
523 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
524 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
525 const std::string& theName, const char* theShapeType,
526 std::map<int, int>& theIDs, const bool theOriented = false)
528 // collect all IDs in the name
529 std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
530 const int aSubNum = theComp->numberOfSubs();
531 for(int a = 0; a < aSubNum; a++) {
532 FeaturePtr aSub = theComp->subFeature(a);
533 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
534 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
535 // there may be many shapes (circle and center)
536 for(; aRes != aResults.cend(); aRes++) {
537 ResultConstructionPtr aConstr =
538 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
540 aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
545 size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
546 bool isShape = false; // anyway the first world must be 'Vertex'
548 aLastNamePos = theName.find('-', aPrevPos);
549 std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
551 if (anID != theShapeType)
555 int anOrientation = 1; // default
556 if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
557 std::string::iterator aSymbol = anID.end() - 1;
558 if (*aSymbol == 'r') anOrientation = -1;
559 anID.erase(aSymbol); // remove last symbol
561 // check start/end symbols
562 std::string::iterator aBack = anID.end() - 1;
565 anID.erase(aBack); // remove last symbol
566 } else if (*aBack == 'e') {
568 anID.erase(aBack); // remove last symbol
571 if (aNames.find(anID) != aNames.end()) {
572 theIDs[aNames[anID]] = anOrientation;
575 aPrevPos = aLastNamePos + 1;
576 } while (aLastNamePos != std::string::npos);
580 /// produces theEdge orientation relatively to theContext face
581 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
583 if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
585 if (theEdge.Orientation() == TopAbs_FORWARD)
587 if (theEdge.Orientation() == TopAbs_REVERSED)
592 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
593 std::shared_ptr<ModelAPI_Result>& theConstr,
594 NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
596 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
597 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
598 std::shared_ptr<GeomAPI_Shape> aResult;
599 ResultConstructionPtr aConstructionContext =
600 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
601 if (!aConstructionContext.get())
603 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
604 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
606 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
607 std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
609 for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
610 aFacesWires.push_back(aWires.Current());
613 aFacesWires.push_back(aFace);
615 std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
616 for(; aFW != aFacesWires.end(); aFW++) {
617 TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
618 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
619 for(; anEdgesExp.More(); anEdgesExp.Next()) {
620 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
621 if (!anEdge.IsNull()) {
622 Standard_Real aFirst, aLast;
623 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
624 if (alreadyProcessed.Contains(aCurve))
626 alreadyProcessed.Add(aCurve);
627 if (theCurves.IsBound(aCurve)) {
629 int anOrient = theCurves.Find(aCurve);
630 if (anOrient != 0) { // extra comparision score is orientation
631 if (edgeOrientation(aFace, anEdge) == anOrient)
639 if (aFound + aNotFound != 0) {
640 if (aFound > aBestFound ||
641 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
643 aBestOrient = aSameOrientation;
645 std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
646 aWire->setImpl(new TopoDS_Shape(*aFW));
649 aResult = aConstructionContext->face(aFaceIndex);
658 std::string Model_SelectionNaming::shortName(
659 std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
661 std::string aName = theConstr->data()->name();
662 // remove "-", "/" and "&" command-symbols
663 aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
664 aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
665 aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
666 // remove the last 's', 'e', 'f' and 'r' symbols:
667 // they are used as markers of start/end/forward/rewersed indicators
668 static const std::string aSyms("sefr");
669 std::string::iterator aSuffix = aName.end() - 1;
670 while(aSyms.find(*aSuffix) != std::string::npos) {
673 aName.erase(aSuffix + 1, aName.end());
675 if (theEdgeVertexPos == 1) {
676 aName += "s"; // start
677 } else if (theEdgeVertexPos == 2) {
683 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
684 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
685 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
686 std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
688 if(theSubShapeName.empty() || theType.empty()) return false;
689 TopAbs_ShapeEnum aType = translateType(theType);
691 // check that it was selected in another document
692 size_t aSlash = theSubShapeName.find("/");
693 std::string aSubShapeName = theSubShapeName;
694 std::shared_ptr<Model_Document> aDoc = theDoc;
695 if (aSlash != std::string::npos) {
696 std::string aDocName = theSubShapeName.substr(0, aSlash);
697 ResultPartPtr aFoundPart;
698 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
699 if (aDocName == aRootDoc->kind()) {
700 aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
702 for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
703 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
704 aRootDoc->object(ModelAPI_ResultPart::group(), a));
705 if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
706 aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
712 if (aDoc != theDoc) {
713 // so, the first word is the document name => reduce the string for the next manips
714 aSubShapeName = theSubShapeName.substr(aSlash + 1);
715 if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
716 theCont = aFoundPart;
722 std::string aContName = getContextName(aSubShapeName);
723 if(aContName.empty()) return false;
724 ResultPtr aCont = aDoc->findByName(aContName);
725 // possible this is body where postfix is added to distinguish several shapes on the same label
726 int aSubShapeId = -1; // -1 means sub shape not found
727 // for result body the name wihtout "_" has higher priority than with it: it is always added
728 if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
729 aContName == aSubShapeName) {
730 size_t aPostIndex = aContName.rfind('_');
731 if (aPostIndex != std::string::npos) {
732 std::string aSubContName = aContName.substr(0, aPostIndex);
733 ResultPtr aSubCont = aDoc->findByName(aSubContName);
734 if (aSubCont.get()) {
736 std::string aNum = aContName.substr(aPostIndex + 1);
737 aSubShapeId = std::stoi(aNum);
738 } catch (std::invalid_argument&) {
741 if (aSubShapeId > 0) {
742 aContName = aSubContName;
750 TopoDS_Shape aSelection;
756 aSelection = findFaceByName(aSubShapeName, aDoc);
761 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
762 if(!aLabel.IsNull()) {
763 Handle(TNaming_NamedShape) aNS;
764 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
765 aSelection = getShapeFromNS(aSubShapeName, aNS);
772 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
773 if(!aLabel.IsNull()) {
774 Handle(TNaming_NamedShape) aNS;
775 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
776 aSelection = getShapeFromNS(aSubShapeName, aNS);
781 case TopAbs_COMPOUND:
782 case TopAbs_COMPSOLID:
785 default: {//TopAbs_SHAPE
786 /// case when the whole sketch is selected, so,
787 /// selection type is compound, but there is no value
788 if (aCont.get() && aCont->shape().get()) {
789 if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
792 } else if (aSubShapeId > 0) { // try to find sub-shape by the index
793 TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
794 for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
798 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
799 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
800 theShapeToBeSelected = aShapeToBeSelected;
809 if (!aSelection.IsNull() &&
810 aSelection.ShapeType() != aType && aSelection.ShapeType() != TopAbs_COMPOUND)
811 aSelection.Nullify(); // to avoid selection of face instead of edge that is described by face
812 // another try to find edge or vertex by faces
813 std::list<std::string> aListofNames;
814 size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
815 if ((aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) ||
816 (!aSelection.IsNull() && aSelection.ShapeType() != aType)) { // edge by one face as example
818 TopTools_ListOfShape aList;
819 std::list<std::string>::iterator it = aListofNames.begin();
820 for(; it != aListofNames.end(); it++){
821 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
825 aSelection = findCommonShape(aType, aList);
828 // in case of construction, there is no registered names for all sub-elements,
829 // even for the main element; so, trying to find them by name (without "&" intersections)
831 size_t aConstrNamePos = aSubShapeName.find("/");
832 bool isFullName = aConstrNamePos == std::string::npos;
833 std::string aContrName = aContName;
834 ResultPtr aConstr = aDoc->findByName(aContrName);
835 if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
838 // For the full construction selection shape must be empty.
839 //theShapeToBeSelected = aConstr->shape();
842 // for sketch sub-elements selected
843 CompositeFeaturePtr aComposite =
844 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
845 if (aComposite.get()) {
846 if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
847 // collect all IDs in the name
848 bool isVertexByEdge = false;
849 std::map<int, int> anIDs;
850 if (!parseSubIndices(aComposite, aSubShapeName,
851 aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs)) {
852 // there is a case when vertex is identified by one circle-edge (2253)
853 if (aType == TopAbs_VERTEX &&
854 parseSubIndices(aComposite, aSubShapeName, "Edge", anIDs))
855 isVertexByEdge = true;
860 const int aSubNum = aComposite->numberOfSubs();
861 for(int a = 0; a < aSubNum; a++) {
862 int aCompID = aComposite->subFeatureId(a);
863 if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
864 FeaturePtr aSub = aComposite->subFeature(a);
865 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
866 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
867 // there may be many shapes (circle and center)
868 for(; aRIt != aResults.cend(); aRIt++) {
869 ResultConstructionPtr aRes =
870 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
872 int anOrientation = abs(anIDs[aCompID]);
873 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
874 if (anOrientation == 1) {
875 if (!isVertexByEdge && aType == aShape.ShapeType()) {
876 theShapeToBeSelected = aRes->shape();
878 } else if (isVertexByEdge && aType != aShape.ShapeType()) {
879 // check that there is only one vertex produces by and circular edge
880 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
881 TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
883 aShape = anExp.Current();
885 if (!anExp.More() || anExp.Current().IsSame(aShape)) {
886 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
887 aShapeToBeSelected->setImpl(new TopoDS_Shape(aShape));
888 theShapeToBeSelected = aShapeToBeSelected;
892 } else { // take first or second vertex of the edge
893 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
894 if (aShape.ShapeType() == TopAbs_VERTEX) continue;
895 TopExp_Explorer anExp(aShape, aType);
896 for(; anExp.More() && anOrientation != 2; anOrientation--)
899 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
900 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
901 theShapeToBeSelected = aShapeToBeSelected;
909 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
910 } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
911 std::map<int, int> anIDs;
912 if (!parseSubIndices(aComposite, aSubShapeName,
913 aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
916 // curves and orientations of edges
917 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
918 const int aSubNum = aComposite->numberOfSubs();
919 for(int a = 0; a < aSubNum; a++) {
920 int aSubID = aComposite->subFeatureId(a);
921 if (anIDs.find(aSubID) != anIDs.end()) {
922 FeaturePtr aSub = aComposite->subFeature(a);
923 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
924 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
925 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
926 ResultConstructionPtr aConstr =
927 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
928 if (aConstr->shape() && aConstr->shape()->isEdge()) {
929 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
930 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
931 if (!anEdge.IsNull()) {
932 Standard_Real aFirst, aLast;
933 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
934 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
940 std::shared_ptr<GeomAPI_Shape> aFoundFW =
941 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
942 if (aFoundFW.get()) {
943 theShapeToBeSelected = aFoundFW;
946 } else if (aType == TopAbs_WIRE) {
947 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
948 std::map<int, int> anIDs;
949 if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
952 // curves and orientations of edges
953 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
954 const int aSubNum = aComposite->numberOfSubs();
955 for(int a = 0; a < aSubNum; a++) {
956 int aSubID = aComposite->subFeatureId(a);
957 if (anIDs.find(aSubID) != anIDs.end()) {
958 FeaturePtr aSub = aComposite->subFeature(a);
959 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
960 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
961 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
962 ResultConstructionPtr aConstr =
963 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
964 if (aConstr->shape() && aConstr->shape()->isEdge()) {
965 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
966 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
967 if (!anEdge.IsNull()) {
968 Standard_Real aFirst, aLast;
969 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
970 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
976 std::shared_ptr<GeomAPI_Shape> aFoundFW =
977 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
978 if (aFoundFW.get()) {
979 theShapeToBeSelected = aFoundFW;
986 if (!aSelection.IsNull()) {
987 // Select it (must be after N=0 checking,
988 // since for simple constructions the shape must be null)
989 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
990 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
991 theShapeToBeSelected = aShapeToBeSelected;