Salome HOME
5c241ad8ad45e12d65882632ebbe623ec73688f1
[modules/hydro.git] / src / HYDROData / HYDROData_PolylineOperator.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_PolylineOperator.h>
20 #include <HYDROData_Document.h>
21 #include <HYDROData_TopoCurve.h>
22 #include <HYDROData_Object.h>
23
24 #ifndef LIGHT_MODE
25 #include <CurveCreator_Utils.hxx>
26 #endif
27
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRep_Builder.hxx>
30 #include <BRep_Tool.hxx>
31 #include <BRepBuilderAPI_MakeEdge2d.hxx>
32 #include <BRepBuilderAPI_MakeEdge.hxx>
33 #include <BRepBuilderAPI_MakeWire.hxx>
34 #include <Extrema_ExtCC.hxx>
35 #include <Extrema_ExtPC.hxx>
36 #include <GeomAPI_Interpolate.hxx>
37 #include <NCollection_Vector.hxx>
38 #include <Precision.hxx>
39 #include <ShapeAnalysis_TransferParametersProj.hxx>
40 #include <ShapeBuild_Edge.hxx>
41 #include <TColgp_Array1OfVec.hxx>
42 #include <TColgp_HArray1OfPnt.hxx>
43 #include <TColStd_HArray1OfBoolean.hxx>
44 #include <TopoDS.hxx>
45 #include <TopoDS_Edge.hxx>
46 #include <TopoDS_Wire.hxx>
47 #include <TopExp.hxx>
48 #include <TopExp_Explorer.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <QStringList>
51 #include <QColor>
52 #include <Geom_BSplineCurve.hxx>
53
54 #define _DEVDEBUG_
55 #include "HYDRO_trace.hxx"
56 #include <BRepTools.hxx>
57 #include <sstream>
58
59 template<class T> void append( std::vector<T>& theList, const std::vector<T>& theList2 )
60 {
61   int aSize = theList.size();
62   int aNewSize = aSize + theList2.size();
63
64   if( aSize==aNewSize )
65     return;
66
67   theList.resize( aNewSize );
68   for( int i=aSize, j=0; i<aNewSize; i++, j++ )
69     theList[i] = theList2[j];
70 }
71
72 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
73                                         const Handle( HYDROData_PolylineXY )& thePolyline,
74                                         const gp_Pnt2d& thePoint,
75                                         double theTolerance ) const
76 {
77   if (thePolyline.IsNull())
78   {
79     return false;
80   }
81
82   std::vector<gp_Pnt2d> aPointsList( 1 );
83   aPointsList[0] = thePoint;
84   std::vector<TopoDS_Wire> aCurves;
85   GetWires(thePolyline, aCurves);
86   bool isOK = true;
87   for( int i=0, n=aCurves.size(); i<n; i++ )
88   {
89     std::vector<TopoDS_Shape> aCurvesList;
90     Split( aCurves[i], thePoint, theTolerance, aCurvesList );
91     bool isLocalOK = CreatePolylines( theDoc, thePolyline, aCurvesList, true );
92     isOK = isOK && isLocalOK;
93   }
94   return isOK;
95 }
96
97 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
98               const Handle( HYDROData_PolylineXY )& thePolyline,
99               const Handle( HYDROData_PolylineXY )& theTool,
100               double theTolerance,
101               bool& theIsIntersected) const
102 {
103   if (thePolyline.IsNull() || theTool.IsNull())
104   {
105     return false;
106   }
107
108   HYDROData_SequenceOfObjects aSeq;
109   aSeq.Append( theTool );
110   return split( theDoc, thePolyline, aSeq, theTolerance, -1, theIsIntersected);
111 }
112
113 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
114                                         const HYDROData_SequenceOfObjects& thePolylines,
115                                         double theTolerance )
116 {
117   int f = thePolylines.Lower(), l = thePolylines.Upper();
118   for( int i=f; i<=l; i++ )
119   {
120     Handle( HYDROData_PolylineXY ) aPolyline = Handle( HYDROData_PolylineXY )::DownCast( thePolylines.Value( i ) );
121     bool isIntersected;
122     if( !split( theDoc, aPolyline, thePolylines, theTolerance, i, isIntersected) )
123       return false;
124   }
125   return true;
126 }
127
128 bool HYDROData_PolylineOperator::Merge( const Handle( HYDROData_Document )& theDoc,
129                                         const QString& theName,
130                                         const HYDROData_SequenceOfObjects& thePolylines,
131                                         bool isConnectByNewSegment,
132                                         double theTolerance )
133 {
134   Handle( HYDROData_PolylineXY ) aNewPolyline =
135     Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
136   int ins =0;
137
138   HYDROData_SequenceOfObjects::Iterator aPIt(thePolylines);
139
140   for (int ip=1; aPIt.More(); aPIt.Next(), ip++)
141   {
142     Handle(HYDROData_PolylineXY) aPolyline =
143       Handle(HYDROData_PolylineXY)::DownCast(aPIt.Value());
144     NCollection_Sequence<TCollection_AsciiString>           aSectNames;
145     NCollection_Sequence<HYDROData_PolylineXY::SectionType> aSectTypes;
146     NCollection_Sequence<bool>                              aSectClosures;
147     aPolyline->GetSections( aSectNames, aSectTypes, aSectClosures );
148
149     for ( int i = 1, n = aSectNames.Size(); i <= n; ++i )
150     {
151       const TCollection_AsciiString& aSectName = aSectNames.Value( i ) + "_" + ip;
152       const HYDROData_PolylineXY::SectionType& aSectType = aSectTypes.Value( i );
153       bool aSectClosure = aSectClosures.Value( i );
154       aNewPolyline->AddSection(aSectName, aSectType, aSectClosure);
155       HYDROData_PolylineXY::PointsList aPointsList = aPolyline->GetPoints(i-1, false);
156       aNewPolyline->SetPoints(ins++, aPointsList);
157     }
158   }
159   QString aName = theName;
160   if( aName.isEmpty() )
161     aName = "merged";
162   aNewPolyline->SetName(aName);
163   return true;
164 }
165
166 bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theDoc,
167                                         const Handle( HYDROData_PolylineXY )& thePolyline,
168                                         const HYDROData_SequenceOfObjects& theTools,
169                                         double theTolerance,
170                                         int theIgnoreIndex,
171                                         bool& theIsIntersected) const
172 {
173   theIsIntersected = false;
174
175   if (thePolyline.IsNull())
176   {
177     return false;
178   }
179
180   std::vector<TopoDS_Wire> aCurves;
181   GetWires(thePolyline, aCurves);
182   std::vector<TopoDS_Wire> aToolCurves;
183   for( int i=theTools.Lower(), n=theTools.Upper(); i<=n; i++ )
184     if( i!=theIgnoreIndex )
185     {
186       Handle( HYDROData_PolylineXY ) aToolPolyline = 
187         Handle( HYDROData_PolylineXY )::DownCast( theTools.Value( i ) );
188       if (!aToolPolyline.IsNull())
189       {
190         std::vector<TopoDS_Wire> aTCurves;
191         GetWires(aToolPolyline, aTCurves);
192         append( aToolCurves, aTCurves);
193       }
194     }
195
196   if (aToolCurves.empty())
197   {
198     return false;
199   }
200
201   const int aPSCount = aCurves.size();
202   const int aTSCount = aToolCurves.size();
203   std::vector<TopoDS_Shape> aResult;
204   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
205   {
206     HYDROData_TopoCurve aCurve;
207     DEBTRACE("Initialize curve " << aPSI);
208     if (!aCurve.Initialize(aCurves[aPSI]))
209     {
210       continue;
211     }
212
213     std::deque<std::list<double> > aParams;
214     for (int aTSI = 0; aTSI < aTSCount; ++aTSI)
215     {
216       aCurve.Intersect(aToolCurves[aTSI], aParams);
217     }
218
219     std::deque<HYDROData_TopoCurve> aSplitCurves;
220     theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
221     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
222       aSplitCurves.begin();
223     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
224       aSplitCurves.end();
225     for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
226     {
227       std::stringstream brepName;
228       brepName << "theSplitWire_";
229       brepName << iw;
230       brepName << ".brep";
231       BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );
232       aResult.push_back(aCIt->Wire());
233     }
234   }
235
236   CreatePolylines( theDoc, thePolyline, aResult, true );
237   //CreatePolylinesSplit( theDoc, thePolyline, aResult, true );
238   return true;
239 }
240
241 void HYDROData_PolylineOperator::GetWires(
242   const Handle( HYDROData_PolylineXY )& thePolyline,
243   std::vector<TopoDS_Wire>& theWires)
244 {
245   TopoDS_Shape aShape = thePolyline->GetShape();
246   if( aShape.ShapeType()==TopAbs_WIRE )
247   {
248     theWires.push_back( TopoDS::Wire( aShape ) );
249   }
250   else
251   {
252     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
253     for( ; anExp.More(); anExp.Next() )
254     {
255       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
256     }
257   }
258 }
259
260 void HYDROData_PolylineOperator::Split(
261   const TopoDS_Wire& theWire,
262   const gp_Pnt2d& thePoint,
263   double theTolerance,
264   std::vector<TopoDS_Shape>& theWires)
265 {
266   HYDROData_TopoCurve aCurve;
267   if (!aCurve.Initialize(theWire))
268   {
269     theWires.push_back(theWire);
270     return;
271   }
272
273   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
274   std::list<TopoDS_Edge>::const_iterator aEPos;
275   double aParam;
276   aCurve.Project(aP, aEPos, aParam);
277   HYDROData_TopoCurve aCurve1, aCurve2;
278   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
279   theWires.push_back(aCurve1.Wire());
280   if (!aCurve2.IsEmpty())
281   {
282     theWires.push_back(aCurve2.Wire());
283   }
284 }
285
286 //bool HYDROData_PolylineOperator::CreatePolylinesSplit(const Handle( HYDROData_Document )& theDoc,
287 //                                                      const Handle( HYDROData_PolylineXY )& thePolyline,
288 //                                                      const std::vector<TopoDS_Shape>& theShapes, bool isUseIndices)
289 //{
290 //
291 //  if (theDoc.IsNull())
292 //    return false;
293 //
294 //  int nbSections = thePolyline->NbSections();
295 //  const QString& theNamePrefix = thePolyline->GetName();
296 //  const QColor& theColor = thePolyline->GetWireColor();
297 //
298 //  int n = theShapes.size();
299 //  DEBTRACE("theShapes.size() "<< n);
300 //  int anIndex = 1;
301 //  for (int i = 0; i < n; i++)
302 //    {
303 //      Handle( HYDROData_PolylineXY ) aPolyline =
304 //      Handle( HYDROData_PolylineXY )::DownCast(theDoc->CreateObject(KIND_POLYLINEXY));
305 //      if (aPolyline.IsNull())
306 //        return false;
307 //
308 //      for (int isec = 0; isec < nbSections; isec++)
309 //        {
310 //          gp_XY p = gp_XY(0, 0);
311 //          //double d = thePolyline->GetMinDistance(isec, p);
312 //        }
313 //
314 //      if (isUseIndices)
315 //        {
316 //          QString aNewName = theNamePrefix + "_" + QString::number(anIndex);
317 //          while (!theDoc->FindObjectByName(aNewName).IsNull())  // the object with such a name is not found
318 //            {
319 //              anIndex++;
320 //              aNewName = theNamePrefix + "_" + QString::number(anIndex);
321 //            }
322 //          aPolyline->SetName(aNewName);
323 //        }
324 //      else
325 //        {
326 //          aPolyline->SetName(theNamePrefix);
327 //        }
328 //
329 //      if (theColor.isValid())
330 //        aPolyline->SetWireColor(theColor);
331 //    }
332 //  return true;
333 //
334 //}
335
336 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
337                                                   const Handle( HYDROData_PolylineXY )& theOldPolyline,
338                                                   const std::vector<TopoDS_Shape>& theShapes,
339                                                   bool isUseIndices )
340 {
341   if( theDoc.IsNull() )
342     return false;
343
344   if ( theOldPolyline.IsNull() )
345     return false;
346   const QString& theNamePrefix = theOldPolyline->GetName();
347   const QColor& theColor = theOldPolyline->GetWireColor();
348
349   int n = theShapes.size();
350   DEBTRACE("theShapes.size() "<< n);
351   int anIndex = 1;
352   for( int i=0; i<n; i++ )
353   {
354     Handle( HYDROData_PolylineXY ) aPolyline = 
355       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
356     if( aPolyline.IsNull() )
357       return false;
358
359     aPolyline->ImportShape(theShapes[i], false, theOldPolyline, false);
360     //aPolyline->SetShape( theShapes[i] );
361
362
363     if( isUseIndices )
364     {
365       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
366       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
367       {
368         anIndex++;
369         aNewName = theNamePrefix + "_" + QString::number( anIndex );
370       }
371       aPolyline->SetName( aNewName );
372     }
373     else
374     {
375       aPolyline->SetName( theNamePrefix );
376     }
377
378     if( theColor.isValid() )
379       aPolyline->SetWireColor( theColor );
380   }
381   return true;
382 }
383
384 double HYDROData_PolylineOperator::ReduceDeflection(
385   const double theDeflection,
386   HYDROData_TopoCurve& theCurve,
387   int& thePieceCount)
388 {
389   // Construct the approximating B-spline.
390   std::list<gp_XYZ> aPs;
391   if (!theCurve.ValuesInKnots(aPs))
392   {
393     return -1;
394   }
395
396   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
397   {
398     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
399     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
400     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
401     {
402       aPs2->SetValue(aPN, *aPIt);
403     }
404   }
405   Handle(Geom_BSplineCurve) aBSpline2;
406   const bool isClosed = theCurve.IsClosed();
407 #ifndef LIGHT_MODE
408   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
409 #endif
410   {
411     return -1;
412   }
413
414   // Calculate the piece deflections.
415   std::deque<double> aSqDefls;
416   double aMaxSqDefl = 0;
417   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
418   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
419   {
420     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
421     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
422     {
423       TopLoc_Location aLoc;
424       double aParams[2];
425       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
426         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
427       const int aKCount = aBSpline->NbKnots();
428       for (int aKN = 1; aKN < aKCount; ++aKN)
429       {
430         const double aParam =
431           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
432         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
433           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
434         const double aSqDefl = Abs(aBSpline->Value(aParam).
435           SquareDistance(aBSpline2->Value(aParam2)));
436         aSqDefls.push_back(aSqDefl);
437         if (aMaxSqDefl < aSqDefl)
438         {
439           aMaxSqDefl = aSqDefl;
440         }
441       }
442       aPrevKCount += aKCount - 1;
443     }
444   }
445
446   // Check whether the reducing is necessary.
447   const double aMaxDefl = Sqrt(aMaxSqDefl);
448   if (aMaxDefl <= theDeflection)
449   {
450     return aMaxDefl;
451   }
452
453   // Reduce the deflections.
454   const double aThresSqDefl =
455     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
456   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
457   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
458   thePieceCount = 0;
459   for (; aEIt != aLastEIt; ++aEIt)
460   {
461     TopLoc_Location aLoc;
462     double aParams[2];
463     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
464       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
465     Handle(Geom_BSplineCurve) aBSpline2 =
466       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
467     const int aKCount = aBSpline->NbKnots();
468     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
469     {
470       if (*aSqDIt > aThresSqDefl)
471       {
472         aBSpline2->InsertKnot(
473           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
474       }
475     }
476     TopoDS_Edge aEdge;
477     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
478     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
479     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
480     thePieceCount += aBSpline2->NbKnots() - 1;
481     *aEIt = aEdge;
482   }
483   return aMaxDefl;
484 }
485
486 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
487                                           const Handle(HYDROData_Object)& theObject )
488 {
489   if( theObject.IsNull() || theDocument.IsNull() )
490     return false;
491
492   QList<TopoDS_Shape> aBoundShapes;
493   QStringList aBoundNames;
494
495   theObject->GetBoundaries( aBoundShapes, aBoundNames );
496
497   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
498   {
499     TopoDS_Shape aShape = aBoundShapes[i];
500     if( aShape.IsNull() )
501       continue;
502
503     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
504
505     Handle( HYDROData_PolylineXY ) aPolyline = 
506       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
507     
508     if( aPolyline.IsNull() )
509       return false;
510
511     aPolyline->SetShape( aShape );
512
513     int anIndex = 0;
514     QString aName = aBoundName;
515     while( !theDocument->FindObjectByName( aName ).IsNull() )
516     {
517       anIndex++;
518       aName = aBoundName + "_" + QString::number( anIndex );
519     }
520     aPolyline->SetName( aName );
521   }
522
523   return true;
524 }