Salome HOME
Changes for bug 0020681.
[modules/smesh.git] / src / StdMeshers / StdMeshers_Regular_1D.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : StdMeshers_Regular_1D.cxx
24 //           Moved here from SMESH_Regular_1D.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27
28 #include "StdMeshers_Regular_1D.hxx"
29 #include "StdMeshers_Distribution.hxx"
30
31 #include "StdMeshers_Arithmetic1D.hxx"
32 #include "StdMeshers_AutomaticLength.hxx"
33 #include "StdMeshers_Deflection1D.hxx"
34 #include "StdMeshers_LocalLength.hxx"
35 #include "StdMeshers_MaxLength.hxx"
36 #include "StdMeshers_NumberOfSegments.hxx"
37 #include "StdMeshers_Propagation.hxx"
38 #include "StdMeshers_SegmentLengthAroundVertex.hxx"
39 #include "StdMeshers_StartEndLength.hxx"
40
41 #include "SMESH_Gen.hxx"
42 #include "SMESH_Mesh.hxx"
43 #include "SMESH_HypoFilter.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "SMESH_Comment.hxx"
47
48 #include "SMDS_MeshElement.hxx"
49 #include "SMDS_MeshNode.hxx"
50
51 #include "Utils_SALOME_Exception.hxx"
52 #include "utilities.h"
53
54 #include <BRepAdaptor_Curve.hxx>
55 #include <BRep_Tool.hxx>
56 #include <GCPnts_AbscissaPoint.hxx>
57 #include <GCPnts_UniformAbscissa.hxx>
58 #include <GCPnts_UniformDeflection.hxx>
59 #include <Precision.hxx>
60 #include <TopExp.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopoDS.hxx>
63 #include <TopoDS_Edge.hxx>
64
65 #include <string>
66 #include <limits>
67
68 using namespace std;
69
70 //=============================================================================
71 /*!
72  *  
73  */
74 //=============================================================================
75
76 StdMeshers_Regular_1D::StdMeshers_Regular_1D(int hypId, int studyId,
77         SMESH_Gen * gen):SMESH_1D_Algo(hypId, studyId, gen)
78 {
79         MESSAGE("StdMeshers_Regular_1D::StdMeshers_Regular_1D");
80         _name = "Regular_1D";
81         _shapeType = (1 << TopAbs_EDGE);
82         _fpHyp = 0;
83
84         _compatibleHypothesis.push_back("LocalLength");
85         _compatibleHypothesis.push_back("MaxLength");
86         _compatibleHypothesis.push_back("NumberOfSegments");
87         _compatibleHypothesis.push_back("StartEndLength");
88         _compatibleHypothesis.push_back("Deflection1D");
89         _compatibleHypothesis.push_back("Arithmetic1D");
90         _compatibleHypothesis.push_back("FixedPoints1D");
91         _compatibleHypothesis.push_back("AutomaticLength");
92
93         _compatibleHypothesis.push_back("QuadraticMesh"); // auxiliary !!!
94         _compatibleHypothesis.push_back("Propagation"); // auxiliary !!!
95 }
96
97 //=============================================================================
98 /*!
99  *  
100  */
101 //=============================================================================
102
103 StdMeshers_Regular_1D::~StdMeshers_Regular_1D()
104 {
105 }
106
107 //=============================================================================
108 /*!
109  *  
110  */
111 //=============================================================================
112
113 bool StdMeshers_Regular_1D::CheckHypothesis
114                          (SMESH_Mesh&                          aMesh,
115                           const TopoDS_Shape&                  aShape,
116                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
117 {
118   _hypType = NONE;
119   _quadraticMesh = false;
120
121   const bool ignoreAuxiliaryHyps = false;
122   const list <const SMESHDS_Hypothesis * > & hyps =
123     GetUsedHypothesis(aMesh, aShape, ignoreAuxiliaryHyps);
124
125   // find non-auxiliary hypothesis
126   const SMESHDS_Hypothesis *theHyp = 0;
127   list <const SMESHDS_Hypothesis * >::const_iterator h = hyps.begin();
128   for ( ; h != hyps.end(); ++h ) {
129     if ( static_cast<const SMESH_Hypothesis*>(*h)->IsAuxiliary() ) {
130       if ( strcmp( "QuadraticMesh", (*h)->GetName() ) == 0 )
131         _quadraticMesh = true;
132     }
133     else {
134       if ( !theHyp )
135         theHyp = *h; // use only the first non-auxiliary hypothesis
136     }
137   }
138
139   if ( !theHyp )
140   {
141     aStatus = SMESH_Hypothesis::HYP_MISSING;
142     return false;  // can't work without a hypothesis
143   }
144
145   string hypName = theHyp->GetName();
146
147   if (hypName == "LocalLength")
148   {
149     const StdMeshers_LocalLength * hyp =
150       dynamic_cast <const StdMeshers_LocalLength * >(theHyp);
151     ASSERT(hyp);
152     _value[ BEG_LENGTH_IND ] = hyp->GetLength();
153     _value[ PRECISION_IND ] = hyp->GetPrecision();
154     ASSERT( _value[ BEG_LENGTH_IND ] > 0 );
155     _hypType = LOCAL_LENGTH;
156     aStatus = SMESH_Hypothesis::HYP_OK;
157   }
158
159   else if (hypName == "MaxLength")
160   {
161     const StdMeshers_MaxLength * hyp =
162       dynamic_cast <const StdMeshers_MaxLength * >(theHyp);
163     ASSERT(hyp);
164     _value[ BEG_LENGTH_IND ] = hyp->GetLength();
165     if ( hyp->GetUsePreestimatedLength() ) {
166       if ( int nbSeg = aMesh.GetGen()->GetBoundaryBoxSegmentation() )
167         _value[ BEG_LENGTH_IND ] = aMesh.GetShapeDiagonalSize() / nbSeg;
168     }
169     ASSERT( _value[ BEG_LENGTH_IND ] > 0 );
170     _hypType = MAX_LENGTH;
171     aStatus = SMESH_Hypothesis::HYP_OK;
172   }
173
174   else if (hypName == "NumberOfSegments")
175   {
176     const StdMeshers_NumberOfSegments * hyp =
177       dynamic_cast <const StdMeshers_NumberOfSegments * >(theHyp);
178     ASSERT(hyp);
179     _ivalue[ NB_SEGMENTS_IND  ] = hyp->GetNumberOfSegments();
180     ASSERT( _ivalue[ NB_SEGMENTS_IND ] > 0 );
181     _ivalue[ DISTR_TYPE_IND ] = (int) hyp->GetDistrType();
182     switch (_ivalue[ DISTR_TYPE_IND ])
183     {
184     case StdMeshers_NumberOfSegments::DT_Scale:
185       _value[ SCALE_FACTOR_IND ] = hyp->GetScaleFactor();
186       _revEdgesIDs = hyp->GetReversedEdges();
187       break;
188     case StdMeshers_NumberOfSegments::DT_TabFunc:
189       _vvalue[ TAB_FUNC_IND ] = hyp->GetTableFunction();
190       _revEdgesIDs = hyp->GetReversedEdges();
191       break;
192     case StdMeshers_NumberOfSegments::DT_ExprFunc:
193       _svalue[ EXPR_FUNC_IND ] = hyp->GetExpressionFunction();
194       _revEdgesIDs = hyp->GetReversedEdges();
195       break;
196     case StdMeshers_NumberOfSegments::DT_Regular:
197       break;
198     default:
199       ASSERT(0);
200       break;
201     }
202     if (_ivalue[ DISTR_TYPE_IND ] == StdMeshers_NumberOfSegments::DT_TabFunc ||
203         _ivalue[ DISTR_TYPE_IND ] == StdMeshers_NumberOfSegments::DT_ExprFunc)
204         _ivalue[ CONV_MODE_IND ] = hyp->ConversionMode();
205     _hypType = NB_SEGMENTS;
206     aStatus = SMESH_Hypothesis::HYP_OK;
207   }
208
209   else if (hypName == "Arithmetic1D")
210   {
211     const StdMeshers_Arithmetic1D * hyp =
212       dynamic_cast <const StdMeshers_Arithmetic1D * >(theHyp);
213     ASSERT(hyp);
214     _value[ BEG_LENGTH_IND ] = hyp->GetLength( true );
215     _value[ END_LENGTH_IND ] = hyp->GetLength( false );
216     ASSERT( _value[ BEG_LENGTH_IND ] > 0 && _value[ END_LENGTH_IND ] > 0 );
217     _hypType = ARITHMETIC_1D;
218
219     _revEdgesIDs = hyp->GetReversedEdges();
220
221     aStatus = SMESH_Hypothesis::HYP_OK;
222   }
223
224   else if (hypName == "FixedPoints1D") {
225     _fpHyp = dynamic_cast <const StdMeshers_FixedPoints1D*>(theHyp);
226     ASSERT(_fpHyp);
227     _hypType = FIXED_POINTS_1D;
228
229     _revEdgesIDs = _fpHyp->GetReversedEdges();
230
231     aStatus = SMESH_Hypothesis::HYP_OK;
232   }
233
234   else if (hypName == "StartEndLength")
235   {
236     const StdMeshers_StartEndLength * hyp =
237       dynamic_cast <const StdMeshers_StartEndLength * >(theHyp);
238     ASSERT(hyp);
239     _value[ BEG_LENGTH_IND ] = hyp->GetLength( true );
240     _value[ END_LENGTH_IND ] = hyp->GetLength( false );
241     ASSERT( _value[ BEG_LENGTH_IND ] > 0 && _value[ END_LENGTH_IND ] > 0 );
242     _hypType = BEG_END_LENGTH;
243
244     _revEdgesIDs = hyp->GetReversedEdges();
245
246     aStatus = SMESH_Hypothesis::HYP_OK;
247   }
248
249   else if (hypName == "Deflection1D")
250   {
251     const StdMeshers_Deflection1D * hyp =
252       dynamic_cast <const StdMeshers_Deflection1D * >(theHyp);
253     ASSERT(hyp);
254     _value[ DEFLECTION_IND ] = hyp->GetDeflection();
255     ASSERT( _value[ DEFLECTION_IND ] > 0 );
256     _hypType = DEFLECTION;
257     aStatus = SMESH_Hypothesis::HYP_OK;
258   }
259
260   else if (hypName == "AutomaticLength")
261   {
262     StdMeshers_AutomaticLength * hyp = const_cast<StdMeshers_AutomaticLength *>
263       (dynamic_cast <const StdMeshers_AutomaticLength * >(theHyp));
264     ASSERT(hyp);
265     _value[ BEG_LENGTH_IND ] = _value[ END_LENGTH_IND ] = hyp->GetLength( &aMesh, aShape );
266 //     _value[ BEG_LENGTH_IND ] = hyp->GetLength( &aMesh, aShape );
267 //     _value[ END_LENGTH_IND ] = Precision::Confusion(); // ?? or set to zero?
268     ASSERT( _value[ BEG_LENGTH_IND ] > 0 );
269     _hypType = MAX_LENGTH;
270     aStatus = SMESH_Hypothesis::HYP_OK;
271   }
272   else
273     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
274
275   return ( _hypType != NONE );
276 }
277
278 static bool computeParamByFunc(Adaptor3d_Curve& C3d, double first, double last,
279                                double length, bool theReverse,
280                                int nbSeg, Function& func,
281                                list<double>& theParams)
282 {
283   // never do this way
284   //OSD::SetSignal( true );
285
286   if (nbSeg <= 0)
287     return false;
288
289   MESSAGE( "computeParamByFunc" );
290
291   int nbPnt = 1 + nbSeg;
292   vector<double> x(nbPnt, 0.);
293
294   if (!buildDistribution(func, 0.0, 1.0, nbSeg, x, 1E-4))
295      return false;
296
297   MESSAGE( "Points:\n" );
298   char buf[1024];
299   for ( int i=0; i<=nbSeg; i++ )
300   {
301     sprintf(  buf, "%f\n", float(x[i] ) );
302     MESSAGE( buf );
303   }
304
305
306
307   // apply parameters in range [0,1] to the space of the curve
308   double prevU = first;
309   double sign = 1.;
310   if (theReverse)
311   {
312     prevU = last;
313     sign = -1.;
314   }
315   for( int i = 1; i < nbSeg; i++ )
316   {
317     double curvLength = length * (x[i] - x[i-1]) * sign;
318     GCPnts_AbscissaPoint Discret( C3d, curvLength, prevU );
319     if ( !Discret.IsDone() )
320       return false;
321     double U = Discret.Parameter();
322     if ( U > first && U < last )
323       theParams.push_back( U );
324     else
325       return false;
326     prevU = U;
327   }
328   return true;
329 }
330
331
332 //================================================================================
333 /*!
334  * \brief adjust internal node parameters so that the last segment length == an
335   * \param a1 - the first segment length
336   * \param an - the last segment length
337   * \param U1 - the first edge parameter
338   * \param Un - the last edge parameter
339   * \param length - the edge length
340   * \param C3d - the edge curve
341   * \param theParams - internal node parameters to adjust
342   * \param adjustNeighbors2an - to adjust length of segments next to the last one
343   *  and not to remove parameters
344  */
345 //================================================================================
346
347 static void compensateError(double a1, double an,
348                             double U1, double Un,
349                             double            length,
350                             Adaptor3d_Curve&  C3d,
351                             list<double> &    theParams,
352                             bool              adjustNeighbors2an = false)
353 {
354   int i, nPar = theParams.size();
355   if ( a1 + an < length && nPar > 1 )
356   {
357     bool reverse = ( U1 > Un );
358     GCPnts_AbscissaPoint Discret(C3d, reverse ? an : -an, Un);
359     if ( !Discret.IsDone() )
360       return;
361     double Utgt = Discret.Parameter(); // target value of the last parameter
362     list<double>::reverse_iterator itU = theParams.rbegin();
363     double Ul = *itU++; // real value of the last parameter
364     double dUn = Utgt - Ul; // parametric error of <an>
365     if ( Abs(dUn) <= Precision::Confusion() )
366       return;
367     double dU = Abs( Ul - *itU ); // parametric length of the last but one segment
368     if ( adjustNeighbors2an || Abs(dUn) < 0.5 * dU ) { // last segment is a bit shorter than it should
369       // move the last parameter to the edge beginning
370     }
371     else {  // last segment is much shorter than it should -> remove the last param and
372       theParams.pop_back(); nPar--; // move the rest points toward the edge end
373       dUn = Utgt - theParams.back();
374     }
375
376     double q  = dUn / ( nPar - 1 );
377     if ( !adjustNeighbors2an ) {
378       for ( itU = theParams.rbegin(), i = 1; i < nPar; itU++, i++ ) {
379         (*itU) += dUn;
380         dUn -= q;
381       }
382     }
383     else {
384       theParams.back() += dUn;
385       double sign = reverse ? -1 : 1;
386       double prevU = theParams.back();
387       itU = theParams.rbegin();
388       for ( ++itU, i = 2; i < nPar; ++itU, i++ ) {
389         double newU = *itU + dUn;
390         if ( newU*sign < prevU*sign ) {
391           prevU = *itU = newU;
392           dUn -= q;
393         }
394         else { // set U between prevU and next valid param
395           list<double>::reverse_iterator itU2 = itU;
396           ++itU2;
397           int nb = 2;
398           while ( (*itU2)*sign > prevU*sign ) {
399             ++itU2; ++nb;
400           }
401           dU = ( *itU2 - prevU ) / nb;
402           while ( itU != itU2 ) {
403             *itU += dU; ++itU;
404           }
405           break;
406         }
407       }
408     }
409   }
410 }
411
412 //================================================================================
413 /*!
414  * \brief Class used to clean mesh on edges when 0D hyp modified.
415  * Common approach doesn't work when 0D algo is missing because the 0D hyp is
416  * considered as not participating in computation whereas it is used by 1D algo.
417  */
418 //================================================================================
419
420 // struct VertexEventListener : public SMESH_subMeshEventListener
421 // {
422 //   VertexEventListener():SMESH_subMeshEventListener(0) // won't be deleted by submesh
423 //   {}
424 //   /*!
425 //    * \brief Clean mesh on edges
426 //    * \param event - algo_event or compute_event itself (of SMESH_subMesh)
427 //    * \param eventType - ALGO_EVENT or COMPUTE_EVENT (of SMESH_subMesh)
428 //    * \param subMesh - the submesh where the event occures
429 //    */
430 //   void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
431 //                     EventListenerData*, const SMESH_Hypothesis*)
432 //   {
433 //     if ( eventType == SMESH_subMesh::ALGO_EVENT) // all algo events
434 //     {
435 //       subMesh->ComputeStateEngine( SMESH_subMesh::MODIF_ALGO_STATE );
436 //     }
437 //   }
438 // }; // struct VertexEventListener
439
440 //=============================================================================
441 /*!
442  * \brief Sets event listener to vertex submeshes
443  * \param subMesh - submesh where algo is set
444  *
445  * This method is called when a submesh gets HYP_OK algo_state.
446  * After being set, event listener is notified on each event of a submesh.
447  */
448 //=============================================================================
449
450 void StdMeshers_Regular_1D::SetEventListener(SMESH_subMesh* subMesh)
451 {
452   StdMeshers_Propagation::SetPropagationMgr( subMesh );
453 }
454
455 //=============================================================================
456 /*!
457  * \brief Do nothing
458  * \param subMesh - restored submesh
459  *
460  * This method is called only if a submesh has HYP_OK algo_state.
461  */
462 //=============================================================================
463
464 void StdMeshers_Regular_1D::SubmeshRestored(SMESH_subMesh* subMesh)
465 {
466 }
467
468 //=============================================================================
469 /*!
470  * \brief Return StdMeshers_SegmentLengthAroundVertex assigned to vertex
471  */
472 //=============================================================================
473
474 const StdMeshers_SegmentLengthAroundVertex*
475 StdMeshers_Regular_1D::getVertexHyp(SMESH_Mesh &          theMesh,
476                                     const TopoDS_Vertex & theV)
477 {
478   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName("SegmentAroundVertex_0D"));
479   if ( const SMESH_Hypothesis * h = theMesh.GetHypothesis( theV, filter, true ))
480   {
481     SMESH_Algo* algo = const_cast< SMESH_Algo* >( static_cast< const SMESH_Algo* > ( h ));
482     const list <const SMESHDS_Hypothesis *> & hypList = algo->GetUsedHypothesis( theMesh, theV, 0 );
483     if ( !hypList.empty() && string("SegmentLengthAroundVertex") == hypList.front()->GetName() )
484       return static_cast<const StdMeshers_SegmentLengthAroundVertex*>( hypList.front() );
485   }
486   return 0;
487 }
488
489 //================================================================================
490 /*!
491  * \brief Tune parameters to fit "SegmentLengthAroundVertex" hypothesis
492   * \param theC3d - wire curve
493   * \param theLength - curve length
494   * \param theParameters - internal nodes parameters to modify
495   * \param theVf - 1st vertex
496   * \param theVl - 2nd vertex
497  */
498 //================================================================================
499
500 void StdMeshers_Regular_1D::redistributeNearVertices (SMESH_Mesh &          theMesh,
501                                                       Adaptor3d_Curve &     theC3d,
502                                                       double                theLength,
503                                                       std::list< double > & theParameters,
504                                                       const TopoDS_Vertex & theVf,
505                                                       const TopoDS_Vertex & theVl)
506 {
507   double f = theC3d.FirstParameter(), l = theC3d.LastParameter();
508   int nPar = theParameters.size();
509   for ( int isEnd1 = 0; isEnd1 < 2; ++isEnd1 )
510   {
511     const TopoDS_Vertex & V = isEnd1 ? theVf : theVl;
512     const StdMeshers_SegmentLengthAroundVertex* hyp = getVertexHyp (theMesh, V );
513     if ( hyp ) {
514       double vertexLength = hyp->GetLength();
515       if ( vertexLength > theLength / 2.0 )
516         continue;
517       if ( isEnd1 ) { // to have a segment of interest at end of theParameters
518         theParameters.reverse();
519         std::swap( f, l );
520       }
521       if ( _hypType == NB_SEGMENTS )
522       {
523         compensateError(0, vertexLength, f, l, theLength, theC3d, theParameters, true );
524       }
525       else if ( nPar <= 3 )
526       {
527         if ( !isEnd1 )
528           vertexLength = -vertexLength;
529         GCPnts_AbscissaPoint Discret(theC3d, vertexLength, l);
530         if ( Discret.IsDone() ) {
531           if ( nPar == 0 )
532             theParameters.push_back( Discret.Parameter());
533           else {
534             double L = GCPnts_AbscissaPoint::Length( theC3d, theParameters.back(), l);
535             if ( vertexLength < L / 2.0 )
536               theParameters.push_back( Discret.Parameter());
537             else
538               compensateError(0, vertexLength, f, l, theLength, theC3d, theParameters, true );
539           }
540         }
541       }
542       else
543       {
544         // recompute params between the last segment and a middle one.
545         // find size of a middle segment
546         int nHalf = ( nPar-1 ) / 2;
547         list< double >::reverse_iterator itU = theParameters.rbegin();
548         std::advance( itU, nHalf );
549         double Um = *itU++;
550         double Lm = GCPnts_AbscissaPoint::Length( theC3d, Um, *itU);
551         double L = GCPnts_AbscissaPoint::Length( theC3d, *itU, l);
552         StdMeshers_Regular_1D algo( *this );
553         algo._hypType = BEG_END_LENGTH;
554         algo._value[ BEG_LENGTH_IND ] = Lm;
555         algo._value[ END_LENGTH_IND ] = vertexLength;
556         double from = *itU, to = l;
557         if ( isEnd1 ) {
558           std::swap( from, to );
559           std::swap( algo._value[ BEG_LENGTH_IND ], algo._value[ END_LENGTH_IND ]);
560         }
561         list<double> params;
562         if ( algo.computeInternalParameters( theMesh, theC3d, L, from, to, params, false ))
563         {
564           if ( isEnd1 ) params.reverse();
565           while ( 1 + nHalf-- )
566             theParameters.pop_back();
567           theParameters.splice( theParameters.end(), params );
568         }
569         else
570         {
571           compensateError(0, vertexLength, f, l, theLength, theC3d, theParameters, true );
572         }
573       }
574       if ( isEnd1 )
575         theParameters.reverse();
576     }
577   }
578 }
579
580 //=============================================================================
581 /*!
582  *  
583  */
584 //=============================================================================
585 bool StdMeshers_Regular_1D::computeInternalParameters(SMESH_Mesh &     theMesh,
586                                                       Adaptor3d_Curve& theC3d,
587                                                       double           theLength,
588                                                       double           theFirstU,
589                                                       double           theLastU,
590                                                       list<double> &   theParams,
591                                                       const bool       theReverse,
592                                                       bool             theConsiderPropagation)
593 {
594   theParams.clear();
595
596   double f = theFirstU, l = theLastU;
597
598   switch( _hypType )
599   {
600   case LOCAL_LENGTH:
601   case MAX_LENGTH:
602   case NB_SEGMENTS: {
603
604     double eltSize = 1;
605     if ( _hypType == MAX_LENGTH )
606     {
607       double nbseg = ceil(theLength / _value[ BEG_LENGTH_IND ]); // integer sup
608       if (nbseg <= 0)
609         nbseg = 1;                        // degenerated edge
610       eltSize = theLength / nbseg;
611     }
612     else if ( _hypType == LOCAL_LENGTH )
613     {
614       // Local Length hypothesis
615       double nbseg = ceil(theLength / _value[ BEG_LENGTH_IND ]); // integer sup
616
617       // NPAL17873:
618       bool isFound = false;
619       if (theConsiderPropagation && !_mainEdge.IsNull()) // propagated from some other edge
620       {
621         // Advanced processing to assure equal number of segments in case of Propagation
622         SMESH_subMesh* sm = theMesh.GetSubMeshContaining(_mainEdge);
623         if (sm) {
624           bool computed = sm->IsMeshComputed();
625           if (!computed) {
626             if (sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE) {
627               sm->ComputeStateEngine(SMESH_subMesh::COMPUTE);
628               computed = sm->IsMeshComputed();
629             }
630           }
631           if (computed) {
632             SMESHDS_SubMesh* smds = sm->GetSubMeshDS();
633             int nb_segments = smds->NbElements();
634             if (nbseg - 1 <= nb_segments && nb_segments <= nbseg + 1) {
635               isFound = true;
636               nbseg = nb_segments;
637             }
638           }
639         }
640       }
641       if (!isFound) // not found by meshed edge in the propagation chain, use precision
642       {
643         double aPrecision = _value[ PRECISION_IND ];
644         double nbseg_prec = ceil((theLength / _value[ BEG_LENGTH_IND ]) - aPrecision);
645         if (nbseg_prec == (nbseg - 1)) nbseg--;
646       }
647
648       if (nbseg <= 0)
649         nbseg = 1;                        // degenerated edge
650       eltSize = theLength / nbseg;
651     }
652     else
653     {
654       // Number Of Segments hypothesis
655       int NbSegm = _ivalue[ NB_SEGMENTS_IND ];
656       if ( NbSegm < 1 )  return false;
657       if ( NbSegm == 1 ) return true;
658
659       switch (_ivalue[ DISTR_TYPE_IND ])
660       {
661       case StdMeshers_NumberOfSegments::DT_Scale:
662         {
663           double scale = _value[ SCALE_FACTOR_IND ];
664
665           if (fabs(scale - 1.0) < Precision::Confusion()) {
666             // special case to avoid division by zero
667             for (int i = 1; i < NbSegm; i++) {
668               double param = f + (l - f) * i / NbSegm;
669               theParams.push_back( param );
670             }
671           } else {
672             // general case of scale distribution
673             if ( theReverse )
674               scale = 1.0 / scale;
675
676             double alpha = pow(scale, 1.0 / (NbSegm - 1));
677             double factor = (l - f) / (1.0 - pow(alpha, NbSegm));
678
679             for (int i = 1; i < NbSegm; i++) {
680               double param = f + factor * (1.0 - pow(alpha, i));
681               theParams.push_back( param );
682             }
683           }
684           return true;
685         }
686         break;
687       case StdMeshers_NumberOfSegments::DT_TabFunc:
688         {
689           FunctionTable func(_vvalue[ TAB_FUNC_IND ], _ivalue[ CONV_MODE_IND ]);
690           return computeParamByFunc(theC3d, f, l, theLength, theReverse,
691                                     _ivalue[ NB_SEGMENTS_IND ], func,
692                                     theParams);
693         }
694         break;
695       case StdMeshers_NumberOfSegments::DT_ExprFunc:
696         {
697           FunctionExpr func(_svalue[ EXPR_FUNC_IND ].c_str(), _ivalue[ CONV_MODE_IND ]);
698           return computeParamByFunc(theC3d, f, l, theLength, theReverse,
699                                     _ivalue[ NB_SEGMENTS_IND ], func,
700                                     theParams);
701         }
702         break;
703       case StdMeshers_NumberOfSegments::DT_Regular:
704         eltSize = theLength / _ivalue[ NB_SEGMENTS_IND ];
705         break;
706       default:
707         return false;
708       }
709     }
710     GCPnts_UniformAbscissa Discret(theC3d, eltSize, f, l);
711     if ( !Discret.IsDone() )
712       return error( "GCPnts_UniformAbscissa failed");
713
714     int NbPoints = Discret.NbPoints();
715     for ( int i = 2; i < NbPoints; i++ )
716     {
717       double param = Discret.Parameter(i);
718       theParams.push_back( param );
719     }
720     compensateError( eltSize, eltSize, f, l, theLength, theC3d, theParams ); // for PAL9899
721     return true;
722   }
723
724   case BEG_END_LENGTH: {
725
726     // geometric progression: SUM(n) = ( a1 - an * q ) / ( 1 - q ) = theLength
727
728     double a1 = _value[ BEG_LENGTH_IND ];
729     double an = _value[ END_LENGTH_IND ];
730     double q  = ( theLength - a1 ) / ( theLength - an );
731
732     double U1 = theReverse ? l : f;
733     double Un = theReverse ? f : l;
734     double param = U1;
735     double eltSize = theReverse ? -a1 : a1;
736     while ( 1 ) {
737       // computes a point on a curve <theC3d> at the distance <eltSize>
738       // from the point of parameter <param>.
739       GCPnts_AbscissaPoint Discret( theC3d, eltSize, param );
740       if ( !Discret.IsDone() ) break;
741       param = Discret.Parameter();
742       if ( f < param && param < l )
743         theParams.push_back( param );
744       else
745         break;
746       eltSize *= q;
747     }
748     compensateError( a1, an, U1, Un, theLength, theC3d, theParams );
749     if (theReverse) theParams.reverse(); // NPAL18025
750     return true;
751   }
752
753   case ARITHMETIC_1D: {
754
755     // arithmetic progression: SUM(n) = ( an - a1 + q ) * ( a1 + an ) / ( 2 * q ) = theLength
756
757     double a1 = _value[ BEG_LENGTH_IND ];
758     double an = _value[ END_LENGTH_IND ];
759
760     double  q = ( an - a1 ) / ( 2 *theLength/( a1 + an ) - 1 );
761     int n = int(fabs(q) > numeric_limits<double>::min() ? ( 1+( an-a1 )/q ) : ( 1+theLength/a1 ));
762
763     double U1 = theReverse ? l : f;
764     double Un = theReverse ? f : l;
765     double param = U1;
766     double eltSize = a1;
767     if ( theReverse ) {
768       eltSize = -eltSize;
769       q = -q;
770     }
771     while ( n-- > 0 && eltSize * ( Un - U1 ) > 0 ) {
772       // computes a point on a curve <theC3d> at the distance <eltSize>
773       // from the point of parameter <param>.
774       GCPnts_AbscissaPoint Discret( theC3d, eltSize, param );
775       if ( !Discret.IsDone() ) break;
776       param = Discret.Parameter();
777       if ( param > f && param < l )
778         theParams.push_back( param );
779       else
780         break;
781       eltSize += q;
782     }
783     compensateError( a1, an, U1, Un, theLength, theC3d, theParams );
784     if (theReverse) theParams.reverse(); // NPAL18025
785
786     return true;
787   }
788
789   case FIXED_POINTS_1D: {
790     const std::vector<double>& aPnts = _fpHyp->GetPoints();
791     const std::vector<int>& nbsegs = _fpHyp->GetNbSegments();
792     int i = 0;
793     TColStd_SequenceOfReal Params;
794     for(; i<aPnts.size(); i++) {
795       if( aPnts[i]<0.0001 || aPnts[i]>0.9999 ) continue;
796       int j=1;
797       bool IsExist = false;
798       for(; j<=Params.Length(); j++) {
799         if( fabs(aPnts[i]-Params.Value(j)) < 1e-4 ) {
800           IsExist = true;
801           break;
802         }
803         if( aPnts[i]<Params.Value(j) ) break;
804       }
805       if(!IsExist) Params.InsertBefore(j,aPnts[i]);
806     }
807     double par2, par1;
808     par1 = f;
809     double eltSize, segmentSize = 0.;
810     double currAbscissa = 0;
811     for(i=0; i<Params.Length(); i++) {
812       int nbseg = ( i > nbsegs.size()-1 ) ? nbsegs[0] : nbsegs[i];
813       segmentSize = Params.Value(i+1)*theLength - currAbscissa;
814       currAbscissa += segmentSize;
815       GCPnts_AbscissaPoint APnt(theC3d, segmentSize, par1);
816       if( !APnt.IsDone() )
817         return error( "GCPnts_AbscissaPoint failed");
818       par2 = APnt.Parameter();
819       eltSize = segmentSize/nbseg;
820       GCPnts_UniformAbscissa Discret(theC3d, eltSize, par1, par2);
821       if ( !Discret.IsDone() )
822         return error( "GCPnts_UniformAbscissa failed");
823       int NbPoints = Discret.NbPoints();
824       list<double> tmpParams;
825       for(int i=2; i<NbPoints; i++) {
826         double param = Discret.Parameter(i);
827         tmpParams.push_back( param );
828       }
829       compensateError( eltSize, eltSize, par1, par2, theLength, theC3d, tmpParams );
830       list<double>::iterator itP = tmpParams.begin();
831       for(; itP != tmpParams.end(); itP++) {
832         theParams.push_back( *(itP) );
833       }
834       theParams.push_back( par2 );
835
836       par1 = par2;
837     }
838     // add for last
839     int nbseg = ( nbsegs.size() > Params.Length() ) ? nbsegs[Params.Length()] : nbsegs[0];
840     segmentSize = theLength - segmentSize;
841     eltSize = segmentSize/nbseg;
842     GCPnts_UniformAbscissa Discret(theC3d, eltSize, par1, l);
843     if ( !Discret.IsDone() )
844       return error( "GCPnts_UniformAbscissa failed");
845     int NbPoints = Discret.NbPoints();
846     list<double> tmpParams;
847     for(int i=2; i<NbPoints; i++) {
848       double param = Discret.Parameter(i);
849       tmpParams.push_back( param );
850     }
851     compensateError(eltSize, eltSize, par1, l, segmentSize, theC3d, tmpParams);
852     list<double>::iterator itP = tmpParams.begin();
853     for(; itP != tmpParams.end(); itP++) {
854       theParams.push_back( *(itP) );
855     }
856
857     if (theReverse) {
858       theParams.reverse(); // NPAL18025
859     }
860     return true;
861   }
862
863   case DEFLECTION: {
864
865     GCPnts_UniformDeflection Discret(theC3d, _value[ DEFLECTION_IND ], f, l, true);
866     if ( !Discret.IsDone() )
867       return false;
868
869     int NbPoints = Discret.NbPoints();
870     for ( int i = 2; i < NbPoints; i++ )
871     {
872       double param = Discret.Parameter(i);
873       theParams.push_back( param );
874     }
875     return true;
876   }
877
878   default:;
879   }
880
881   return false;
882 }
883
884 //=============================================================================
885 /*!
886  *  
887  */
888 //=============================================================================
889
890 bool StdMeshers_Regular_1D::Compute(SMESH_Mesh & theMesh, const TopoDS_Shape & theShape)
891 {
892   if ( _hypType == NONE )
893     return false;
894
895   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
896
897   const TopoDS_Edge & EE = TopoDS::Edge(theShape);
898   TopoDS_Edge E = TopoDS::Edge(EE.Oriented(TopAbs_FORWARD));
899   int shapeID = meshDS->ShapeToIndex( E );
900
901   double f, l;
902   Handle(Geom_Curve) Curve = BRep_Tool::Curve(E, f, l);
903
904   TopoDS_Vertex VFirst, VLast;
905   TopExp::Vertices(E, VFirst, VLast);   // Vfirst corresponds to f and Vlast to l
906
907   ASSERT(!VFirst.IsNull());
908   ASSERT(!VLast.IsNull());
909   const SMDS_MeshNode * idFirst = SMESH_Algo::VertexNode( VFirst, meshDS );
910   const SMDS_MeshNode * idLast = SMESH_Algo::VertexNode( VLast, meshDS );
911   if (!idFirst || !idLast)
912     return error( COMPERR_BAD_INPUT_MESH, "No node on vertex");
913
914   if (!Curve.IsNull())
915   {
916     list< double > params;
917     bool reversed = false;
918     if ( theMesh.GetShapeToMesh().ShapeType() >= TopAbs_WIRE ) {
919       reversed = ( EE.Orientation() == TopAbs_REVERSED );
920     }
921     if ( !_mainEdge.IsNull() ) {
922       reversed = ( _mainEdge.Orientation() == TopAbs_REVERSED );
923     }
924     else if ( _revEdgesIDs.size() > 0 ) {
925       for ( int i = 0; i < _revEdgesIDs.size(); i++) {
926         if ( _revEdgesIDs[i] == shapeID ) {
927           reversed = !reversed;
928         }
929       }
930     }
931
932     BRepAdaptor_Curve C3d( E );
933     double length = EdgeLength( E );
934     if ( ! computeInternalParameters( theMesh, C3d, length, f, l, params, reversed, true )) {
935       return false;
936     }
937     redistributeNearVertices( theMesh, C3d, length, params, VFirst, VLast );
938
939     // edge extrema (indexes : 1 & NbPoints) already in SMDS (TopoDS_Vertex)
940     // only internal nodes receive an edge position with param on curve
941
942     const SMDS_MeshNode * idPrev = idFirst;
943     double parPrev = f;
944     double parLast = l;
945
946     /* NPAL18025
947     if (reversed) {
948       idPrev = idLast;
949       idLast = idFirst;
950       idFirst = idPrev;
951       parPrev = l;
952       parLast = f;
953     }
954     */
955
956     for (list<double>::iterator itU = params.begin(); itU != params.end(); itU++) {
957       double param = *itU;
958       gp_Pnt P = Curve->Value(param);
959
960       //Add the Node in the DataStructure
961       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
962       meshDS->SetNodeOnEdge(node, shapeID, param);
963
964       if(_quadraticMesh) {
965         // create medium node
966         double prm = ( parPrev + param )/2;
967         gp_Pnt PM = Curve->Value(prm);
968         SMDS_MeshNode * NM = meshDS->AddNode(PM.X(), PM.Y(), PM.Z());
969         meshDS->SetNodeOnEdge(NM, shapeID, prm);
970         SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, node, NM);
971         meshDS->SetMeshElementOnShape(edge, shapeID);
972       }
973       else {
974         SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, node);
975         meshDS->SetMeshElementOnShape(edge, shapeID);
976       }
977
978       idPrev = node;
979       parPrev = param;
980     }
981     if(_quadraticMesh) {
982       double prm = ( parPrev + parLast )/2;
983       gp_Pnt PM = Curve->Value(prm);
984       SMDS_MeshNode * NM = meshDS->AddNode(PM.X(), PM.Y(), PM.Z());
985       meshDS->SetNodeOnEdge(NM, shapeID, prm);
986       SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, idLast, NM);
987       meshDS->SetMeshElementOnShape(edge, shapeID);
988     }
989     else {
990       SMDS_MeshEdge* edge = meshDS->AddEdge(idPrev, idLast);
991       meshDS->SetMeshElementOnShape(edge, shapeID);
992     }
993   }
994   else
995   {
996     //MESSAGE("************* Degenerated edge! *****************");
997
998     // Edge is a degenerated Edge : We put n = 5 points on the edge.
999     const int NbPoints = 5;
1000     BRep_Tool::Range( E, f, l ); // PAL15185
1001     double du = (l - f) / (NbPoints - 1);
1002
1003     gp_Pnt P = BRep_Tool::Pnt(VFirst);
1004
1005     const SMDS_MeshNode * idPrev = idFirst;
1006     for (int i = 2; i < NbPoints; i++) {
1007       double param = f + (i - 1) * du;
1008       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
1009       if(_quadraticMesh) {
1010         // create medium node
1011         double prm = param - du/2.;
1012         SMDS_MeshNode * NM = meshDS->AddNode(P.X(), P.Y(), P.Z());
1013         meshDS->SetNodeOnEdge(NM, shapeID, prm);
1014         SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, node, NM);
1015         meshDS->SetMeshElementOnShape(edge, shapeID);
1016       }
1017       else {
1018         SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, node);
1019         meshDS->SetMeshElementOnShape(edge, shapeID);
1020       }
1021       meshDS->SetNodeOnEdge(node, shapeID, param);
1022       idPrev = node;
1023     }
1024     if(_quadraticMesh) {
1025       // create medium node
1026       double prm = l - du/2.;
1027       SMDS_MeshNode * NM = meshDS->AddNode(P.X(), P.Y(), P.Z());
1028       meshDS->SetNodeOnEdge(NM, shapeID, prm);
1029       SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, idLast, NM);
1030       meshDS->SetMeshElementOnShape(edge, shapeID);
1031     }
1032     else {
1033       SMDS_MeshEdge * edge = meshDS->AddEdge(idPrev, idLast);
1034       meshDS->SetMeshElementOnShape(edge, shapeID);
1035     }
1036   }
1037   return true;
1038 }
1039
1040
1041 //=============================================================================
1042 /*!
1043  *  
1044  */
1045 //=============================================================================
1046
1047 bool StdMeshers_Regular_1D::Evaluate(SMESH_Mesh & theMesh,
1048                                      const TopoDS_Shape & theShape,
1049                                      MapShapeNbElems& aResMap)
1050 {
1051   if ( _hypType == NONE )
1052     return false;
1053
1054   //SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1055
1056   const TopoDS_Edge & EE = TopoDS::Edge(theShape);
1057   TopoDS_Edge E = TopoDS::Edge(EE.Oriented(TopAbs_FORWARD));
1058   //  int shapeID = meshDS->ShapeToIndex( E );
1059
1060   double f, l;
1061   Handle(Geom_Curve) Curve = BRep_Tool::Curve(E, f, l);
1062
1063   TopoDS_Vertex VFirst, VLast;
1064   TopExp::Vertices(E, VFirst, VLast);   // Vfirst corresponds to f and Vlast to l
1065
1066   ASSERT(!VFirst.IsNull());
1067   ASSERT(!VLast.IsNull());
1068
1069   std::vector<int> aVec(SMDSEntity_Last,0);
1070
1071   if (!Curve.IsNull()) {
1072     list< double > params;
1073
1074     BRepAdaptor_Curve C3d( E );
1075     double length = EdgeLength( E );
1076     if ( ! computeInternalParameters( theMesh, C3d, length, f, l, params, false, true )) {
1077       SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1078       aResMap.insert(std::make_pair(sm,aVec));
1079       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1080       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
1081       return false;
1082     }
1083     redistributeNearVertices( theMesh, C3d, length, params, VFirst, VLast );
1084
1085     if(_quadraticMesh) {
1086       aVec[SMDSEntity_Node] = 2*params.size() + 1;
1087       aVec[SMDSEntity_Quad_Edge] = params.size() + 1;
1088     }
1089     else {
1090       aVec[SMDSEntity_Node] = params.size();
1091       aVec[SMDSEntity_Edge] = params.size() + 1;
1092     }
1093     
1094   }
1095   else {
1096     //MESSAGE("************* Degenerated edge! *****************");
1097     // Edge is a degenerated Edge : We put n = 5 points on the edge.
1098     if(_quadraticMesh) {
1099       aVec[SMDSEntity_Node] = 11;
1100       aVec[SMDSEntity_Quad_Edge] = 6;
1101     }
1102     else {
1103       aVec[SMDSEntity_Node] = 5;
1104       aVec[SMDSEntity_Edge] = 6;
1105     }
1106   }
1107
1108   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1109   aResMap.insert(std::make_pair(sm,aVec));
1110
1111   return true;
1112 }
1113
1114
1115 //=============================================================================
1116 /*!
1117  *  See comments in SMESH_Algo.cxx
1118  */
1119 //=============================================================================
1120
1121 const list <const SMESHDS_Hypothesis *> &
1122 StdMeshers_Regular_1D::GetUsedHypothesis(SMESH_Mesh &         aMesh,
1123                                          const TopoDS_Shape & aShape,
1124                                          const bool           ignoreAuxiliary)
1125 {
1126   _usedHypList.clear();
1127   _mainEdge.Nullify();
1128
1129   SMESH_HypoFilter auxiliaryFilter, compatibleFilter;
1130   auxiliaryFilter.Init( SMESH_HypoFilter::IsAuxiliary() );
1131   const bool ignoreAux = true;
1132   InitCompatibleHypoFilter( compatibleFilter, ignoreAux );
1133
1134   // get non-auxiliary assigned to aShape
1135   int nbHyp = aMesh.GetHypotheses( aShape, compatibleFilter, _usedHypList, false );
1136
1137   if (nbHyp == 0 && aShape.ShapeType() == TopAbs_EDGE)
1138   {
1139     // Check, if propagated from some other edge
1140     _mainEdge = StdMeshers_Propagation::GetPropagationSource( aMesh, aShape );
1141     if ( !_mainEdge.IsNull() )
1142     {
1143       // Propagation of 1D hypothesis from <aMainEdge> on this edge;
1144       // get non-auxiliary assigned to _mainEdge
1145       nbHyp = aMesh.GetHypotheses( _mainEdge, compatibleFilter, _usedHypList, true );
1146     }
1147   }
1148
1149   if (nbHyp == 0) // nothing propagated nor assigned to aShape
1150   {
1151     SMESH_Algo::GetUsedHypothesis( aMesh, aShape, ignoreAuxiliary );
1152     nbHyp = _usedHypList.size();
1153   }
1154   else
1155   {
1156     // get auxiliary hyps from aShape
1157     aMesh.GetHypotheses( aShape, auxiliaryFilter, _usedHypList, true );
1158   }
1159   if ( nbHyp > 1 && ignoreAuxiliary )
1160     _usedHypList.clear(); //only one compatible non-auxiliary hypothesis allowed
1161
1162   return _usedHypList;
1163 }