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();
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 // this is to avoid duplicated names of results problem
116 std::string aContextName = aNewContext->data()->name();
117 // myLab corresponds to the current time
118 TDF_Label aCurrentLab = myLab;
119 while(aCurrentLab.Depth() > 3)
120 aCurrentLab = aCurrentLab.Father();
122 int aNumInHistoryNames =
123 theDoc->numberOfNameInHistory(aNewContext, aCurrentLab);
124 while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
125 aContextName = "_" + aContextName;
126 aNumInHistoryNames--;
129 aName = aContextName + "/" + aName;
136 // Name is empty and this is full context, it just add the whole context name that must be added
137 bool isEmptyName = aName.empty();
138 if (isNeedContextName && (!isEmptyName || theWholeContext)) {
139 aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
141 aName = theContext->document()->kind() + "/" + aName; // PartSet
146 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
148 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
149 TopoDS_Compound aCmp;
151 BB.MakeCompound(aCmp);
152 TopTools_ListIteratorOfListOfShape it(theAncestors);
153 for(;it.More();it.Next()) {
154 if (theSMap.Contains(it.Value()))
156 BB.Add(aCmp, it.Value());
157 theSMap.Add(it.Value());
160 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
161 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
162 for (int i = 1; i <= aMap2.Extent(); i++) {
163 const TopoDS_Shape& aKey = aMap2.FindKey(i);
164 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
165 if(anAncestors.Extent() > 1) aNumber++;
167 if(aNumber > 1) return false;
171 const TopoDS_Shape findCommonShape(
172 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
174 if(theList.Extent() < 1) {
175 return TopoDS_Shape();
176 } else if (theList.Extent() == 1) { // check that sub-shape is bounded by this alone shape
177 TopTools_MapOfShape aSubsInShape;
178 TopExp_Explorer anExp(theList.First(), theType);
179 for(; anExp.More(); anExp.Next()) {
180 if (aSubsInShape.Contains(anExp.Current())) { // found duplicate
181 return anExp.Current();
183 aSubsInShape.Add(anExp.Current());
187 // Store in maps sub-shapes from each face.
188 std::vector<TopTools_MapOfShape> aVec;
189 for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) {
190 const TopoDS_Shape aFace = anIt.Value();
191 TopTools_MapOfShape aMap;
192 for(TopExp_Explorer anExp(aFace, theType); anExp.More(); anExp.Next()) {
193 const TopoDS_Shape& aSubShape = anExp.Current();
194 aMap.Add(anExp.Current());
196 aVec.push_back(aMap);
199 // Find sub-shape shared between all faces.
200 TopoDS_Shape aSharedShape;
201 for(TopTools_MapIteratorOfMapOfShape anIt(aVec[0]); anIt.More(); anIt.Next()) {
202 const TopoDS_Shape& aSubShape = anIt.Value();
204 for(int anIndex = 1; anIndex < aVec.size(); ++anIndex) {
205 if(aVec[anIndex].Contains(aSubShape)) {
209 if(aSharedNb == theList.Extent()) {
210 if(aSharedShape.IsNull()) {
211 aSharedShape = aSubShape;
213 // More than one shape shared between all faces, return null shape in this case.
214 return TopoDS_Shape();
222 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
223 std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
224 const bool theAnotherDoc)
226 std::string aName("Undefined name");
228 || !theContext->shape().get()
229 || theContext->shape()->isNull()) {
230 return !theDefaultName.empty() ? theDefaultName : aName;
233 // if it is in result of another part
234 std::shared_ptr<Model_Document> aDoc =
235 std::dynamic_pointer_cast<Model_Document>(theContext->document());
236 if (theContext->groupName() == ModelAPI_ResultPart::group()) {
237 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
240 return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
242 return aPart->data()->name();
245 if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
246 // but if it is in another Part, add this part name
247 std::string aPartName;
249 aPartName = theContext->document()->kind() + "/"; // PartSet
250 return aPartName + theContext->data()->name();
252 TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
253 TopoDS_Shape aContext = theContext->shape()->impl<TopoDS_Shape>();
255 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
256 BRepTools::Write(aSubShape, "Selection.brep");
257 BRepTools::Write(aContext, "Context.brep");
260 aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
261 theContext->shape()->isEqual(theSubSh));
263 if(aName.empty() ) { // not in the document!
264 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
267 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
271 // name structure: F1 & F2 [& F3 & F4],
272 // where F1 & F2 the faces which gives the Edge in trivial case
273 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
274 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
275 aName = "Degenerated_Edge";
278 TopTools_IndexedDataMapOfShapeListOfShape aMap;
279 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
280 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
281 bool isTrivialCase(true);
282 if(aMap.Contains(aSubShape)) {
283 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
284 // check that it is not a trivial case (F1 & F2: aNumber = 1)
285 isTrivialCase = isTrivial(anAncestors, aSMap);
286 if (!isTrivialCase) { // another try: check that common shape can be processed anyway
287 isTrivialCase = !findCommonShape(TopAbs_EDGE, anAncestors).IsNull();
291 TopTools_ListOfShape aListOfNbs;
292 if(!isTrivialCase) { // find Neighbors
293 TNaming_Localizer aLocalizer;
294 TopTools_MapOfShape aMap3;
295 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
296 //int n = aMap3.Extent();
297 TopTools_MapIteratorOfMapOfShape it(aMap3);
298 for(;it.More();it.Next()) {
299 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
300 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
301 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
302 TopTools_ListIteratorOfListOfShape it2(aList);
303 for(;it2.More();it2.Next()) {
304 if(aSMap.Contains(it2.Value())) continue; // skip this Face
305 aListOfNbs.Append(it2.Value());
308 } // else a trivial case
310 // build name of the sub-shape Edge
311 for(int i=1; i <= aSMap.Extent(); i++) {
312 const TopoDS_Shape& aFace = aSMap.FindKey(i);
313 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
317 aName += "&" + aFaceName;
319 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
320 for (;itl.More();itl.Next()) {
321 std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
322 aName += "&" + aFaceName;
328 // name structure (Monifold Topology):
329 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
330 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
331 // but it should be kept as is to obtain safe recomputation
332 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
333 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
334 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
335 // or compound of 2 open faces.
336 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
337 // two independent edges (wire or compound)
338 // implemented 2 first cases
340 TopTools_IndexedDataMapOfShapeListOfShape aMap;
341 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
342 TopTools_ListOfShape aList;
343 TopTools_MapOfShape aFMap;
344 // simetimes when group is moved in history, naming may be badly updated, so
345 // avoid crash in FindFromKey (issue 1842)
346 if (aMap.Contains(aSubShape)) {
347 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
349 TopTools_ListIteratorOfListOfShape itl2(aList2);
350 for (int i = 1;itl2.More();itl2.Next(),i++) {
351 if(aFMap.Add(itl2.Value()))
352 aList.Append(itl2.Value());
356 int n = aList.Extent();
357 bool isByFaces = n >= 3;
358 if(!isByFaces) { // open topology case or Compound case => via edges
359 TopTools_IndexedDataMapOfShapeListOfShape aMap;
360 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
361 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
362 if(aList22.Extent() >= 2) { // regular solution
364 // bug! duplication; fix is below
366 TopTools_ListOfShape aListE;
367 TopTools_ListIteratorOfListOfShape itl2(aList22);
368 for (int i = 1;itl2.More();itl2.Next(),i++) {
369 if(aFMap.Add(itl2.Value()))
370 aListE.Append(itl2.Value());
373 TopTools_ListIteratorOfListOfShape itl(aListE);
374 for (int i = 1;itl.More();itl.Next(),i++) {
375 const TopoDS_Shape& anEdge = itl.Value();
376 std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
377 if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
385 aName += "&" + anEdgeName;
388 else { // dangle vertex: if(aList22.Extent() == 1)
389 //it should be already in DF
393 TopTools_ListIteratorOfListOfShape itl(aList);
394 for (int i = 1;itl.More();itl.Next(),i++) {
395 const TopoDS_Shape& aFace = itl.Value();
396 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
400 aName += "&" + aFaceName;
411 TopAbs_ShapeEnum translateType (const std::string& theType)
413 // map from the textual shape types to OCCT enumeration
414 static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
416 if(aShapeTypes.size() == 0) {
417 aShapeTypes["compound"] = TopAbs_COMPOUND;
418 aShapeTypes["compounds"] = TopAbs_COMPOUND;
419 aShapeTypes["compsolid"] = TopAbs_COMPSOLID;
420 aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
421 aShapeTypes["solid"] = TopAbs_SOLID;
422 aShapeTypes["solids"] = TopAbs_SOLID;
423 aShapeTypes["shell"] = TopAbs_SHELL;
424 aShapeTypes["shells"] = TopAbs_SHELL;
425 aShapeTypes["face"] = TopAbs_FACE;
426 aShapeTypes["faces"] = TopAbs_FACE;
427 aShapeTypes["wire"] = TopAbs_WIRE;
428 aShapeTypes["wires"] = TopAbs_WIRE;
429 aShapeTypes["edge"] = TopAbs_EDGE;
430 aShapeTypes["edges"] = TopAbs_EDGE;
431 aShapeTypes["vertex"] = TopAbs_VERTEX;
432 aShapeTypes["vertices"] = TopAbs_VERTEX;
433 aShapeTypes["COMPOUND"] = TopAbs_COMPOUND;
434 aShapeTypes["COMPOUNDS"] = TopAbs_COMPOUND;
435 aShapeTypes["COMPSOLID"] = TopAbs_COMPSOLID;
436 aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
437 aShapeTypes["SOLID"] = TopAbs_SOLID;
438 aShapeTypes["SOLIDS"] = TopAbs_SOLID;
439 aShapeTypes["SHELL"] = TopAbs_SHELL;
440 aShapeTypes["SHELLS"] = TopAbs_SHELL;
441 aShapeTypes["FACE"] = TopAbs_FACE;
442 aShapeTypes["FACES"] = TopAbs_FACE;
443 aShapeTypes["WIRE"] = TopAbs_WIRE;
444 aShapeTypes["WIRES"] = TopAbs_WIRE;
445 aShapeTypes["EDGE"] = TopAbs_EDGE;
446 aShapeTypes["EDGES"] = TopAbs_EDGE;
447 aShapeTypes["VERTEX"] = TopAbs_VERTEX;
448 aShapeTypes["VERTICES"] = TopAbs_VERTEX;
450 if (aShapeTypes.find(theType) != aShapeTypes.end())
451 return aShapeTypes[theType];
452 Events_InfoMessage("Model_SelectionNaming",
453 "Shape type defined in XML is not implemented!").send();
457 const TopoDS_Shape getShapeFromNS(
458 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
460 TopoDS_Shape aSelection;
461 std::string::size_type n = theSubShapeName.rfind('/');
462 if (n == std::string::npos) n = -1;
463 std::string aSubString = theSubShapeName.substr(n + 1);
464 n = aSubString.rfind('_');
466 if (n != std::string::npos) {// for primitives this is a first
467 // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
468 Handle(TDataStd_Name) aName;
469 if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
470 aName->Get() != aSubString.c_str()) {
471 aSubString = aSubString.substr(n+1);
472 indx = atoi(aSubString.c_str());
476 TNaming_Iterator anItL(theNS);
477 for(int i = 1; anItL.More(); anItL.Next(), i++) {
479 return anItL.NewShape();
485 const TopoDS_Shape findFaceByName(
486 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
487 const ResultPtr theDetectedContext, bool theContextIsUnique)
490 std::string aSubString = theSubShapeName;
492 static const ResultPtr anEmpty;
493 TDF_Label aLabel = theDoc->findNamingName(aSubString,
494 theContextIsUnique ? theDetectedContext : anEmpty);
495 if (aLabel.IsNull()) { // try to remove additional artificial suffix
496 std::string::size_type n = aSubString.rfind('_');
497 if (n != std::string::npos) {
498 aSubString = aSubString.substr(0, n);
499 aLabel = theDoc->findNamingName(aSubString,
500 theContextIsUnique ? theDetectedContext : anEmpty);
503 if(aLabel.IsNull()) return aFace;
504 Handle(TNaming_NamedShape) aNS;
505 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
506 aFace = getShapeFromNS(theSubShapeName, aNS);
511 size_t ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
513 std::string aName = theSubShapeName;
514 std::string aLastName = aName;
515 size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
516 while ((n2 = aName.find('&', n1)) != std::string::npos) {
517 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
518 theList.push_back(aName1);
520 aLastName = aName.substr(n1);
522 if(!aLastName.empty())
523 theList.push_back(aLastName);
524 return theList.size();
527 std::string getContextName(const std::string& theSubShapeName)
530 std::string::size_type n = theSubShapeName.find('/');
531 if (n == std::string::npos) return theSubShapeName;
532 aName = theSubShapeName.substr(0, n);
536 /// Parses naming name of sketch sub-elements: takes indices and orientation
537 /// (if theOriented = true) from this name. Map theIDs constains indices ->
538 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
539 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
540 const std::string& theName, const char* theShapeType,
541 std::map<int, int>& theIDs, const bool theOriented = false)
543 // collect all IDs in the name
544 std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
545 const int aSubNum = theComp->numberOfSubs();
546 for(int a = 0; a < aSubNum; a++) {
547 FeaturePtr aSub = theComp->subFeature(a);
548 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
549 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
550 // there may be many shapes (circle and center)
551 for(; aRes != aResults.cend(); aRes++) {
552 ResultConstructionPtr aConstr =
553 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
555 aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
560 size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
561 bool isShape = false; // anyway the first world must be 'Vertex'
563 aLastNamePos = theName.find('-', aPrevPos);
564 std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
566 if (anID != theShapeType)
570 int anOrientation = 1; // default
571 if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
572 std::string::iterator aSymbol = anID.end() - 1;
573 if (*aSymbol == 'r') anOrientation = -1;
574 anID.erase(aSymbol); // remove last symbol
576 // check start/end symbols
577 std::string::iterator aBack = anID.end() - 1;
580 anID.erase(aBack); // remove last symbol
581 } else if (*aBack == 'e') {
583 anID.erase(aBack); // remove last symbol
586 if (aNames.find(anID) != aNames.end()) {
587 theIDs[aNames[anID]] = anOrientation;
590 aPrevPos = aLastNamePos + 1;
591 } while (aLastNamePos != std::string::npos);
595 /// produces theEdge orientation relatively to theContext face
596 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
598 if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
600 if (theEdge.Orientation() == TopAbs_FORWARD)
602 if (theEdge.Orientation() == TopAbs_REVERSED)
607 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
608 std::shared_ptr<ModelAPI_Result>& theConstr,
609 NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
611 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
612 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
613 std::shared_ptr<GeomAPI_Shape> aResult;
614 ResultConstructionPtr aConstructionContext =
615 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
616 if (!aConstructionContext.get())
618 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
619 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
621 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
622 std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
624 for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
625 aFacesWires.push_back(aWires.Current());
628 aFacesWires.push_back(aFace);
630 std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
631 for(; aFW != aFacesWires.end(); aFW++) {
632 TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
633 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
634 for(; anEdgesExp.More(); anEdgesExp.Next()) {
635 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
636 if (!anEdge.IsNull()) {
637 Standard_Real aFirst, aLast;
638 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
639 if (alreadyProcessed.Contains(aCurve))
641 alreadyProcessed.Add(aCurve);
642 if (theCurves.IsBound(aCurve)) {
644 int anOrient = theCurves.Find(aCurve);
645 if (anOrient != 0) { // extra comparision score is orientation
646 if (edgeOrientation(aFace, anEdge) == anOrient)
654 if (aFound + aNotFound != 0) {
655 if (aFound > aBestFound ||
656 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
658 aBestOrient = aSameOrientation;
660 std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
661 aWire->setImpl(new TopoDS_Shape(*aFW));
664 aResult = aConstructionContext->face(aFaceIndex);
673 std::string Model_SelectionNaming::shortName(
674 std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
676 std::string aName = theConstr->data()->name();
677 // remove "-", "/" and "&" command-symbols
678 aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
679 aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
680 aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
681 // remove the last 's', 'e', 'f' and 'r' symbols:
682 // they are used as markers of start/end/forward/rewersed indicators
683 static const std::string aSyms("sefr");
684 std::string::iterator aSuffix = aName.end() - 1;
685 while(aSyms.find(*aSuffix) != std::string::npos) {
688 aName.erase(aSuffix + 1, aName.end());
690 if (theEdgeVertexPos == 1) {
691 aName += "s"; // start
692 } else if (theEdgeVertexPos == 2) {
698 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
699 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
700 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
701 std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
703 if(theSubShapeName.empty() || theType.empty()) return false;
704 TopAbs_ShapeEnum aType = translateType(theType);
706 // check that it was selected in another document
707 size_t aSlash = theSubShapeName.find("/");
708 std::string aSubShapeName = theSubShapeName;
709 std::shared_ptr<Model_Document> aDoc = theDoc;
710 if (aSlash != std::string::npos) {
711 std::string aDocName = theSubShapeName.substr(0, aSlash);
712 ResultPartPtr aFoundPart;
713 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
714 if (aDocName == aRootDoc->kind()) {
715 aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
717 for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
718 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
719 aRootDoc->object(ModelAPI_ResultPart::group(), a));
720 if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
721 aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
727 if (aDoc != theDoc) {
728 // so, the first word is the document name => reduce the string for the next manips
729 aSubShapeName = theSubShapeName.substr(aSlash + 1);
730 if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
731 theCont = aFoundPart;
737 std::string aContName = getContextName(aSubShapeName);
738 if(aContName.empty()) return false;
739 bool anUniqueContext = false;
740 ResultPtr aCont = aDoc->findByName(aContName, aSubShapeName, anUniqueContext);
741 // possible this is body where postfix is added to distinguish several shapes on the same label
742 int aSubShapeId = -1; // -1 means sub shape not found
743 // for result body the name wihtout "_" has higher priority than with it: it is always added
744 if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
745 aContName == aSubShapeName) {
746 size_t aPostIndex = aContName.rfind('_');
747 if (aPostIndex != std::string::npos) {
748 std::string anEmpty, aSubContName = aContName.substr(0, aPostIndex);
749 ResultPtr aSubCont = aDoc->findByName(aSubContName, anEmpty, anUniqueContext);
750 if (aSubCont.get()) {
752 std::string aNum = aContName.substr(aPostIndex + 1);
753 aSubShapeId = std::stoi(aNum);
754 } catch (std::invalid_argument&) {
757 if (aSubShapeId > 0) {
758 aContName = aSubContName;
766 static const ResultPtr anEmpty;
767 TopoDS_Shape aSelection;
773 aSelection = findFaceByName(aSubShapeName, aDoc, aCont, anUniqueContext);
778 const TDF_Label& aLabel =
779 aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
780 if(!aLabel.IsNull()) {
781 Handle(TNaming_NamedShape) aNS;
782 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
783 aSelection = getShapeFromNS(aSubShapeName, aNS);
790 const TDF_Label& aLabel =
791 aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
792 if(!aLabel.IsNull()) {
793 Handle(TNaming_NamedShape) aNS;
794 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
795 aSelection = getShapeFromNS(aSubShapeName, aNS);
800 case TopAbs_COMPOUND:
801 case TopAbs_COMPSOLID:
804 default: {//TopAbs_SHAPE
805 /// case when the whole sketch is selected, so,
806 /// selection type is compound, but there is no value
807 if (aCont.get() && aCont->shape().get()) {
808 if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
811 } else if (aSubShapeId > 0) { // try to find sub-shape by the index
812 TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
813 for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
817 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
818 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
819 theShapeToBeSelected = aShapeToBeSelected;
828 if (!aSelection.IsNull() &&
829 aSelection.ShapeType() != aType && aSelection.ShapeType() != TopAbs_COMPOUND)
830 aSelection.Nullify(); // to avoid selection of face instead of edge that is described by face
831 // another try to find edge or vertex by faces
832 std::list<std::string> aListofNames;
833 size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
834 if ((aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) ||
835 (!aSelection.IsNull() && aSelection.ShapeType() != aType)) { // edge by one face as example
837 TopTools_ListOfShape aList;
838 std::list<std::string>::iterator it = aListofNames.begin();
839 for(; it != aListofNames.end(); it++) {
840 ResultPtr aFaceContext = aCont;
841 if (it != aListofNames.begin()) { // there may be other context for different sub-faces
842 std::string aContName = getContextName(*it);
843 if(!aContName.empty()) {
844 aFaceContext = aDoc->findByName(aContName, *it, anUniqueContext);
847 const TopoDS_Shape aFace = findFaceByName(*it, aDoc, aFaceContext, anUniqueContext);
851 aSelection = findCommonShape(aType, aList);
854 // in case of construction, there is no registered names for all sub-elements,
855 // even for the main element; so, trying to find them by name (without "&" intersections)
857 size_t aConstrNamePos = aSubShapeName.find("/");
858 bool isFullName = aConstrNamePos == std::string::npos;
859 std::string anEmpty, aContrName = aContName;
860 ResultPtr aConstr = aDoc->findByName(aContrName, anEmpty, anUniqueContext);
861 if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
864 // For the full construction selection shape must be empty.
865 //theShapeToBeSelected = aConstr->shape();
868 // for sketch sub-elements selected
869 CompositeFeaturePtr aComposite =
870 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
871 if (aComposite.get()) {
872 if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
873 // collect all IDs in the name
874 bool isVertexByEdge = false;
875 std::map<int, int> anIDs;
876 if (!parseSubIndices(aComposite, aSubShapeName,
877 aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs)) {
878 // there is a case when vertex is identified by one circle-edge (2253)
879 if (aType == TopAbs_VERTEX &&
880 parseSubIndices(aComposite, aSubShapeName, "Edge", anIDs))
881 isVertexByEdge = true;
886 const int aSubNum = aComposite->numberOfSubs();
887 for(int a = 0; a < aSubNum; a++) {
888 int aCompID = aComposite->subFeatureId(a);
889 if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
890 FeaturePtr aSub = aComposite->subFeature(a);
891 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
892 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
893 // there may be many shapes (circle and center)
894 for(; aRIt != aResults.cend(); aRIt++) {
895 ResultConstructionPtr aRes =
896 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
898 int anOrientation = abs(anIDs[aCompID]);
899 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
900 if (anOrientation == 1) {
901 if (!isVertexByEdge && aType == aShape.ShapeType()) {
902 theShapeToBeSelected = aRes->shape();
904 } else if (isVertexByEdge && aType != aShape.ShapeType()) {
905 // check that there is only one vertex produces by and circular edge
906 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
907 TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
909 aShape = anExp.Current();
911 if (!anExp.More() || anExp.Current().IsSame(aShape)) {
912 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
913 aShapeToBeSelected->setImpl(new TopoDS_Shape(aShape));
914 theShapeToBeSelected = aShapeToBeSelected;
918 } else { // take first or second vertex of the edge
919 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
920 if (aShape.ShapeType() == TopAbs_VERTEX) continue;
921 TopExp_Explorer anExp(aShape, aType);
922 for(; anExp.More() && anOrientation != 2; anOrientation--)
925 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
926 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
927 theShapeToBeSelected = aShapeToBeSelected;
935 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
936 } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
937 std::map<int, int> anIDs;
938 if (!parseSubIndices(aComposite, aSubShapeName,
939 aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
942 // curves and orientations of edges
943 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
944 const int aSubNum = aComposite->numberOfSubs();
945 for(int a = 0; a < aSubNum; a++) {
946 int aSubID = aComposite->subFeatureId(a);
947 if (anIDs.find(aSubID) != anIDs.end()) {
948 FeaturePtr aSub = aComposite->subFeature(a);
949 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
950 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
951 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
952 ResultConstructionPtr aConstr =
953 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
954 if (aConstr->shape() && aConstr->shape()->isEdge()) {
955 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
956 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
957 if (!anEdge.IsNull()) {
958 Standard_Real aFirst, aLast;
959 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
960 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
966 std::shared_ptr<GeomAPI_Shape> aFoundFW =
967 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
968 if (aFoundFW.get()) {
969 theShapeToBeSelected = aFoundFW;
972 } else if (aType == TopAbs_WIRE) {
973 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
974 std::map<int, int> anIDs;
975 if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
978 // curves and orientations of edges
979 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
980 const int aSubNum = aComposite->numberOfSubs();
981 for(int a = 0; a < aSubNum; a++) {
982 int aSubID = aComposite->subFeatureId(a);
983 if (anIDs.find(aSubID) != anIDs.end()) {
984 FeaturePtr aSub = aComposite->subFeature(a);
985 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
986 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
987 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
988 ResultConstructionPtr aConstr =
989 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
990 if (aConstr->shape() && aConstr->shape()->isEdge()) {
991 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
992 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
993 if (!anEdge.IsNull()) {
994 Standard_Real aFirst, aLast;
995 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
996 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1002 std::shared_ptr<GeomAPI_Shape> aFoundFW =
1003 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1004 if (aFoundFW.get()) {
1005 theShapeToBeSelected = aFoundFW;
1012 if (!aSelection.IsNull()) {
1013 // Select it (must be after N=0 checking,
1014 // since for simple constructions the shape must be null)
1015 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1016 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1017 theShapeToBeSelected = aShapeToBeSelected;