Salome HOME
Merge branch 'Dev_1.4.0' of newgeom:newgeom into Dev_1.4.0
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_SelectionNaming.cpp
4 // Created:     11 Aug 2015
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_SelectionNaming.h"
8 #include "Model_Document.h"
9 #include <ModelAPI_Feature.h>
10 #include <Events_Error.h>
11
12 #include <TopoDS_Iterator.hxx>
13 #include <TopoDS.hxx>
14 #include <TopoDS_Compound.hxx>
15 #include <TopExp.hxx>
16 #include <TopExp_Explorer.hxx>
17 #include <TopTools_ListOfShape.hxx>
18 #include <TopTools_MapOfShape.hxx>
19 #include <TopTools_IndexedMapOfShape.hxx>
20 #include <TopTools_ListIteratorOfListOfShape.hxx>
21 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
22 #include <TopTools_MapIteratorOfMapOfShape.hxx>
23 #include <BRep_Builder.hxx>
24 #include <TNaming_Iterator.hxx>
25 #include <TNaming_Tool.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Localizer.hxx>
28 #include <TDataStd_Name.hxx>
29
30 #ifdef DEB_NAMING
31 #include <BRepTools.hxx>
32 #endif
33
34 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
35 {
36   myLab = theSelectionLab;
37 }
38
39
40 std::string Model_SelectionNaming::getShapeName(
41   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape)
42 {
43   std::string aName;
44   // check if the subShape is already in DF
45   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
46   Handle(TDataStd_Name) anAttr;
47   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
48     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
49       aName = TCollection_AsciiString(anAttr->Get()).ToCString();
50       if(!aName.empty()) {          
51         const TDF_Label& aLabel = theDoc->findNamingName(aName);
52         /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
53         if(!aLabel.IsEqual(aNS->Label())) {
54         //aName.erase(); //something is wrong, to be checked!!!
55         aName += "_SomethingWrong";
56         return aName;
57         }*/
58
59         static const std::string aPostFix("_");
60         TNaming_Iterator anItL(aNS);
61         for(int i = 1; anItL.More(); anItL.Next(), i++) {
62           if(anItL.NewShape() == theShape) {
63             aName += aPostFix;
64             aName += TCollection_AsciiString (i).ToCString();
65             break;
66           }
67         }
68       } 
69     }
70   }
71   return aName;
72 }
73
74
75
76 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
77 {
78   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
79   TopoDS_Compound aCmp;
80   BRep_Builder BB;
81   BB.MakeCompound(aCmp);
82   TopTools_ListIteratorOfListOfShape it(theAncestors);
83   for(;it.More();it.Next()) {
84     BB.Add(aCmp, it.Value());
85     theSMap.Add(it.Value());
86   }
87   int aNumber(0);
88   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
89   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
90   for (int i = 1; i <= aMap2.Extent(); i++) {
91     const TopoDS_Shape& aKey = aMap2.FindKey(i);
92     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
93     if(anAncestors.Extent() > 1) aNumber++;
94   }
95   if(aNumber > 1) return false;
96   return true;
97 }
98
99 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
100   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName)
101 {
102   std::string aName("Undefined name");
103   if(!theContext.get() || theContext->shape()->isNull()) 
104     return !theDefaultName.empty() ? theDefaultName : aName;
105   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
106     return theContext->data()->name();
107   }
108   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
109   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
110 #ifdef DEB_NAMING
111   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
112     BRepTools::Write(aSubShape, "Selection.brep");
113     BRepTools::Write(aContext, "Context.brep");
114   }
115 #endif
116   std::shared_ptr<Model_Document> aDoc = 
117     std::dynamic_pointer_cast<Model_Document>(theContext->document());
118
119   // check if the subShape is already in DF
120   aName = getShapeName(aDoc, aSubShape);
121   if(aName.empty() ) { // not in the document!
122     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
123     switch (aType) {
124     case TopAbs_FACE:
125       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged             
126       break;
127     case TopAbs_EDGE:
128       {
129         // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
130         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces      
131         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
132           aName = "Degenerated_Edge";
133           break;
134         }    
135         TopTools_IndexedDataMapOfShapeListOfShape aMap;
136         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
137         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
138         bool isTrivialCase(true);
139         if(aMap.Contains(aSubShape)) {
140           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
141           // check that it is not a trivial case (F1 & F2: aNumber = 1)
142           isTrivialCase = isTrivial(anAncestors, aSMap);                
143         } else 
144           break;
145         TopTools_ListOfShape aListOfNbs;
146         if(!isTrivialCase) { // find Neighbors
147           TNaming_Localizer aLocalizer;
148           TopTools_MapOfShape aMap3;
149           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
150           //int n = aMap3.Extent();
151           TopTools_MapIteratorOfMapOfShape it(aMap3);
152           for(;it.More();it.Next()) {
153             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
154             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
155             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
156             TopTools_ListIteratorOfListOfShape it2(aList);
157             for(;it2.More();it2.Next()) {
158               if(aSMap.Contains(it2.Value())) continue; // skip this Face
159               aListOfNbs.Append(it2.Value());
160             }
161           }
162         }  // else a trivial case
163
164         // build name of the sub-shape Edge
165         for(int i=1; i <= aSMap.Extent(); i++) {
166           const TopoDS_Shape& aFace = aSMap.FindKey(i);
167           std::string aFaceName = getShapeName(aDoc, aFace);
168           if(i == 1)
169             aName = aFaceName;
170           else 
171             aName += "|" + aFaceName;
172         }
173         TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
174         for (;itl.More();itl.Next()) {
175           std::string aFaceName = getShapeName(aDoc, itl.Value());
176           aName += "|" + aFaceName;
177         }                 
178       }
179       break;
180
181     case TopAbs_VERTEX:
182       // name structure (Monifold Topology): 
183       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
184       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
185       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
186       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
187       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
188       //                   or compound of 2 open faces.
189       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
190       //                   two independent edges (wire or compound)
191       // implemented 2 first cases
192       {
193         TopTools_IndexedDataMapOfShapeListOfShape aMap;
194         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
195         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
196         TopTools_ListOfShape aList;
197         TopTools_MapOfShape aFMap;
198         // fix is below
199         TopTools_ListIteratorOfListOfShape itl2(aList2);
200         for (int i = 1;itl2.More();itl2.Next(),i++) {
201           if(aFMap.Add(itl2.Value()))
202             aList.Append(itl2.Value());
203         }
204         int n = aList.Extent();
205         bool isByFaces = n >= 3;
206         if(!isByFaces) { // open topology case or Compound case => via edges
207           TopTools_IndexedDataMapOfShapeListOfShape aMap;
208           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
209           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
210           if(aList22.Extent() >= 2)  { // regular solution
211
212             // bug! duplication; fix is below
213             aFMap.Clear();
214             TopTools_ListOfShape aListE;
215             TopTools_ListIteratorOfListOfShape itl2(aList22);
216             for (int i = 1;itl2.More();itl2.Next(),i++) {
217               if(aFMap.Add(itl2.Value()))
218                 aListE.Append(itl2.Value());
219             }
220             n = aListE.Extent();
221             TopTools_ListIteratorOfListOfShape itl(aListE);
222             for (int i = 1;itl.More();itl.Next(),i++) {
223               const TopoDS_Shape& anEdge = itl.Value();
224               std::string anEdgeName = getShapeName(aDoc, anEdge);
225               if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
226                 isByFaces = true;
227                 aName.clear();
228                 break;
229               }
230               if(i == 1)
231                 aName = anEdgeName;
232               else 
233                 aName += "|" + anEdgeName;
234             }
235           }//reg
236           else { // dangle vertex: if(aList22.Extent() == 1)
237             //it should be already in DF
238           }
239         } 
240         if (isByFaces) {
241           TopTools_ListIteratorOfListOfShape itl(aList);
242           for (int i = 1;itl.More();itl.Next(),i++) {
243             const TopoDS_Shape& aFace = itl.Value();
244             std::string aFaceName = getShapeName(aDoc, aFace);
245             if(i == 1)
246               aName = aFaceName;
247             else 
248               aName += "|" + aFaceName;
249           }
250         }
251       }
252       break;
253     }
254     // register name                    
255     // aDoc->addNamingName(selectionLabel(), aName);
256     // the selected sub-shape will not be shared and as result it will not require registration
257   }
258   return aName;
259 }
260
261 TopAbs_ShapeEnum translateType (const std::string& theType)
262 {
263   // map from the textual shape types to OCCT enumeration
264   static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
265   if (MyShapeTypes.size() == 0) {
266     MyShapeTypes["face"] = TopAbs_FACE;
267     MyShapeTypes["faces"] = TopAbs_FACE;
268     MyShapeTypes["vertex"] = TopAbs_VERTEX;
269     MyShapeTypes["vertices"] = TopAbs_VERTEX;
270     MyShapeTypes["wire"] = TopAbs_WIRE;
271     MyShapeTypes["edge"] = TopAbs_EDGE;
272     MyShapeTypes["edges"] = TopAbs_EDGE;
273     MyShapeTypes["shell"] = TopAbs_SHELL;
274     MyShapeTypes["solid"] = TopAbs_SOLID;
275     MyShapeTypes["solids"] = TopAbs_SOLID;
276     MyShapeTypes["FACE"] = TopAbs_FACE;
277     MyShapeTypes["FACES"] = TopAbs_FACE;
278     MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
279     MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
280     MyShapeTypes["WIRE"] = TopAbs_WIRE;
281     MyShapeTypes["EDGE"] = TopAbs_EDGE;
282     MyShapeTypes["EDGES"] = TopAbs_EDGE;
283     MyShapeTypes["SHELL"] = TopAbs_SHELL;
284     MyShapeTypes["SOLID"] = TopAbs_SOLID;
285     MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
286   }
287   if (MyShapeTypes.find(theType) != MyShapeTypes.end())
288     return MyShapeTypes[theType];
289   Events_Error::send("Shape type defined in XML is not implemented!");
290   return TopAbs_SHAPE;
291 }
292
293 const TopoDS_Shape getShapeFromNS(
294   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
295 {
296   TopoDS_Shape aSelection;
297   std::string::size_type n = theSubShapeName.rfind('/');                        
298   if (n == std::string::npos) n = 0;
299   std::string aSubString = theSubShapeName.substr(n + 1);
300   n = aSubString.rfind('_');
301   if (n == std::string::npos) return aSelection;
302   aSubString = aSubString.substr(n+1);
303   int indx = atoi(aSubString.c_str());
304
305   TNaming_Iterator anItL(theNS);
306   for(int i = 1; anItL.More(); anItL.Next(), i++) {
307     if (i == indx) {
308       return anItL.NewShape();
309     }
310   }
311   return aSelection;    
312 }
313
314 const TopoDS_Shape findFaceByName(
315   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
316 {
317   TopoDS_Shape aFace;
318   std::string::size_type n, nb = theSubShapeName.rfind('/');                    
319   if (nb == std::string::npos) nb = 0;
320   std::string aSubString = theSubShapeName.substr(nb + 1);
321   n = aSubString.rfind('_');
322   if (n != std::string::npos) {
323     std::string aSubStr2 = aSubString.substr(0, n);
324     aSubString  = theSubShapeName.substr(0, nb + 1);
325     aSubString = aSubString + aSubStr2; 
326   } else
327     aSubString = theSubShapeName;
328
329   const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
330   if(aLabel.IsNull()) return aFace;
331   Handle(TNaming_NamedShape) aNS;
332   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
333     aFace = getShapeFromNS(theSubShapeName, aNS);
334   }
335   return aFace;
336 }
337
338 int ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
339 {
340   std::string aName = theSubShapeName;
341   std::string aLastName;
342   int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
343   while ((n2 = aName.find('|', n1)) != std::string::npos) {
344     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
345     theList.push_back(aName1);  
346     n1 = n2 + 1;
347     aLastName = aName.substr(n1);
348   }
349   if(!aLastName.empty())
350     theList.push_back(aLastName);
351   return theList.size();
352 }
353
354 const TopoDS_Shape findCommonShape(
355   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
356 {
357   TopoDS_Shape aShape;
358   std::vector<TopTools_MapOfShape> aVec;
359   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
360   if(theList.Extent() > 1) {
361     aVec.push_back(aMap1);
362     aVec.push_back(aMap2);
363   }
364   if(theList.Extent() > 2)
365     aVec.push_back(aMap3);
366   if(theList.Extent() == 4)
367     aVec.push_back(aMap4);
368
369   //fill maps
370   TopTools_ListIteratorOfListOfShape it(theList);
371   for(int i = 0;it.More();it.Next(),i++) {
372     const TopoDS_Shape& aFace = it.Value();             
373     if(i < 2) {
374       TopExp_Explorer anExp (aFace, theType);
375       for(;anExp.More();anExp.Next()) {
376         const TopoDS_Shape& anEdge = anExp.Current();
377         if (!anEdge.IsNull())
378           aVec[i].Add(anExp.Current());
379       }
380     } else {
381       TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
382       for(;anExp.More();anExp.Next()) {
383         const TopoDS_Shape& aVertex = anExp.Current();
384         if (!aVertex.IsNull())
385           aVec[i].Add(anExp.Current());
386       }
387     }
388   }
389   //trivial case: 2 faces
390   TopTools_ListOfShape aList;
391   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
392   for(;it2.More();it2.Next()) {
393     if(aVec[1].Contains(it2.Key())) {
394       aShape = it2.Key();
395       if(theList.Extent() == 2)
396         break;
397       else 
398         aList.Append(it2.Key());
399     }
400   }
401   if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors 
402     if(aVec[2].Extent() && aVec[3].Extent()) {
403       TopTools_ListIteratorOfListOfShape it(aList);
404       for(;it.More();it.Next()) {
405         const TopoDS_Shape& aCand = it.Value();
406         // not yet completelly implemented, to be rechecked
407         TopoDS_Vertex aV1, aV2;
408         TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
409         int aNum(0);
410         if(aVec[2].Contains(aV1)) aNum++;
411         else if(aVec[2].Contains(aV2)) aNum++;
412         if(aVec[3].Contains(aV1)) aNum++;
413         else if(aVec[3].Contains(aV2)) aNum++;
414         if(aNum == 2) {
415           aShape = aCand;
416           break;
417         }
418       }
419     }
420   }
421
422   if(aList.Extent() && aVec.size() == 3) {
423
424     TopTools_ListIteratorOfListOfShape it(aList);
425     for(;it.More();it.Next()) {
426       const TopoDS_Shape& aCand = it.Value();
427       if(aVec[2].Contains(aCand)) {
428         aShape = aCand;
429         break;
430       }
431     }
432   }
433   return aShape;
434 }
435
436 std::string getContextName(const std::string& theSubShapeName)
437 {
438   std::string aName;
439   std::string::size_type n = theSubShapeName.find('/');                 
440   if (n == std::string::npos) return aName;
441   aName = theSubShapeName.substr(0, n);
442   return aName;
443 }
444
445 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
446 bool Model_SelectionNaming::selectSubShape(const std::string& theType, 
447   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
448   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
449 {
450   if(theSubShapeName.empty() || theType.empty()) return false;
451   TopAbs_ShapeEnum aType = translateType(theType);
452   std::string aContName = getContextName(theSubShapeName);
453   if(aContName.empty()) return false;
454   ResultPtr aCont = theDoc->findByName(aContName);
455   if(!aCont.get() || aCont->shape()->isNull()) return false;
456   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
457   TopAbs_ShapeEnum aContType = aContext.ShapeType();
458   if(aType <= aContType) return false; // not applicable
459
460
461   TopoDS_Shape aSelection;
462   switch (aType) 
463   {
464   case TopAbs_COMPOUND:
465     break;
466   case TopAbs_COMPSOLID:
467     break;
468   case TopAbs_SOLID:
469     break;
470   case TopAbs_SHELL:
471     break;
472   case TopAbs_FACE:
473     {
474       const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, theDoc);
475       if(!aSelection.IsNull()) {// Select it
476         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
477         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
478         theShapeToBeSelected = aShapeToBeSelected;
479         theCont = aCont;
480         return true;
481       }
482     }
483     break;
484   case TopAbs_WIRE:
485     break;
486   case TopAbs_EDGE:
487     {  
488       TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
489       const TDF_Label& aLabel = theDoc->findNamingName(theSubShapeName);
490       if(!aLabel.IsNull()) {
491         Handle(TNaming_NamedShape) aNS;
492         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
493           aSelection = getShapeFromNS(theSubShapeName, aNS);
494         }
495       }
496       if(aSelection.IsNull()) {
497         std::list<std::string> aListofNames;
498         int n = ParseName(theSubShapeName, aListofNames);
499         if(n > 1 && n < 5) {
500           TopTools_ListOfShape aList;
501           std::list<std::string>::iterator it =aListofNames.begin();
502           for(;it != aListofNames.end();it++){
503             const TopoDS_Shape aFace = findFaceByName(*it, theDoc);
504             aList.Append(aFace);                
505           }
506           aSelection = findCommonShape(TopAbs_EDGE, aList);
507         }
508       }
509       if(!aSelection.IsNull()) {// Select it
510         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
511         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
512         theShapeToBeSelected = aShapeToBeSelected;
513         theCont = aCont;
514         return true;
515       }
516     }
517     break;
518   case TopAbs_VERTEX:
519     {
520       TopoDS_Shape aSelection;
521       const TDF_Label& aLabel = theDoc->findNamingName(theSubShapeName);
522       if(!aLabel.IsNull()) {
523         Handle(TNaming_NamedShape) aNS;
524         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
525           aSelection = getShapeFromNS(theSubShapeName, aNS);
526         }
527       }
528       if(aSelection.IsNull()) {
529         std::list<std::string> aListofNames;
530         int n = ParseName(theSubShapeName, aListofNames);
531         if(n > 1 && n < 4) { // 2 || 3
532           TopTools_ListOfShape aList;
533           std::list<std::string>::iterator it = aListofNames.begin();
534           for(; it != aListofNames.end(); it++){
535             const TopoDS_Shape aFace = findFaceByName(*it, theDoc);
536             if(!aFace.IsNull())
537               aList.Append(aFace);              
538           }
539           aSelection = findCommonShape(TopAbs_VERTEX, aList);
540         }
541       }
542       if(!aSelection.IsNull()) {// Select it
543         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
544         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
545         theShapeToBeSelected = aShapeToBeSelected;
546         theCont = aCont;
547         return true;
548       }
549     }
550     break;
551   default: //TopAbs_SHAPE
552     return false;
553   }
554   return false;
555 }
556