Salome HOME
Merge commit '0d956a814' into pre/IMPS_2016
[modules/hydro.git] / src / HYDROData / HYDROData_SplitToZonesTool.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include "HYDROData_SplitToZonesTool.h"
20
21 #include "HYDROData_PolylineXY.h"
22 #include "HYDROData_ShapesGroup.h"
23 #include <HYDROData_Transform.h>
24 #include <BRepAlgoAPI_Cut.hxx>
25 #include <BRepAlgoAPI_Common.hxx>
26 #include <BRepBuilderAPI_MakeFace.hxx>
27 #include <BRep_Builder.hxx>
28 #include <TopExp_Explorer.hxx>
29 #include <TopoDS.hxx>
30 #include <TopoDS_Shape.hxx>
31 #include <TopoDS_Compound.hxx>
32 #include <TopoDS_Wire.hxx>
33 #include <TopoDS_Edge.hxx>
34 #include <BRepCheck_Analyzer.hxx>
35 #include <TopTools_ListOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_IndexedMapOfShape.hxx>
38 #include <gp_Pln.hxx>
39 #include <BRepGProp.hxx>
40 #include <GProp_GProps.hxx>
41 #include <Geom_Plane.hxx>
42 #include <BRepBuilderAPI_FindPlane.hxx>
43
44 #include <BOPAlgo_BOP.hxx>
45 #include <BOPAlgo_Builder.hxx>
46 #include <TopExp.hxx>
47 #include <assert.h>
48
49 //#define DEB_SPLIT_TO_ZONES 1
50 //#define DEB_SPLIT_TO_ZONES_CHECK_PARTITION 1
51 #if (defined (DEB_SPLIT_TO_ZONES) || defined(DEB_SPLIT_TO_ZONES_CHECK_PARTITION))
52 #include <BRepTools.hxx>
53 static TCollection_AsciiString fileNameBefore("BeforeTranslation");
54 #endif
55
56 #define _DEVDEBUG_
57 #include "HYDRO_trace.hxx"
58
59 TopoDS_Face HYDROData_SplitToZonesTool::SplitData::Face() const
60 {
61   TopoDS_Face aResFace;
62
63   if( !Shape.IsNull() )
64   {
65     if ( Shape.ShapeType() == TopAbs_FACE )
66     {
67       aResFace = TopoDS::Face( Shape );
68     }
69     else if ( Shape.ShapeType() == TopAbs_WIRE )
70     {
71       BRepBuilderAPI_MakeFace aMakeFace( TopoDS::Wire( Shape ), Standard_True );
72       aMakeFace.Build();
73       if( aMakeFace.IsDone() )
74         aResFace = aMakeFace.Face();
75     }
76   }
77
78   return aResFace;
79 }
80
81 Standard_Boolean buildLimFace(const TopoDS_Wire& theBndWire, TopoDS_Face& outFace) 
82 {
83   GProp_GProps G;
84   BRepGProp::LinearProperties(theBndWire,G);
85   const gp_Pnt& aCPnt = G.CentreOfMass();
86   gp_Pln aPln;
87   BRepBuilderAPI_FindPlane fndPlane (theBndWire, Precision::Confusion());  
88   if(fndPlane.Found())
89     aPln = fndPlane.Plane()->Pln();
90   else
91     aPln = gp_Pln(aCPnt, gp::OZ().Direction());
92   BRepBuilderAPI_MakeFace  aMkFace(aPln, theBndWire);
93   if(aMkFace.IsDone()) {
94     outFace = aMkFace.Face();      
95     if(!outFace.IsNull()) {
96 #ifdef DEB_SPLIT_TO_ZONES
97 //      BRepTools::Write(limFace,"FL.brep");
98 #endif
99       return Standard_True;
100     }
101   }
102   return Standard_False;
103 }
104 //======================================================================================
105
106 void HYDROData_SplitToZonesTool::SetFileNames(const QString& theNameBefore, const QString& theNameAfter)
107 {
108 #ifdef DEB_SPLIT_TO_ZONES_CHECK_PARTITION
109   if(!theNameBefore.isNull() && !theNameBefore.isEmpty())
110   {
111     TCollection_AsciiString aName (theNameBefore.toStdString().data());
112     fileNameBefore = aName;
113   }
114   if(!theNameAfter.isNull() && !theNameAfter.isEmpty())
115   {
116     TCollection_AsciiString aName (theNameAfter.toStdString().data());
117     HYDROData_Transform::SetFileName (aName);
118   }
119 #endif
120 }
121 //======================================================================================
122 Standard_Integer HYDROData_SplitToZonesTool::SplitFaces(const TopoDS_Compound& theComp, 
123                                                         HYDROData_Transform& theTool)
124 {
125   theTool.Clear();
126   theTool.SetArgument(theComp);
127   theTool.Detect();
128   const Standard_Boolean bToTransform = theTool.ToTransform();  
129   theTool.SetToTransform(bToTransform);  
130   theTool.Perform();
131   Standard_Integer anErr = theTool.ErrorStatus();
132   return anErr;
133 }
134
135 //======================================================================================
136 HYDROData_SplitToZonesTool::SplitDataList
137   HYDROData_SplitToZonesTool::Split( const HYDROData_SequenceOfObjects&  theObjectList,
138                                      const HYDROData_SequenceOfObjects&  theGroupsList,
139                                      const Handle(HYDROData_PolylineXY)& thePolyline,
140                                      const HYDROData_SequenceOfObjects& InterPolys)
141 {
142 #ifndef NDEBUG
143   DEBTRACE("Split");
144 #endif
145   SplitDataList anOutputSplitDataList;
146   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher> OutNE;
147   if(theObjectList.IsEmpty())
148     return anOutputSplitDataList;
149   // Preparation. 
150   // Collect the object shapes to split. InputDataList will contain elements which will hold shape & name_of_shape.
151   SplitDataList anInputSplitDataList;
152 #ifdef DEB_SPLIT_TO_ZONES
153   TCollection_AsciiString aNam("Faces_");
154 #endif
155   for( int anIndex = 1, aLength = theObjectList.Length(); anIndex <= aLength; anIndex++ )
156   {
157     Handle(HYDROData_Entity) anObj = theObjectList.Value( anIndex );
158     TopoDS_Shape aShape;
159
160     Handle(HYDROData_Object) aGeomObj = Handle(HYDROData_Object)::DownCast( anObj );
161     if( !aGeomObj.IsNull() ) {
162       aShape = aGeomObj->GetTopShape();
163     }
164
165     if ( aShape.IsNull() )
166       continue;  
167 #ifdef DEB_SPLIT_TO_ZONES
168    TCollection_AsciiString aName = aNam + anIndex + "_a.brep";
169    BRepTools::Write(aShape, aName.ToCString());
170 #endif
171     if ( aShape.ShapeType() == TopAbs_COMPOUND ) {
172       // Create split data for each face contained in the compound
173       TopExp_Explorer anExp( aShape, TopAbs_FACE );
174       for ( ; anExp.More(); anExp.Next() ) {
175         const TopoDS_Face& aFace = TopoDS::Face( anExp.Current() );
176         if ( !aFace.IsNull() ) {
177           SplitData aSplitData( SplitData::Data_Zone, aFace, anObj->GetName() );
178           anInputSplitDataList.append( aSplitData );
179         }
180       }
181     } else {
182       SplitData aSplitData( SplitData::Data_Zone, aShape, anObj->GetName() );
183       anInputSplitDataList.append( aSplitData );
184     }
185   }
186   //
187   SplitDataList anInputGroupList;
188   for( int anIndex = 1, aLength = theGroupsList.Length(); anIndex <=aLength; anIndex++ )
189   {
190     Handle(HYDROData_ShapesGroup) aGeomGroup = 
191       Handle(HYDROData_ShapesGroup)::DownCast( theGroupsList.Value( anIndex ) );
192     if( aGeomGroup.IsNull() )
193       continue;
194       
195     TopTools_SequenceOfShape aGroupShapes;
196     aGeomGroup->GetShapes( aGroupShapes );
197     for( int i = 1, aNbShapes = aGroupShapes.Length(); i <= aNbShapes; i++ ) {
198       const TopoDS_Shape& aGroupShape = aGroupShapes.Value( i );
199       if ( aGroupShape.IsNull() )
200         continue;  
201
202       if ( aGroupShape.ShapeType() == TopAbs_COMPOUND ) {    
203         TopExp_Explorer anExp( aGroupShape, TopAbs_EDGE );
204         for ( ; anExp.More(); anExp.Next() ) {
205           const TopoDS_Edge& anEdge = TopoDS::Edge( anExp.Current() );
206           if ( !anEdge.IsNull() ) {
207             SplitData aSplitData( SplitData::Data_Edge, anEdge, aGeomGroup->GetName() );
208             anInputGroupList.append( aSplitData );
209           }
210         }
211       } else {
212         SplitData aSplitData( SplitData::Data_Edge, aGroupShape, aGeomGroup->GetName() );
213         anInputGroupList.append( aSplitData );
214 #ifdef DEB_SPLIT_TO_ZONES
215         QString aStr = aSplitData.ObjectNames.join(" "); 
216         DEBTRACE("Group# = " <<anIndex <<" Nmb in grp = " << i<< " Names = "<<aStr.toStdString() << " size = " <<aSplitData.ObjectNames.size());
217 #endif
218       }
219     }
220   }
221   // If only one shape is given we don't split it 
222   // algorithm just returns the unpacked input data
223   bool limplus1Object(false);
224   if(theObjectList.Size() == 1 ) 
225   {
226     if(thePolyline.IsNull()) 
227     {
228       //anOutputSplitDataList.append(anInputSplitDataList); 
229       SplitData SD = anInputSplitDataList.at(0);
230       TopTools_ListOfShape newshs;
231       TopTools_IndexedDataMapOfShapeListOfShape OutOrSh2M;
232       CutFaceByEdges(SD.Face(), newshs, InterPolys, &OutNE, &OutOrSh2M);
233       for (TopTools_ListIteratorOfListOfShape it(newshs); it.More(); it.Next())
234       {
235         SplitData NSD = SD;
236         NSD.Shape = it.Value();
237         anOutputSplitDataList.append(NSD);
238       }
239
240       NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>::Iterator spit(OutNE);
241       for (;spit.More();spit.Next())
242       {
243         const TopoDS_Edge& E = TopoDS::Edge(spit.Key());
244         if (E.IsNull())
245           continue;
246         SplitData SDI(SplitData::Data_IntEdge, E, spit.Value()->GetName());   
247         anOutputSplitDataList.append(SDI);
248       }
249
250 #ifndef NDEBUG
251       //check CutFaceByEdges method: ensure that SD.Face() edges fully covered by
252       //history map (OutOrSh2M)
253       if (!OutOrSh2M.IsEmpty())
254       {
255         TopTools_IndexedMapOfShape EE;
256         TopExp::MapShapes(SD.Face(), TopAbs_EDGE, EE);
257         int noncontNb = 0;      
258         for (int i = 1; i <= EE.Extent(); i++)
259         {
260           const TopoDS_Shape& E = EE(i);
261           noncontNb += !OutOrSh2M.Contains(E);
262         }
263         //noncontNb > 0 => some problem with edge history
264         assert(noncontNb == 0);
265       }
266 #endif
267
268       if(!theGroupsList.IsEmpty() ) 
269       {
270         SplitDataList ModifInpGroupList;
271         SplitDataListIterator it(anInputGroupList);
272         while( it.hasNext() )
273         {
274           const SplitData& SData = it.next();
275           if (SData.Type != SplitData::Data_Edge)
276             ModifInpGroupList.append(SData); //add as is
277           const TopoDS_Shape& SData_sh = SData.Shape;
278           TopTools_ListOfShape modif_ls;
279           if (!InterPolys.IsEmpty())
280             if (OutOrSh2M.Contains(SData_sh))
281               modif_ls = OutOrSh2M.FindFromKey(SData_sh);
282             //else TODO -  show message that one of the object should be updated
283
284 #ifndef NDEBUG
285           if (!InterPolys.IsEmpty() && OutOrSh2M.IsEmpty())
286             assert (true);
287 #endif
288           if (modif_ls.IsEmpty())
289             ModifInpGroupList.append(SData); //non modified
290           else
291           {
292             TopTools_ListIteratorOfListOfShape itl_modif(modif_ls);
293             for (;itl_modif.More();itl_modif.Next())
294             {
295               const TopoDS_Shape& CSH = itl_modif.Value();
296               if (CSH.ShapeType() == TopAbs_EDGE)
297               {
298                 SplitData NewSData;
299                 NewSData.ObjectNames = SData.ObjectNames;
300                 NewSData.Type = SData.Type;
301                 NewSData.Shape = CSH;
302                 ModifInpGroupList.append(NewSData);
303               }
304             }
305           }
306
307         }
308         anOutputSplitDataList.append(ModifInpGroupList);
309       }
310       return anOutputSplitDataList;
311     }
312     else
313       limplus1Object = true;// size =1 && hasLimits
314   }
315   HYDROData_DataMapOfShapeListOfString aDM3;
316   if(!anInputGroupList.isEmpty()) {// Old edge ==> List_Of_Names
317     QStringList aListOfNames;
318     for (int i=0;i < anInputGroupList.size() ;i++) {
319       const TopoDS_Shape& aSh = anInputGroupList.at(i).Shape;
320       aDM3.Add(aSh, anInputGroupList.at(i).ObjectNames);
321     }
322   }
323
324   // Step 1. Prepare Partition structures. 
325   TopoDS_Shape aResult;
326   BOPCol_ListOfShape aLS;  
327   QStringList aListOfNames;
328   TopoDS_Compound aCmp;
329   BRep_Builder aBB;
330   aBB.MakeCompound(aCmp);
331   for (int i=0;i < anInputSplitDataList.size() ;i++) {
332     const TopoDS_Shape& aSh = anInputSplitDataList.at(i).Shape;
333     aDM3.Add(aSh, anInputSplitDataList.at(i).ObjectNames);
334     aLS.Append(aSh);
335     aBB.Add(aCmp,aSh);
336 #ifdef DEB_SPLIT_TO_ZONES
337     TCollection_AsciiString aName = aNam + i + "_b.brep";
338     BRepTools::Write(aSh, aName.ToCString());
339 #endif
340   }
341 #ifdef DEB_SPLIT_TO_ZONES_CHECK_PARTITION
342   TCollection_AsciiString aNameBefore = fileNameBefore + "_c.brep";
343   BRepTools::Write(aCmp, aNameBefore.ToCString());
344 #endif
345
346   HYDROData_DataMapOfShapeListOfShape aDM1;
347   if(anInputSplitDataList.size() > 1) {
348     HYDROData_Transform splitTool; 
349     const Standard_Integer anErr = SplitFaces(aCmp, splitTool);    
350     if(anErr)
351       return anOutputSplitDataList;
352     aResult = splitTool.Shape();
353     if (aResult.IsNull()) 
354       return anOutputSplitDataList;
355     BRepCheck_Analyzer aCheck (aResult);
356     if(!aCheck.IsValid()) {
357   #ifdef DEB_SPLIT_TO_ZONES
358       DEBTRACE("result is not valid");
359       BRepTools::Write(aResult, "SplitFacesNV.brep");  
360   #endif
361       return anOutputSplitDataList;
362     }
363   #ifdef DEB_SPLIT_TO_ZONES
364     BRepTools::Write(aResult, "SplitFacesV.brep");
365   #endif
366     
367     // Step 3. Collect history  
368     //HYDROData_DataMapOfShapeListOfShape aDM1;
369     BOPCol_ListIteratorOfListOfShape anIt(aLS); 
370   #ifdef DEB_SPLIT_TO_ZONES
371     TCollection_AsciiString aNamM ("EdgM_");
372     TCollection_AsciiString aNamG ("EdgG_");
373   #endif
374     for (int i =1;anIt.More();anIt.Next(),i++) {
375       Standard_Boolean foundF(Standard_False);
376       const TopTools_ListOfShape& aListOfNew = splitTool.Modified(anIt.Value());
377       if(!aListOfNew.IsEmpty())
378         foundF = Standard_True;
379
380       TopTools_ListOfShape aList;
381
382       TopTools_ListIteratorOfListOfShape it(aListOfNew);
383       for(;it.More();it.Next())       
384         aList.Append(it.Value());
385           /* *********************************************************************
386       // Bug in History: partition should give only modified entities! => temporary solution is used
387       //const TopTools_ListOfShape& aListOfGen = splitTool.Generated(anIt.Value());
388       //if(!aListOfGen.IsEmpty())
389         //foundF = Standard_True;
390       //it.Initialize(aListOfGen);    
391       //for(;it.More();it.Next())     
392        // aList.Append(it.Value());  
393            ********************************************************************* */
394       if(!foundF) // face is not modified
395         aList.Append (anIt.Value());
396       aDM1.Add(anIt.Value(), aList);
397   #ifdef DEB_SPLIT_TO_ZONES
398       TCollection_AsciiString aName;
399   #endif
400       if(!anInputGroupList.isEmpty() ) { // 1
401         TopExp_Explorer exp (anIt.Value(), TopAbs_EDGE);
402         for (int j =1;exp.More();exp.Next(),j++) {
403           aList.Clear();
404           Standard_Boolean foundE(Standard_False);
405           const TopTools_ListOfShape& aListM = splitTool.Modified(exp.Current()); 
406 #ifndef NDEBUG
407           DEBTRACE("NB_EDGE_M = " << aListM.Extent());
408 #endif
409           if(aListM.Extent()) foundE = Standard_True;
410           it.Initialize(aListM);    
411           for(int k=1;it.More();it.Next(),k++) {    
412             aList.Append(it.Value());
413   #ifdef DEB_SPLIT_TO_ZONES
414             aName = aNamM + i + j +k +"_d.brep";
415             BRepTools::Write(it.Value(),aName.ToCString());
416   #endif
417           }
418           /* *********************************************************************
419                   //const TopTools_ListOfShape& aListG = splitTool.Generated(exp.Current());
420           //if(aListG.Extent()) foundE = Standard_True;
421           //it.Initialize(aListG);    
422           //for(int k=1;it.More();it.Next(),k++)
423             //aList.Append(it.Value());
424           //cout << "NB_EDGE = " << aList.Extent() <<endl;
425                   ************************************************************************** */
426           if(!foundE) {
427             aList.Append (exp.Current());
428   #ifdef DEB_SPLIT_TO_ZONES
429             aName = aNamG + i + j +"_e.brep";
430             BRepTools::Write(exp.Current(),aName.ToCString());
431             DEBTRACE(aName.ToCString()<< " = " << exp.Current().TShape());
432   #endif
433           }
434           aDM1.Add(exp.Current(), aList);
435         }
436       }
437     }
438   } else {
439       aResult = anInputSplitDataList.at(0).Shape; // get single input shape
440   }
441
442   // aDM2: NewShape ==> ListOfOldShapes
443   HYDROData_DataMapOfShapeListOfShape aDM2;
444   // make limiting face
445   HYDROData_DataMapOfShapeListOfShape aDM4;
446   Standard_Boolean hasLimits(Standard_False);
447   QString aBndName;
448   HYDROData_MapOfShape aBndView;
449   if (! thePolyline.IsNull()) {
450     Handle(TopTools_HSequenceOfShape) aConnectedWires = new TopTools_HSequenceOfShape;
451     int nbWires = thePolyline->GetNbConnectedWires(aConnectedWires);
452     const TopoDS_Wire aBndWire = TopoDS::Wire(aConnectedWires->Value(1));
453     if(!aBndWire.IsNull()) {
454       TopoDS_Face limFace;       
455       if(buildLimFace(aBndWire, limFace)) {
456         TopoDS_Shape aComResult;
457         BRepAlgoAPI_Common mkCom(aResult, limFace);
458         if(mkCom.IsDone()) {
459           aComResult = mkCom.Shape();
460           BRepCheck_Analyzer aCheck (aComResult);
461           if(aCheck.IsValid()) {
462 #ifdef DEB_SPLIT_TO_ZONES
463             BRepTools::Write(aComResult,"CommonV.brep");
464             BRepTools::Write(limFace,"limFace.brep");
465 #endif    
466             aBndName = thePolyline->GetName();
467             hasLimits = Standard_True; // DM2 should be filled here
468             TopExp_Explorer exp (limFace, TopAbs_EDGE);
469             for (int i =1;exp.More();exp.Next(),i++) {
470               const TopoDS_Shape& anEdge = exp.Current();
471               if(anEdge.IsNull()) continue;
472               aBndView.Add(anEdge);
473               QStringList aListOfNames;
474               aListOfNames.append(aBndName);
475               aDM3.Add(anEdge, aListOfNames);
476               TopTools_ListOfShape aList;
477               aList.Append(anEdge);
478               aDM1.Add(anEdge,aList);
479             }
480             HYDROData_MapOfShape aView;
481             exp.Init (aResult, TopAbs_FACE);
482             for (int i =1;exp.More();exp.Next(),i++) {
483               const TopoDS_Shape& aFace = exp.Current();
484               if(!aFace.IsNull()) {
485                 const TopTools_ListOfShape& aListOfNew = mkCom.Modified(aFace);
486 #ifndef NDEBUG
487                 DEBTRACE("Modified: " << aListOfNew.Extent());
488 #endif
489                 if(!aListOfNew.IsEmpty()) {
490                   aDM4.Add(aFace, aListOfNew);
491 #ifdef DEB_SPLIT_TO_ZONES
492                   TCollection_AsciiString aName = aNam + i + "_f.brep";
493                   BRepTools::Write(aListOfNew.Last(), aName.ToCString());
494 #endif
495                 }
496                 else {
497                     if(!mkCom.IsDeleted(aFace)) {
498                       const TopTools_ListOfShape& aListOfGen = mkCom.Generated(aFace);    
499                       if(!aListOfGen.IsEmpty()) {
500                         /* aDM4.Bind(aFace, aListOfGen); ???   */
501 #ifdef DEB_SPLIT_TO_ZONES
502                         TCollection_AsciiString aName = aNam + i + "_g.brep";
503                         BRepTools::Write(aListOfGen.Last(), aName.ToCString());
504 #endif
505                       }
506                        else {
507                         TopTools_ListOfShape aList; 
508                         aList.Append(aFace);
509                         aDM4.Add(aFace, aList); //the same face - not modified
510                        }
511                     }
512              }
513              TopExp_Explorer exp2 (aFace, TopAbs_EDGE);
514              for (int j =1;exp2.More();exp2.Next(),j++) {
515                const TopoDS_Shape& anEdge = exp2.Current();
516                if(!anEdge.IsNull()) {
517                  if(aView.Contains(anEdge)) continue;
518                  aView.Add(anEdge);
519                  const TopTools_ListOfShape& aListOfNewEd = mkCom.Modified(anEdge);                 
520                  if(!aListOfNewEd.IsEmpty())
521                    aDM4.Add(anEdge, aListOfNewEd);
522                  else {
523                    if(!mkCom.IsDeleted(anEdge)) {
524                      const TopTools_ListOfShape& aListOfGenEd = mkCom.Generated(anEdge);
525                      if(!aListOfGenEd.IsEmpty()) {
526                        /* aDM4.Bind(anEdge, aListOfGenEd); ???*/
527                      } else {
528                        TopTools_ListOfShape aList; 
529                        aList.Append(anEdge);
530                        aDM4.Add(anEdge, aList);//the same edge - not modified
531                      }
532                    }
533                  }
534                }
535              }
536             }
537             } //end DM4 filling (phase 1)
538             //cout << "DM4 Ext = " <<aDM4.Extent() <<endl;
539          // phase 2 (from tool)
540 #ifdef DEB_SPLIT_TO_ZONES
541          TCollection_AsciiString aNam("BndEd_");
542 #endif
543          TopExp_Explorer expt (limFace, TopAbs_EDGE);
544          for(int i =1;expt.More();expt.Next(),i++) {
545            const TopoDS_Shape& anEdge = expt.Current();
546            if(!anEdge.IsNull()) {
547              const TopTools_ListOfShape& aListOfNewEd = mkCom.Modified(anEdge);    
548 #ifdef DEB_SPLIT_TO_ZONES
549              TopTools_ListIteratorOfListOfShape itl(aListOfNewEd);
550              for(int j=1;itl.More();itl.Next(),j++) {
551                TCollection_AsciiString aName = aNam + i + "_" + j + "_j.brep";
552                BRepTools::Write(itl.Value(), aName.ToCString());
553                DEBTRACE(aName.ToCString()<<" = "<< itl.Value().TShape());
554              }
555 #endif
556              if(!aListOfNewEd.IsEmpty())
557                aDM4.Add(anEdge, aListOfNewEd);
558              else {
559                if(!mkCom.IsDeleted(anEdge)) {
560                  const TopTools_ListOfShape& aListOfGenEd = mkCom.Generated(anEdge);
561                  if(!aListOfGenEd.IsEmpty()) {
562                    /* aDM4.Bind(anEdge, aListOfGenEd); ??? */
563                  } else {
564                    TopTools_ListOfShape aList; 
565                    aList.Append(anEdge);
566                    aDM4.Add(anEdge, aList);//the same edge - not modified
567                  }
568                }
569              }
570            }
571          }
572          //cout << "DM4 Ext = " <<aDM4.Extent() <<endl;
573          if(limplus1Object) {
574            // fill DM1 (old - new) and DM2 (new - old)
575            HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape mIt(aDM4);
576            for(;mIt.More();mIt.Next()) {
577              const TopoDS_Shape& aKey = mIt.Key();//old
578              TopTools_ListOfShape aList;
579              aList.Append(aKey);
580              const TopTools_ListOfShape& aListOfNew = mIt.Value();
581              aDM1.Add(aKey, aListOfNew);
582              TopTools_ListIteratorOfListOfShape it(aListOfNew);
583              for(;it.More();it.Next()) {
584                if(!aDM2.Contains(it.Value()))
585                  aDM2.Add(it.Value(), aList);
586                else {
587                  TopTools_ListOfShape& aList = aDM2.ChangeFromKey(it.Value());
588                  aList.Prepend(aKey);
589                }
590              }
591            }
592          } else {
593            HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape aMIt(aDM1); 
594            //DM4 contains Old - New after common op. DM1: old - new after Split op.
595            for(;aMIt.More();aMIt.Next()) {
596              const TopoDS_Shape& aKey = aMIt.Key();
597              TopTools_ListOfShape aList;
598              aList.Append(aKey);
599              const TopTools_ListOfShape& aListOfNew = aMIt.Value();
600              TopTools_ListIteratorOfListOfShape it(aListOfNew);
601              for(;it.More();it.Next()) {// iterate new: b1, b2, b3...
602                if(!aDM4.Contains(it.Value())) // bi - is deleted
603                  continue; // go to the next bi
604                else {
605                  const TopTools_ListOfShape& aListOfNew4 = aDM4.FindFromKey(it.Value());
606                   TopTools_ListIteratorOfListOfShape it4(aListOfNew4); // {c1, c2, c3,...}
607                   for(;it4.More();it4.Next()) {
608                     if(!aDM2.Contains(it4.Value()))
609                       aDM2.Add(it4.Value(), aList);
610                     else {
611                       TopTools_ListOfShape& aList = aDM2.ChangeFromKey(it4.Value());
612                       aList.Prepend(aKey);
613                     }
614                   }
615                }
616              }
617            }
618          }
619          } else {
620              hasLimits = Standard_False;
621 #ifdef DEB_SPLIT_TO_ZONES
622              BRepTools::Write(aComResult,"CommonNV.brep");
623 #endif    
624           }
625        }
626       }
627     }
628   }// end limits processing
629   if(!hasLimits) {
630     HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape aMIt(aDM1);
631     for(;aMIt.More();aMIt.Next()) {
632       const TopoDS_Shape& aKey = aMIt.Key();
633       TopTools_ListOfShape aList;
634       aList.Append(aKey);
635       const TopTools_ListOfShape& aListOfNew = aMIt.Value();
636       TopTools_ListIteratorOfListOfShape it(aListOfNew);
637       for(;it.More();it.Next()) {
638         if(!aDM2.Contains(it.Value()))
639           aDM2.Add(it.Value(), aList);
640         else {
641           TopTools_ListOfShape& aList = aDM2.ChangeFromKey(it.Value());
642           aList.Prepend(aKey);
643         }
644       }
645     }
646   }
647
648   AddInternalEdges(aDM2, InterPolys, &OutNE);
649   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>::Iterator spit(OutNE);
650   for (;spit.More();spit.Next())
651   {
652     const TopoDS_Edge& E = TopoDS::Edge(spit.Key());
653     if (E.IsNull())
654       continue;
655     SplitData SDI(SplitData::Data_IntEdge, E, spit.Value()->GetName());   
656     anOutputSplitDataList.append(SDI);
657   }
658
659   // Step 4. Fill output structure.
660 #ifdef DEB_SPLIT_TO_ZONES
661   TCollection_AsciiString aNam4 ("SC_");
662 #endif  
663   HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape aMIt(aDM2);
664   for(int i =1;aMIt.More();aMIt.Next(),i++) {
665     SplitData aDestSplitData;
666     const TopoDS_Shape& aKey = aMIt.Key(); //new
667     aDestSplitData.Shape = aKey;
668     if(aKey.ShapeType() == TopAbs_FACE)
669       aDestSplitData.Type = SplitData::Data_Zone;
670     else {
671       aDestSplitData.Type = SplitData::Data_Edge;
672 #ifdef DEB_SPLIT_TO_ZONES
673       TCollection_AsciiString aName = aNam4 + i + "_k.brep";
674       BRepTools::Write(aKey,aName.ToCString());
675 #endif    
676     }
677
678     QStringList aListOfNames; // names processing
679     const TopTools_ListOfShape& aListOfOld = aMIt.Value();
680     TopTools_ListIteratorOfListOfShape it(aListOfOld);
681     for(int j =1;it.More();it.Next(),j++) {    
682       const TopoDS_Shape& aSh = it.Value(); //old
683       if(aDM3.Contains(aSh)) {
684         const QStringList& ObjectNames = aDM3.FindFromKey(aSh);    
685         aListOfNames.append(ObjectNames);
686 #ifdef DEB_SPLIT_TO_ZONES
687         TCollection_AsciiString aName = aNam4 + i +"_" + j + "_l.brep";
688         BRepTools::Write(aSh ,aName.ToCString());        
689 #endif    
690       }    else {
691 #ifdef DEB_SPLIT_TO_ZONES
692         TCollection_AsciiString aName = aNam4 +"__" + i +"_" + j + "_m.brep";
693         BRepTools::Write(aSh ,aName.ToCString());        
694         DEBTRACE(aName.ToCString()<<" = "<< aSh.TShape());
695 #endif
696           if(aBndView.Contains(aSh) && hasLimits) {            
697             aListOfNames.append(aBndName);
698 #ifdef DEB_SPLIT_TO_ZONES
699             DEBTRACE(" BndName = "<<aBndName.toStdString());
700 #endif
701           }
702       }
703     }
704
705     aDestSplitData.ObjectNames = aListOfNames;  
706     anOutputSplitDataList.append(aDestSplitData);    
707 #ifdef DEB_SPLIT_TO_ZONES
708     QString aStr = aDestSplitData.ObjectNames.join(" "); 
709     DEBTRACE("New# = " << i<< " Names = "<<aStr.toStdString() << " size = " <<aDestSplitData.ObjectNames.size());
710 #endif
711   }
712
713   return anOutputSplitDataList;
714 }
715
716 HYDROData_SplitToZonesTool::SplitDataList
717   HYDROData_SplitToZonesTool::Split( const HYDROData_SequenceOfObjects& theObjectList )
718 {
719   HYDROData_SequenceOfObjects aGeomGroups;
720   Handle(HYDROData_PolylineXY) aPolyline;
721   HYDROData_SequenceOfObjects InterPolys;
722
723   return Split( theObjectList, aGeomGroups, aPolyline, InterPolys );
724 }
725
726 void HYDROData_SplitToZonesTool::AddInternalEdges(HYDROData_DataMapOfShapeListOfShape& DM,
727    const HYDROData_SequenceOfObjects& thePolylines,
728    NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>* OutNE)
729 {
730
731   HYDROData_SequenceOfObjects::Iterator it(thePolylines);
732   TopTools_ListOfShape Wires;
733   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher> W2P;
734   for (;it.More();it.Next())
735   {
736     Handle(HYDROData_PolylineXY) P = Handle(HYDROData_PolylineXY)::DownCast(it.Value());
737     const TopoDS_Shape& CW = P->GetShape();
738     Wires.Append(CW);
739     W2P.Bind(CW, P);
740   }
741
742   HYDROData_DataMapOfShapeListOfShape newDM;
743   TopTools_IndexedDataMapOfShapeShape OutNE1;
744   for (int i = 1; i <= DM.Extent();i++)
745   {
746     const TopoDS_Shape& K = DM.FindKey(i);
747     const TopTools_ListOfShape& V = DM.FindFromIndex(i);
748     TopTools_ListOfShape out;
749     if (K.ShapeType() == TopAbs_FACE)
750     {
751       CutByEdges(K, Wires, out, &OutNE1, NULL);
752       TopTools_ListIteratorOfListOfShape it(out);
753       for (;it.More(); it.Next())
754       {
755         const TopoDS_Shape& NF = it.Value();
756         if (!NF.IsNull())
757           newDM.Add(NF, V);
758       }
759     }
760     else
761       newDM.Add(K, V); // ignore edges, wires...
762   }
763
764   for (int i = 1; i <= OutNE1.Extent(); i++)
765     OutNE->Bind(OutNE1.FindKey(i), W2P(OutNE1.FindFromIndex(i)));
766
767   DM = newDM;
768 }
769
770 void HYDROData_SplitToZonesTool::CutFaceByEdges(const TopoDS_Face& in, 
771                                                 TopTools_ListOfShape& out, 
772                                                 const HYDROData_SequenceOfObjects& thePolylines,
773                                                 NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>* OutNE,                                                
774                                                 TopTools_IndexedDataMapOfShapeListOfShape* OutOrSh2M)
775 {
776
777   HYDROData_SequenceOfObjects::Iterator it(thePolylines);
778   TopTools_ListOfShape Wires;
779   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher> W2P;
780   for (;it.More();it.Next())
781   {
782     Handle(HYDROData_PolylineXY) P = Handle(HYDROData_PolylineXY)::DownCast(it.Value());
783     const TopoDS_Shape& CW = P->GetShape();
784     Wires.Append(CW);
785     W2P.Bind(CW, P);
786   }
787
788   TopTools_IndexedDataMapOfShapeShape OutNE1;
789   CutByEdges(in, Wires, out, &OutNE1, OutOrSh2M);
790
791   for (int i = 1; i <= OutNE1.Extent(); i++)
792     OutNE->Bind(OutNE1.FindKey(i), W2P(OutNE1.FindFromIndex(i)));
793
794 }
795
796 int HYDROData_SplitToZonesTool::CutByEdges(const TopoDS_Shape& InSh, const TopTools_ListOfShape& InW,
797                                            TopTools_ListOfShape& outShs, 
798                                            TopTools_IndexedDataMapOfShapeShape* OutNE, 
799                                            TopTools_IndexedDataMapOfShapeListOfShape* OInSH2MSH)
800 {
801   int anError;
802   if (InSh.IsNull())
803     return -1;
804   if (InW.IsEmpty())
805   {
806     outShs.Clear();
807     outShs.Append(InSh);
808     return 0;
809   }
810   TopTools_ListIteratorOfListOfShape anIt;
811   BOPAlgo_Builder anAlgo;
812   anAlgo.AddArgument(InSh);
813
814   anIt.Initialize( InW );
815   for( ; anIt.More(); anIt.Next() )
816     anAlgo.AddArgument( anIt.Value() );
817
818   anAlgo.Perform(); 
819   anError = anAlgo.ErrorStatus();
820   if (anError)
821     return anError;
822
823   outShs = anAlgo.Modified( InSh );
824   if (outShs.IsEmpty())
825     outShs.Append(InSh);
826
827   if (OutNE)
828   {
829     TopTools_IndexedDataMapOfShapeShape NonFOutNE;
830     anIt.Initialize( InW );
831     for( ; anIt.More(); anIt.Next() )
832     {
833       const TopoDS_Shape& OSH = anIt.Value(); 
834       TopExp_Explorer exp(OSH, TopAbs_EDGE);
835       for (;exp.More();exp.Next())
836       {
837         const TopoDS_Edge& OE = TopoDS::Edge(exp.Current());
838         const TopTools_ListOfShape& ls = anAlgo.Modified(OE);
839         TopTools_ListIteratorOfListOfShape itls(ls);
840         for (;itls.More();itls.Next())
841           NonFOutNE.Add(itls.Value(), OSH);
842       }
843     }
844
845     //filter edges; if face contain an edge => keep it
846     TopTools_IndexedMapOfShape AllEdges; //edges from output shape
847     for (anIt.Initialize(outShs); anIt.More();anIt.Next())
848       TopExp::MapShapes(anIt.Value(), TopAbs_EDGE, AllEdges);
849
850     for (int i = 1; i <= NonFOutNE.Extent(); i++)
851     {
852       const TopoDS_Shape& CE = NonFOutNE.FindKey(i);
853       const TopoDS_Shape& V = NonFOutNE.FindFromIndex(i);
854       if (AllEdges.Contains(CE))
855         OutNE->Add(CE, V);
856     }
857   }
858
859   //map all sub-shapes from the original InSh to modified shapes  
860   if (OInSH2MSH)
861   {
862     TopTools_IndexedMapOfShape allSh;
863     TopExp::MapShapes(InSh, allSh);
864     for(int i = 1; i <= allSh.Extent(); i++ )
865     {
866       const TopoDS_Shape& or_sh = allSh(i); 
867       const TopTools_ListOfShape& ls = anAlgo.Modified(or_sh);
868       OInSH2MSH->Add(or_sh, ls);
869     }
870   }
871
872   return 0;
873 }