Salome HOME
Integration of run_mesher code
[modules/smesh.git] / src / StdMeshers / StdMeshers_Regular_1D.cxx
1 // Copyright (C) 2007-2022  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, or (at your option) any later version.
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
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
30 #include "SMDS_MeshElement.hxx"
31 #include "SMDS_MeshNode.hxx"
32 #include "SMESHDS_Mesh.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_Mesh.hxx"
37 #include "SMESH_subMesh.hxx"
38 #include "SMESH_subMeshEventListener.hxx"
39 #include "StdMeshers_Adaptive1D.hxx"
40 #include "StdMeshers_Arithmetic1D.hxx"
41 #include "StdMeshers_AutomaticLength.hxx"
42 #include "StdMeshers_Geometric1D.hxx"
43 #include "StdMeshers_Deflection1D.hxx"
44 #include "StdMeshers_Distribution.hxx"
45 #include "StdMeshers_FixedPoints1D.hxx"
46 #include "StdMeshers_LocalLength.hxx"
47 #include "StdMeshers_MaxLength.hxx"
48 #include "StdMeshers_NumberOfSegments.hxx"
49 #include "StdMeshers_Propagation.hxx"
50 #include "StdMeshers_SegmentLengthAroundVertex.hxx"
51 #include "StdMeshers_StartEndLength.hxx"
52
53 #include <Utils_SALOME_Exception.hxx>
54 #include <utilities.h>
55
56 #include <BRepAdaptor_Curve.hxx>
57 #include <BRep_Tool.hxx>
58 #include <GCPnts_AbscissaPoint.hxx>
59 #include <GCPnts_UniformAbscissa.hxx>
60 #include <GCPnts_UniformDeflection.hxx>
61 #include <Precision.hxx>
62 #include <TopExp.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <TopoDS.hxx>
65 #include <TopoDS_Edge.hxx>
66 #include <TopoDS_Vertex.hxx>
67
68 #include <string>
69 #include <limits>
70
71 using namespace std;
72 using namespace StdMeshers;
73
74 //=============================================================================
75 /*!
76  *
77  */
78 //=============================================================================
79
80 StdMeshers_Regular_1D::StdMeshers_Regular_1D(int         hypId,
81                                              SMESH_Gen * gen)
82   :SMESH_1D_Algo( hypId, gen )
83 {
84   _name = "Regular_1D";
85   _shapeType = (1 << TopAbs_EDGE);
86   _fpHyp = 0;
87
88   _compatibleHypothesis.push_back("LocalLength");
89   _compatibleHypothesis.push_back("MaxLength");
90   _compatibleHypothesis.push_back("NumberOfSegments");
91   _compatibleHypothesis.push_back("StartEndLength");
92   _compatibleHypothesis.push_back("Deflection1D");
93   _compatibleHypothesis.push_back("Arithmetic1D");
94   _compatibleHypothesis.push_back("GeometricProgression");
95   _compatibleHypothesis.push_back("FixedPoints1D");
96   _compatibleHypothesis.push_back("AutomaticLength");
97   _compatibleHypothesis.push_back("Adaptive1D");
98   // auxiliary:
99   _compatibleHypothesis.push_back("QuadraticMesh");
100   _compatibleHypothesis.push_back("Propagation");
101   _compatibleHypothesis.push_back("PropagOfDistribution");
102 }
103
104 //=============================================================================
105 /*!
106  *
107  */
108 //=============================================================================
109
110 StdMeshers_Regular_1D::~StdMeshers_Regular_1D()
111 {
112 }
113
114 //=============================================================================
115 /*!
116  *
117  */
118 //=============================================================================
119
120 bool StdMeshers_Regular_1D::CheckHypothesis( SMESH_Mesh&         aMesh,
121                                              const TopoDS_Shape& aShape,
122                                              Hypothesis_Status&  aStatus )
123 {
124   _hypType        = NONE;
125   _quadraticMesh  = false;
126   _onlyUnaryInput = true;
127
128   // check propagation in a redefined GetUsedHypothesis()
129   const list <const SMESHDS_Hypothesis * > hyps =
130     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliaryHyps=*/false);
131   const SMESH_HypoFilter & propagFilter = StdMeshers_Propagation::GetFilter();
132
133   // find non-auxiliary hypothesis
134   const SMESHDS_Hypothesis *theHyp = 0;
135   set< string > propagTypes;
136   std::cout << "For shape " << aShape.HashCode(1) << " of type "<< aShape.ShapeType() <<
137                "CheckHypothesis" << std::endl;
138   for(auto hyp:hyps){
139     SMESH_Comment hypStr;
140     hypStr << hyp << " " << hyp->GetName() << " ";
141     ((SMESHDS_Hypothesis*)hyp)->SaveTo( hypStr.Stream() );
142     hypStr << " ";
143     std::cout << hypStr << std::endl;
144   }
145   list <const SMESHDS_Hypothesis * >::const_iterator h = hyps.begin();
146   for ( ; h != hyps.end(); ++h ) {
147     if ( static_cast<const SMESH_Hypothesis*>(*h)->IsAuxiliary() ) {
148       if ( strcmp( "QuadraticMesh", (*h)->GetName() ) == 0 )
149         _quadraticMesh = true;
150       if ( propagFilter.IsOk( static_cast< const SMESH_Hypothesis*>( *h ), aShape ))
151         propagTypes.insert( (*h)->GetName() );
152     }
153     else {
154       if ( !theHyp )
155         theHyp = *h; // use only the first non-auxiliary hypothesis
156     }
157   }
158
159   if ( !theHyp )
160   {
161     aStatus = SMESH_Hypothesis::HYP_MISSING;
162     return false;  // can't work without a hypothesis
163   }
164
165   string hypName = theHyp->GetName();
166
167   if ( !_mainEdge.IsNull() && _hypType == DISTRIB_PROPAGATION )
168   {
169     aStatus = SMESH_Hypothesis::HYP_OK;
170   }
171   else if ( hypName == "LocalLength" )
172   {
173     const StdMeshers_LocalLength * hyp =
174       dynamic_cast <const StdMeshers_LocalLength * >(theHyp);
175     ASSERT(hyp);
176     _value[ BEG_LENGTH_IND ] = hyp->GetLength();
177     _value[ PRECISION_IND  ] = hyp->GetPrecision();
178     ASSERT( _value[ BEG_LENGTH_IND ] > 0 );
179     _hypType = LOCAL_LENGTH;
180     aStatus = SMESH_Hypothesis::HYP_OK;
181   }
182
183   else if ( hypName == "MaxLength" )
184   {
185     const StdMeshers_MaxLength * hyp =
186       dynamic_cast <const StdMeshers_MaxLength * >(theHyp);
187     ASSERT(hyp);
188     _value[ BEG_LENGTH_IND ] = hyp->GetLength();
189     if ( hyp->GetUsePreestimatedLength() ) {
190       if ( int nbSeg = aMesh.GetGen()->GetBoundaryBoxSegmentation() )
191         _value[ BEG_LENGTH_IND ] = aMesh.GetShapeDiagonalSize() / nbSeg;
192     }
193     ASSERT( _value[ BEG_LENGTH_IND ] > 0 );
194     _hypType = MAX_LENGTH;
195     aStatus = SMESH_Hypothesis::HYP_OK;
196   }
197
198   else if ( hypName == "NumberOfSegments" )
199   {
200     const StdMeshers_NumberOfSegments * hyp =
201       dynamic_cast <const StdMeshers_NumberOfSegments * >(theHyp);
202     ASSERT(hyp);
203     _ivalue[ NB_SEGMENTS_IND  ] = hyp->GetNumberOfSegments();
204     ASSERT( _ivalue[ NB_SEGMENTS_IND ] > 0 );
205     _ivalue[ DISTR_TYPE_IND ] = (int) hyp->GetDistrType();
206     switch (_ivalue[ DISTR_TYPE_IND ])
207     {
208     case StdMeshers_NumberOfSegments::DT_Scale:
209       _value[ SCALE_FACTOR_IND ] = hyp->GetScaleFactor();
210       _revEdgesIDs = hyp->GetReversedEdges();
211       break;
212     case StdMeshers_NumberOfSegments::DT_TabFunc:
213       _vvalue[ TAB_FUNC_IND ] = hyp->GetTableFunction();
214       _revEdgesIDs = hyp->GetReversedEdges();
215       break;
216     case StdMeshers_NumberOfSegments::DT_ExprFunc:
217       _svalue[ EXPR_FUNC_IND ] = hyp->GetExpressionFunction();
218       _revEdgesIDs = hyp->GetReversedEdges();
219       break;
220     case StdMeshers_NumberOfSegments::DT_Regular:
221       break;
222     default:
223       ASSERT(0);
224       break;
225     }
226     if (_ivalue[ DISTR_TYPE_IND ] == StdMeshers_NumberOfSegments::DT_TabFunc ||
227         _ivalue[ DISTR_TYPE_IND ] == StdMeshers_NumberOfSegments::DT_ExprFunc)
228         _ivalue[ CONV_MODE_IND ] = hyp->ConversionMode();
229     _hypType = NB_SEGMENTS;
230     aStatus = SMESH_Hypothesis::HYP_OK;
231   }
232
233   else if ( hypName == "Arithmetic1D" )
234   {
235     const StdMeshers_Arithmetic1D * hyp =
236       dynamic_cast <const StdMeshers_Arithmetic1D * >(theHyp);
237     ASSERT(hyp);
238     _value[ BEG_LENGTH_IND ] = hyp->GetLength( true );
239     _value[ END_LENGTH_IND ] = hyp->GetLength( false );
240     ASSERT( _value[ BEG_LENGTH_IND ] > 0 && _value[ END_LENGTH_IND ] > 0 );
241     _hypType = ARITHMETIC_1D;
242
243     _revEdgesIDs = hyp->GetReversedEdges();
244
245     aStatus = SMESH_Hypothesis::HYP_OK;
246   }
247
248   else if ( hypName == "GeometricProgression" )
249   {
250     const StdMeshers_Geometric1D * hyp =
251       dynamic_cast <const StdMeshers_Geometric1D * >(theHyp);
252     ASSERT(hyp);
253     _value[ BEG_LENGTH_IND ] = hyp->GetStartLength();
254     _value[ END_LENGTH_IND ] = hyp->GetCommonRatio();
255     ASSERT( _value[ BEG_LENGTH_IND ] > 0 && _value[ END_LENGTH_IND ] > 0 );
256     _hypType = GEOMETRIC_1D;
257
258     _revEdgesIDs = hyp->GetReversedEdges();
259
260     aStatus = SMESH_Hypothesis::HYP_OK;
261   }
262
263   else if ( hypName == "FixedPoints1D" ) {
264     _fpHyp = dynamic_cast <const StdMeshers_FixedPoints1D*>(theHyp);
265     ASSERT(_fpHyp);
266     _hypType = FIXED_POINTS_1D;
267
268     _revEdgesIDs = _fpHyp->GetReversedEdges();
269
270     aStatus = SMESH_Hypothesis::HYP_OK;
271   }
272
273   else if ( hypName == "StartEndLength" )
274   {
275     const StdMeshers_StartEndLength * hyp =
276       dynamic_cast <const StdMeshers_StartEndLength * >(theHyp);
277     ASSERT(hyp);
278     _value[ BEG_LENGTH_IND ] = hyp->GetLength( true );
279     _value[ END_LENGTH_IND ] = hyp->GetLength( false );
280     ASSERT( _value[ BEG_LENGTH_IND ] > 0 && _value[ END_LENGTH_IND ] > 0 );
281     _hypType = BEG_END_LENGTH;
282
283     _revEdgesIDs = hyp->GetReversedEdges();
284
285     aStatus = SMESH_Hypothesis::HYP_OK;
286   }
287
288   else if ( hypName == "Deflection1D" )
289   {
290     const StdMeshers_Deflection1D * hyp =
291       dynamic_cast <const StdMeshers_Deflection1D * >(theHyp);
292     ASSERT(hyp);
293     _value[ DEFLECTION_IND ] = hyp->GetDeflection();
294     ASSERT( _value[ DEFLECTION_IND ] > 0 );
295     _hypType = DEFLECTION;
296     aStatus = SMESH_Hypothesis::HYP_OK;
297   }
298
299   else if ( hypName == "AutomaticLength" )
300   {
301     StdMeshers_AutomaticLength * hyp = const_cast<StdMeshers_AutomaticLength *>
302       (dynamic_cast <const StdMeshers_AutomaticLength * >(theHyp));
303     ASSERT(hyp);
304     _value[ BEG_LENGTH_IND ] = _value[ END_LENGTH_IND ] = hyp->GetLength( &aMesh, aShape );
305     ASSERT( _value[ BEG_LENGTH_IND ] > 0 );
306     _hypType = MAX_LENGTH;
307     aStatus = SMESH_Hypothesis::HYP_OK;
308   }
309   else if ( hypName == "Adaptive1D" )
310   {
311     _adaptiveHyp = dynamic_cast < const StdMeshers_Adaptive1D* >(theHyp);
312     ASSERT(_adaptiveHyp);
313     _hypType = ADAPTIVE;
314     _onlyUnaryInput = false;
315     aStatus = SMESH_Hypothesis::HYP_OK;
316   }
317   else
318   {
319     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
320   }
321
322   if ( propagTypes.size() > 1 && aStatus == HYP_OK )
323   {
324     // detect concurrent Propagation hyps
325     _usedHypList.clear();
326     list< TopoDS_Shape > assignedTo;
327     if ( aMesh.GetHypotheses( aShape, propagFilter, _usedHypList, true, &assignedTo ) > 1 )
328     {
329       // find most simple shape and a hyp on it
330       int simpleShape = TopAbs_COMPOUND;
331       const SMESHDS_Hypothesis* localHyp = 0;
332       list< TopoDS_Shape >::iterator            shape = assignedTo.begin();
333       list< const SMESHDS_Hypothesis *>::iterator hyp = _usedHypList.begin();
334       for ( ; shape != assignedTo.end(); ++shape )
335         if ( shape->ShapeType() > simpleShape )
336         {
337           simpleShape = shape->ShapeType();
338           localHyp = (*hyp);
339         }
340       // check if there a different hyp on simpleShape
341       shape = assignedTo.begin();
342       hyp = _usedHypList.begin();
343       for ( ; hyp != _usedHypList.end(); ++hyp, ++shape )
344         if ( shape->ShapeType() == simpleShape &&
345              !localHyp->IsSameName( **hyp ))
346         {
347           aStatus = HYP_INCOMPAT_HYPS;
348           return error( SMESH_Comment("Hypotheses of both \"")
349                         << StdMeshers_Propagation::GetName() << "\" and \""
350                         << StdMeshers_PropagOfDistribution::GetName()
351                         << "\" types can't be applied to the same edge");
352         }
353     }
354   }
355
356   return ( aStatus == SMESH_Hypothesis::HYP_OK );
357 }
358
359 static bool computeParamByFunc(Adaptor3d_Curve& C3d,
360                                double first, double last, double length,
361                                bool theReverse, smIdType nbSeg, Function& func,
362                                list<double>& theParams)
363 {
364   // never do this way
365   //OSD::SetSignal( true );
366
367   if ( nbSeg <= 0 )
368     return false;
369
370   smIdType nbPnt = 1 + nbSeg;
371   vector<double> x( nbPnt, 0. );
372
373
374   const double eps = Min( 1E-4, 0.01 / double( nbSeg ));
375
376   if ( !buildDistribution( func, 0.0, 1.0, nbSeg, x, eps ))
377      return false;
378
379   // apply parameters in range [0,1] to the space of the curve
380   double prevU = first;
381   double  sign = 1.;
382   if ( theReverse )
383   {
384     prevU = last;
385     sign  = -1.;
386   }
387
388   for ( smIdType i = 1; i < nbSeg; i++ )
389   {
390     double curvLength = length * (x[i] - x[i-1]) * sign;
391     double tol        = Min( Precision::Confusion(), curvLength / 100. );
392     GCPnts_AbscissaPoint Discret( tol, C3d, curvLength, prevU );
393     if ( !Discret.IsDone() )
394       return false;
395     double U = Discret.Parameter();
396     if ( U > first && U < last )
397       theParams.push_back( U );
398     else
399       return false;
400     prevU = U;
401   }
402   if ( theReverse )
403     theParams.reverse();
404
405   return true;
406 }
407
408
409 //================================================================================
410 /*!
411  * \brief adjust internal node parameters so that the last segment length == an
412  *  \param a1 - the first segment length
413  *  \param an - the last segment length
414  *  \param U1 - the first edge parameter
415  *  \param Un - the last edge parameter
416  *  \param length - the edge length
417  *  \param C3d - the edge curve
418  *  \param theParams - internal node parameters to adjust
419  *  \param adjustNeighbors2an - to adjust length of segments next to the last one
420  *   and not to remove parameters
421  */
422 //================================================================================
423
424 static void compensateError(double a1, double an,
425                             double U1, double Un,
426                             double            length,
427                             Adaptor3d_Curve&  C3d,
428                             list<double> &    theParams,
429                             bool              adjustNeighbors2an = false)
430 {
431   smIdType i, nPar = theParams.size();
432   if ( a1 + an <= length && nPar > 1 )
433   {
434     bool reverse = ( U1 > Un );
435     double tol   = Min( Precision::Confusion(), 0.01 * an );
436     GCPnts_AbscissaPoint Discret( tol, C3d, reverse ? an : -an, Un );
437     if ( !Discret.IsDone() )
438       return;
439     double Utgt = Discret.Parameter(); // target value of the last parameter
440     list<double>::reverse_iterator itU = theParams.rbegin();
441     double Ul = *itU++; // real value of the last parameter
442     double dUn = Utgt - Ul; // parametric error of <an>
443     double dU = Abs( Ul - *itU ); // parametric length of the last but one segment
444     if ( Abs(dUn) <= 1e-3 * dU )
445       return;
446     if ( adjustNeighbors2an || Abs(dUn) < 0.5 * dU ) { // last segment is a bit shorter than it should
447       // move the last parameter to the edge beginning
448     }
449     else {  // last segment is much shorter than it should -> remove the last param and
450       theParams.pop_back(); nPar--; // move the rest points toward the edge end
451       dUn = Utgt - theParams.back();
452     }
453
454     if ( !adjustNeighbors2an )
455     {
456       double q = dUn / ( Utgt - Un ); // (signed) factor of segment length change
457       for ( itU = theParams.rbegin(), i = 1; i < nPar; i++ ) {
458         double prevU = *itU;
459         (*itU) += dUn;
460         ++itU;
461         dUn = q * (*itU - prevU) * (prevU-U1)/(Un-U1);
462       }
463     }
464     else if ( nPar == 1 )
465     {
466       theParams.back() += dUn;
467     }
468     else
469     {
470       double q  =  dUn / double( nPar - 1 );
471       theParams.back() += dUn;
472       double sign = reverse ? -1 : 1;
473       double prevU = theParams.back();
474       itU = theParams.rbegin();
475       for ( ++itU, i = 2; i < nPar; ++itU, i++ ) {
476         double newU = *itU + dUn;
477         if ( newU*sign < prevU*sign ) {
478           prevU = *itU = newU;
479           dUn -= q;
480         }
481         else { // set U between prevU and next valid param
482           list<double>::reverse_iterator itU2 = itU;
483           ++itU2;
484           int nb = 2;
485           while ( (*itU2)*sign > prevU*sign ) {
486             ++itU2; ++nb;
487           }
488           dU = ( *itU2 - prevU ) / nb;
489           while ( itU != itU2 ) {
490             *itU += dU; ++itU;
491           }
492           break;
493         }
494       }
495     }
496   }
497 }
498
499 //================================================================================
500 /*!
501  * \brief Class used to clean mesh on edges when 0D hyp modified.
502  * Common approach doesn't work when 0D algo is missing because the 0D hyp is
503  * considered as not participating in computation whereas it is used by 1D algo.
504  */
505 //================================================================================
506
507 // struct VertexEventListener : public SMESH_subMeshEventListener
508 // {
509 //   VertexEventListener():SMESH_subMeshEventListener(0) // won't be deleted by submesh
510 //   {}
511 //   /*!
512 //    * \brief Clean mesh on edges
513 //    * \param event - algo_event or compute_event itself (of SMESH_subMesh)
514 //    * \param eventType - ALGO_EVENT or COMPUTE_EVENT (of SMESH_subMesh)
515 //    * \param subMesh - the submesh where the event occurs
516 //    */
517 //   void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
518 //                     EventListenerData*, const SMESH_Hypothesis*)
519 //   {
520 //     if ( eventType == SMESH_subMesh::ALGO_EVENT) // all algo events
521 //     {
522 //       subMesh->ComputeStateEngine( SMESH_subMesh::MODIF_ALGO_STATE );
523 //     }
524 //   }
525 // }; // struct VertexEventListener
526
527 //=============================================================================
528 /*!
529  * \brief Sets event listener to vertex submeshes
530  * \param subMesh - submesh where algo is set
531  *
532  * This method is called when a submesh gets HYP_OK algo_state.
533  * After being set, event listener is notified on each event of a submesh.
534  */
535 //=============================================================================
536
537 void StdMeshers_Regular_1D::SetEventListener(SMESH_subMesh* subMesh)
538 {
539   StdMeshers_Propagation::SetPropagationMgr( subMesh );
540 }
541
542 //=============================================================================
543 /*!
544  * \brief Do nothing
545  * \param subMesh - restored submesh
546  *
547  * This method is called only if a submesh has HYP_OK algo_state.
548  */
549 //=============================================================================
550
551 void StdMeshers_Regular_1D::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
552 {
553 }
554
555 //=============================================================================
556 /*!
557  * \brief Return StdMeshers_SegmentLengthAroundVertex assigned to vertex
558  */
559 //=============================================================================
560
561 const StdMeshers_SegmentLengthAroundVertex*
562 StdMeshers_Regular_1D::getVertexHyp(SMESH_Mesh &          theMesh,
563                                     const TopoDS_Vertex & theV)
564 {
565   static SMESH_HypoFilter filter( SMESH_HypoFilter::HasName("SegmentAroundVertex_0D"));
566   if ( const SMESH_Hypothesis * h = theMesh.GetHypothesis( theV, filter, true ))
567   {
568     SMESH_Algo* algo = const_cast< SMESH_Algo* >( static_cast< const SMESH_Algo* > ( h ));
569     const list <const SMESHDS_Hypothesis *> & hypList = algo->GetUsedHypothesis( theMesh, theV, 0 );
570     if ( !hypList.empty() && string("SegmentLengthAroundVertex") == hypList.front()->GetName() )
571       return static_cast<const StdMeshers_SegmentLengthAroundVertex*>( hypList.front() );
572   }
573   return 0;
574 }
575
576 //================================================================================
577 /*!
578  * \brief Divide a curve into equal segments
579  */
580 //================================================================================
581
582 bool StdMeshers_Regular_1D::divideIntoEqualSegments( SMESH_Mesh &        theMesh,
583                                                      Adaptor3d_Curve &   theC3d,
584                                                      smIdType            theNbPoints,
585                                                      double              theTol,
586                                                      double              theLength,
587                                                      double              theFirstU,
588                                                      double              theLastU,
589                                                      std::list<double> & theParameters )
590 {
591   bool ok = false;
592   if ( theNbPoints < IntegerLast() )
593   {
594     int nbPnt = FromSmIdType<int>( theNbPoints );
595     GCPnts_UniformAbscissa discret(theC3d, nbPnt, theFirstU, theLastU, theTol );
596     if ( !discret.IsDone() )
597       return error( "GCPnts_UniformAbscissa failed");
598     if ( discret.NbPoints() < nbPnt )
599       discret.Initialize(theC3d, nbPnt + 1, theFirstU, theLastU, theTol );
600
601     int nbPoints = Min( discret.NbPoints(), nbPnt );
602     for ( int i = 2; i < nbPoints; i++ ) // skip 1st and last points
603     {
604       double param = discret.Parameter(i);
605       theParameters.push_back( param );
606     }
607     ok = true;
608   }
609   else // huge nb segments
610   {
611     // use FIXED_POINTS_1D method
612     StdMeshers_FixedPoints1D fixedPointsHyp( GetGen()->GetANewId(), GetGen() );
613     _fpHyp = &fixedPointsHyp;
614     std::vector<double>   params = { 0., 1. };
615     std::vector<smIdType> nbSegs = { theNbPoints - 1 };
616     fixedPointsHyp.SetPoints( params );
617     fixedPointsHyp.SetNbSegments( nbSegs );
618
619     HypothesisType curType = _hypType;
620     _hypType = FIXED_POINTS_1D;
621
622     ok = computeInternalParameters( theMesh, theC3d, theLength, theFirstU, theLastU,
623                                     theParameters, /*reverse=*/false );
624     _hypType = curType;
625     _fpHyp = 0;
626   }
627   return ok;
628 }
629
630 //================================================================================
631 /*!
632  * \brief Tune parameters to fit "SegmentLengthAroundVertex" hypothesis
633  *  \param theC3d - wire curve
634  *  \param theLength - curve length
635  *  \param theParameters - internal nodes parameters to modify
636  *  \param theVf - 1st vertex
637  *  \param theVl - 2nd vertex
638  */
639 //================================================================================
640
641 void StdMeshers_Regular_1D::redistributeNearVertices (SMESH_Mesh &          theMesh,
642                                                       Adaptor3d_Curve &     theC3d,
643                                                       double                theLength,
644                                                       std::list< double > & theParameters,
645                                                       const TopoDS_Vertex & theVf,
646                                                       const TopoDS_Vertex & theVl)
647 {
648   double f = theC3d.FirstParameter(), l = theC3d.LastParameter();
649   size_t nPar = theParameters.size();
650   for ( int isEnd1 = 0; isEnd1 < 2; ++isEnd1 )
651   {
652     const TopoDS_Vertex & V = isEnd1 ? theVf : theVl;
653     const StdMeshers_SegmentLengthAroundVertex* hyp = getVertexHyp (theMesh, V );
654     if ( hyp ) {
655       double vertexLength = hyp->GetLength();
656       if ( vertexLength > theLength / 2.0 )
657         continue;
658       if ( isEnd1 ) { // to have a segment of interest at end of theParameters
659         theParameters.reverse();
660         std::swap( f, l );
661       }
662       if ( _hypType == NB_SEGMENTS )
663       {
664         compensateError(0, vertexLength, f, l, theLength, theC3d, theParameters, true );
665       }
666       else if ( nPar <= 3 )
667       {
668         if ( !isEnd1 )
669           vertexLength = -vertexLength;
670         double tol = Min( Precision::Confusion(), 0.01 * vertexLength );
671         GCPnts_AbscissaPoint Discret( tol, theC3d, vertexLength, l );
672         if ( Discret.IsDone() ) {
673           if ( nPar == 0 )
674             theParameters.push_back( Discret.Parameter());
675           else {
676             double L = GCPnts_AbscissaPoint::Length( theC3d, theParameters.back(), l);
677             if ( vertexLength < L / 2.0 )
678               theParameters.push_back( Discret.Parameter());
679             else
680               compensateError(0, vertexLength, f, l, theLength, theC3d, theParameters, true );
681           }
682         }
683       }
684       else
685       {
686         // recompute params between the last segment and a middle one.
687         // find size of a middle segment
688         smIdType nHalf = ( nPar-1 ) / 2;
689         list< double >::reverse_iterator itU = theParameters.rbegin();
690         std::advance( itU, nHalf );
691         double Um = *itU++;
692         double Lm = GCPnts_AbscissaPoint::Length( theC3d, Um, *itU);
693         double L = GCPnts_AbscissaPoint::Length( theC3d, *itU, l);
694         static StdMeshers_Regular_1D* auxAlgo = 0;
695         if ( !auxAlgo ) {
696           auxAlgo = new StdMeshers_Regular_1D( _gen->GetANewId(), _gen );
697           auxAlgo->_hypType = BEG_END_LENGTH;
698         }
699         auxAlgo->_value[ BEG_LENGTH_IND ] = Lm;
700         auxAlgo->_value[ END_LENGTH_IND ] = vertexLength;
701         double from = *itU, to = l;
702         if ( isEnd1 ) {
703           std::swap( from, to );
704           std::swap( auxAlgo->_value[ BEG_LENGTH_IND ], auxAlgo->_value[ END_LENGTH_IND ]);
705         }
706         list<double> params;
707         if ( auxAlgo->computeInternalParameters( theMesh, theC3d, L, from, to, params, false ))
708         {
709           if ( isEnd1 ) params.reverse();
710           while ( 1 + nHalf-- )
711             theParameters.pop_back();
712           theParameters.splice( theParameters.end(), params );
713         }
714         else
715         {
716           compensateError(0, vertexLength, f, l, theLength, theC3d, theParameters, true );
717         }
718       }
719       if ( isEnd1 )
720         theParameters.reverse();
721     }
722   }
723 }
724
725 //=============================================================================
726 /*!
727  *
728  */
729 //=============================================================================
730 bool StdMeshers_Regular_1D::computeInternalParameters(SMESH_Mesh &     theMesh,
731                                                       Adaptor3d_Curve& theC3d,
732                                                       double           theLength,
733                                                       double           theFirstU,
734                                                       double           theLastU,
735                                                       list<double> &   theParams,
736                                                       const bool       theReverse,
737                                                       bool             theConsiderPropagation)
738 {
739   theParams.clear();
740
741   double f = theFirstU, l = theLastU;
742
743   // Propagation Of Distribution
744   //
745   if ( !_mainEdge.IsNull() && _hypType == DISTRIB_PROPAGATION )
746   {
747     TopoDS_Edge mainEdge = TopoDS::Edge( _mainEdge ); // should not be a reference!
748     _gen->Compute( theMesh, mainEdge, SMESH_Gen::SHAPE_ONLY_UPWARD );
749
750     SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( mainEdge );
751     if ( !smDS )
752       return error("No mesh on the source edge of Propagation Of Distribution");
753     if ( smDS->NbNodes() < 1 )
754       return true; // 1 segment
755
756     map< double, const SMDS_MeshNode* > mainEdgeParamsOfNodes;
757     if ( ! SMESH_Algo::GetSortedNodesOnEdge( theMesh.GetMeshDS(), mainEdge, _quadraticMesh,
758                                              mainEdgeParamsOfNodes, SMDSAbs_Edge ))
759       return error("Bad node parameters on the source edge of Propagation Of Distribution");
760     vector< double > segLen( mainEdgeParamsOfNodes.size() - 1 );
761     double totalLen = 0;
762     BRepAdaptor_Curve mainEdgeCurve( mainEdge );
763     map< double, const SMDS_MeshNode* >::iterator
764       u_n2 = mainEdgeParamsOfNodes.begin(), u_n1 = u_n2++;
765     for ( size_t i = 1; i < mainEdgeParamsOfNodes.size(); ++i, ++u_n1, ++u_n2 )
766     {
767       segLen[ i-1 ] = GCPnts_AbscissaPoint::Length( mainEdgeCurve,
768                                                     u_n1->first,
769                                                     u_n2->first);
770       totalLen += segLen[ i-1 ];
771     }
772     for ( size_t i = 0; i < segLen.size(); ++i )
773       segLen[ i ] *= theLength / totalLen;
774
775     size_t  iSeg = theReverse ? segLen.size()-1 : 0;
776     size_t  dSeg = theReverse ? -1 : +1;
777     double param = theFirstU;
778     size_t nbParams = 0;
779     for ( size_t i = 1; i < segLen.size(); ++i, iSeg += dSeg )
780     {
781       double tol = Min( Precision::Confusion(), 0.01 * segLen[ iSeg ]);
782       GCPnts_AbscissaPoint Discret( tol, theC3d, segLen[ iSeg ], param );
783       if ( !Discret.IsDone() ) break;
784       param = Discret.Parameter();
785       theParams.push_back( param );
786       ++nbParams;
787     }
788     if ( nbParams != segLen.size()-1 )
789       return error( SMESH_Comment("Can't divide into ") << segLen.size() << " segments");
790
791     compensateError( segLen[ theReverse ? segLen.size()-1 : 0 ],
792                      segLen[ theReverse ? 0 : segLen.size()-1 ],
793                      f, l, theLength, theC3d, theParams, true );
794     return true;
795   }
796
797
798   switch( _hypType )
799   {
800   case LOCAL_LENGTH:
801   case MAX_LENGTH:
802   case NB_SEGMENTS:
803   {
804     double eltSize = 1;
805     smIdType nbSegments;
806     if ( _hypType == MAX_LENGTH )
807     {
808       double nbseg = ceil(theLength / _value[ BEG_LENGTH_IND ]); // integer sup
809       if (nbseg <= 0)
810         nbseg = 1; // degenerated edge
811       eltSize = theLength / nbseg * ( 1. - 1e-9 );
812       nbSegments = ToSmIdType( nbseg );
813     }
814     else if ( _hypType == LOCAL_LENGTH )
815     {
816       // Local Length hypothesis
817       double nbseg = ceil(theLength / _value[ BEG_LENGTH_IND ]); // integer sup
818
819       // NPAL17873:
820       bool isFound = false;
821       if (theConsiderPropagation && !_mainEdge.IsNull()) // propagated from some other edge
822       {
823         // Advanced processing to assure equal number of segments in case of Propagation
824         SMESH_subMesh* sm = theMesh.GetSubMeshContaining(_mainEdge);
825         if (sm) {
826           bool computed = sm->IsMeshComputed();
827           if (!computed) {
828             if (sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE) {
829               _gen->Compute( theMesh, _mainEdge, /*anUpward=*/true);
830               computed = sm->IsMeshComputed();
831             }
832           }
833           if (computed) {
834             SMESHDS_SubMesh* smds = sm->GetSubMeshDS();
835             smIdType  nb_segments = smds->NbElements();
836             if (nbseg - 1 <= nb_segments && nb_segments <= nbseg + 1) {
837               isFound = true;
838               nbseg = FromSmIdType<double>( nb_segments );
839             }
840           }
841         }
842       }
843       if (!isFound) // not found by meshed edge in the propagation chain, use precision
844       {
845         double aPrecision = _value[ PRECISION_IND ];
846         double nbseg_prec = ceil((theLength / _value[ BEG_LENGTH_IND ]) - aPrecision);
847         if (nbseg_prec == (nbseg - 1)) nbseg--;
848       }
849
850       if (nbseg <= 0)
851         nbseg = 1;                        // degenerated edge
852       eltSize = theLength / nbseg;
853       nbSegments = ToSmIdType( nbseg );
854     }
855     else
856     {
857       // Number Of Segments hypothesis
858       nbSegments = _ivalue[ NB_SEGMENTS_IND ];
859       if ( nbSegments < 1 )  {
860         return false;
861       }
862       if ( nbSegments == 1 ) {
863         return true;
864       }
865
866       switch (_ivalue[ DISTR_TYPE_IND ])
867       {
868       case StdMeshers_NumberOfSegments::DT_Scale:
869         {
870           double scale = _value[ SCALE_FACTOR_IND ];
871
872           if (fabs(scale - 1.0) < Precision::Confusion()) {
873             // special case to avoid division by zero
874             for ( smIdType i = 1; i < nbSegments; i++) {
875               double param = f + (l - f) * double( i ) / double( nbSegments );
876               theParams.push_back( param );
877             }
878           }
879           else { // general case of scale distribution
880             if ( theReverse )
881               scale = 1.0 / scale;
882
883             double  alpha = pow(scale, 1.0 / double( nbSegments - 1 ));
884             double factor = (l - f) / (1.0 - pow(alpha, nbSegments));
885
886             for ( smIdType i = 1; i < nbSegments; i++) {
887               double param = f + factor * (1.0 - pow(alpha, i));
888               theParams.push_back( param );
889             }
890           }
891           const double lenFactor = theLength/(l-f);
892           const double minSegLen = Min( theParams.front() - f, l - theParams.back() );
893           const double       tol = Min( Precision::Confusion(), 0.01 * minSegLen );
894           list<double>::iterator u = theParams.begin(), uEnd = theParams.end();
895           for ( ; u != uEnd; ++u )
896           {
897             GCPnts_AbscissaPoint Discret( tol, theC3d, ((*u)-f) * lenFactor, f );
898             if ( Discret.IsDone() )
899               *u = Discret.Parameter();
900           }
901           return true;
902         }
903         break;
904       case StdMeshers_NumberOfSegments::DT_TabFunc:
905         {
906           FunctionTable func(_vvalue[ TAB_FUNC_IND ], FromSmIdType<int>( _ivalue[ CONV_MODE_IND ]));
907           return computeParamByFunc(theC3d, f, l, theLength, theReverse,
908                                     _ivalue[ NB_SEGMENTS_IND ], func,
909                                     theParams);
910         }
911         break;
912       case StdMeshers_NumberOfSegments::DT_ExprFunc:
913         {
914           FunctionExpr func(_svalue[ EXPR_FUNC_IND ].c_str(),
915                             FromSmIdType<int>( _ivalue[ CONV_MODE_IND ]));
916           return computeParamByFunc(theC3d, f, l, theLength, theReverse,
917                                     _ivalue[ NB_SEGMENTS_IND ], func,
918                                     theParams);
919         }
920         break;
921       case StdMeshers_NumberOfSegments::DT_Regular:
922         eltSize = theLength / double( nbSegments );
923         break;
924       default:
925         return false;
926       }
927     }
928
929     double tol = Min( Precision::Confusion(), 0.01 * eltSize );
930     divideIntoEqualSegments( theMesh, theC3d, nbSegments + 1, tol,
931                              theLength, theFirstU, theLastU, theParams );
932
933     compensateError( eltSize, eltSize, f, l, theLength, theC3d, theParams, true ); // for PAL9899
934     return true;
935   }
936
937
938   case BEG_END_LENGTH: {
939
940     // geometric progression: SUM(n) = ( a1 - an * q ) / ( 1 - q ) = theLength
941
942     double a1 = _value[ BEG_LENGTH_IND ];
943     double an = _value[ END_LENGTH_IND ];
944     double q  = ( theLength - a1 ) / ( theLength - an );
945     if ( q < theLength/1e6 || 1.01*theLength < a1 + an)
946       return error ( SMESH_Comment("Invalid segment lengths (")<<a1<<" and "<<an<<") "<<
947                      "for an edge of length "<<theLength);
948
949     double      U1 = theReverse ? l : f;
950     double      Un = theReverse ? f : l;
951     double   param = U1;
952     double eltSize = theReverse ? -a1 : a1;
953     double     tol = Min( Precision::Confusion(), 0.01 * Min( a1, an ));
954     while ( 1 ) {
955       // computes a point on a curve <theC3d> at the distance <eltSize>
956       // from the point of parameter <param>.
957       GCPnts_AbscissaPoint Discret( tol, theC3d, eltSize, param );
958       if ( !Discret.IsDone() ) break;
959       param = Discret.Parameter();
960       if ( f < param && param < l )
961         theParams.push_back( param );
962       else
963         break;
964       eltSize *= q;
965     }
966     compensateError( a1, an, U1, Un, theLength, theC3d, theParams );
967     if (theReverse) theParams.reverse(); // NPAL18025
968     return true;
969   }
970
971   case ARITHMETIC_1D:
972   {
973     // arithmetic progression: SUM(n) = ( an - a1 + q ) * ( a1 + an ) / ( 2 * q ) = theLength
974
975     double a1 = _value[ BEG_LENGTH_IND ];
976     double an = _value[ END_LENGTH_IND ];
977     if ( 1.01*theLength < a1 + an )
978       return error ( SMESH_Comment("Invalid segment lengths (")<<a1<<" and "<<an<<") "<<
979                      "for an edge of length "<<theLength);
980
981     double q = ( an - a1 ) / ( 2 *theLength/( a1 + an ) - 1 );
982     int    n = int(fabs(q) > numeric_limits<double>::min() ? ( 1+( an-a1 )/q ) : ( 1+theLength/a1 ));
983
984     double      U1 = theReverse ? l : f;
985     double      Un = theReverse ? f : l;
986     double   param = U1;
987     double eltSize = a1;
988     double     tol = Min( Precision::Confusion(), 0.01 * Min( a1, an ));
989     if ( theReverse ) {
990       eltSize = -eltSize;
991       q = -q;
992     }
993     while ( n-- > 0 && eltSize * ( Un - U1 ) > 0 ) {
994       // computes a point on a curve <theC3d> at the distance <eltSize>
995       // from the point of parameter <param>.
996       GCPnts_AbscissaPoint Discret( tol, theC3d, eltSize, param );
997       if ( !Discret.IsDone() ) break;
998       param = Discret.Parameter();
999       if ( param > f && param < l )
1000         theParams.push_back( param );
1001       else
1002         break;
1003       eltSize += q;
1004     }
1005     compensateError( a1, an, U1, Un, theLength, theC3d, theParams );
1006     if ( theReverse ) theParams.reverse(); // NPAL18025
1007
1008     return true;
1009   }
1010
1011   case GEOMETRIC_1D:
1012   {
1013     double a1 = _value[ BEG_LENGTH_IND ], an = 0;
1014     double q  = _value[ END_LENGTH_IND ];
1015
1016     double U1 = theReverse ? l : f;
1017     double Un = theReverse ? f : l;
1018     double param = U1;
1019     double eltSize = a1;
1020     if ( theReverse )
1021       eltSize = -eltSize;
1022
1023     int nbParams = 0;
1024     while ( true ) {
1025       // computes a point on a curve <theC3d> at the distance <eltSize>
1026       // from the point of parameter <param>.
1027       double tol = Min( Precision::Confusion(), 0.01 * eltSize );
1028       GCPnts_AbscissaPoint Discret( tol, theC3d, eltSize, param );
1029       if ( !Discret.IsDone() ) break;
1030       param = Discret.Parameter();
1031       if ( f < param && param < l )
1032         theParams.push_back( param );
1033       else
1034         break;
1035       an = eltSize;
1036       eltSize *= q;
1037       ++nbParams;
1038       if ( q < 1. && eltSize < 1e-100 )
1039         return error("Too small common ratio causes too many segments");
1040     }
1041     if ( nbParams > 1 )
1042     {
1043       if ( Abs( param - Un ) < 0.2 * Abs( param - theParams.back() ))
1044       {
1045         compensateError( a1, Abs(eltSize), U1, Un, theLength, theC3d, theParams );
1046       }
1047       else if ( Abs( Un - theParams.back() ) <
1048                 0.2 * Abs( theParams.back() - *(++theParams.rbegin())))
1049       {
1050         theParams.pop_back();
1051         compensateError( a1, Abs(an), U1, Un, theLength, theC3d, theParams );
1052       }
1053     }
1054     if (theReverse) theParams.reverse(); // NPAL18025
1055
1056     return true;
1057   }
1058
1059   case FIXED_POINTS_1D:
1060   {
1061     const std::vector<double>& aPnts = _fpHyp->GetPoints();
1062     std::vector<smIdType>     nbsegs = _fpHyp->GetNbSegments();
1063
1064     // sort normalized params, taking into account theReverse
1065     TColStd_SequenceOfReal Params;
1066     double tol = 1e-7;
1067     for ( size_t i = 0; i < aPnts.size(); i++ )
1068     {
1069       if( aPnts[i] < tol || aPnts[i] > 1 - tol )
1070         continue;
1071       double u = theReverse ? ( 1 - aPnts[i] ) : aPnts[i];
1072       int    j = 1;
1073       bool IsExist = false;
1074       for ( ; j <= Params.Length() &&  !IsExist; j++ )
1075       {
1076         IsExist = ( Abs( u - Params.Value(j) ) < tol );
1077         if ( u < Params.Value(j) ) break;
1078       }
1079       if ( !IsExist ) Params.InsertBefore( j, u );
1080     }
1081     Params.InsertBefore( 1, 0.0 );
1082     Params.Append( 1.0 );
1083
1084     if ( theReverse )
1085     {
1086       if ((int) nbsegs.size() > Params.Length() - 1 )
1087         nbsegs.resize( Params.Length() - 1 );
1088       std::reverse( nbsegs.begin(), nbsegs.end() );
1089     }
1090     if ( nbsegs.empty() )
1091     {
1092       nbsegs.push_back( 1 );
1093     }
1094     if ((int) nbsegs.size() < Params.Length() - 1 )
1095       nbsegs.resize( Params.Length() - 1, nbsegs[0] );
1096
1097     // care of huge nbsegs - additionally divide diapasons
1098     for ( int i = 2; i <= Params.Length(); i++ )
1099     {
1100       smIdType nbTot = nbsegs[ i-2 ];
1101       if ( nbTot <= IntegerLast() )
1102         continue;
1103       smIdType   nbDiapason = nbTot / IntegerLast() + 1;
1104       smIdType nbSegPerDiap = nbTot / nbDiapason;
1105       double           par0 = Params( i - 1 ), par1 = Params( i );
1106       for ( smIdType iDiap = 0; iDiap < nbDiapason - 1; ++iDiap )
1107       {
1108         double    r = double( nbSegPerDiap * ( iDiap + 1 )) / double( nbTot );
1109         double parI = par0 + ( par1 - par0 ) * r;
1110         Params.InsertBefore( i, parI );
1111         auto it = nbsegs.begin();
1112         smIdType incr_it = i - 2 + iDiap;
1113         nbsegs.insert( it + incr_it, nbSegPerDiap );
1114       }
1115       nbsegs[ i-2 + nbDiapason - 1 ] = nbSegPerDiap + nbTot % nbDiapason;
1116     }
1117
1118     // transform normalized Params into real ones
1119     std::vector< double > uVec( Params.Length() );
1120     uVec[ 0 ] = theFirstU;
1121     double abscissa;
1122     for ( int i = 2; i < Params.Length(); i++ )
1123     {
1124       abscissa = Params( i ) * theLength;
1125       tol      = Min( Precision::Confusion(), 0.01 * abscissa );
1126       GCPnts_AbscissaPoint APnt( tol, theC3d, abscissa, theFirstU );
1127       if ( !APnt.IsDone() )
1128         return error( "GCPnts_AbscissaPoint failed");
1129       uVec[ i-1 ] = APnt.Parameter();
1130     }
1131     uVec.back() = theLastU;
1132
1133     // divide segments
1134     double eltSize, segmentSize, par1, par2;
1135     for ( int i = 0; i < (int)uVec.size()-1; i++ )
1136     {
1137       par1 = uVec[ i   ];
1138       par2 = uVec[ i+1 ];
1139       smIdType nbseg = ( i < (int) nbsegs.size() ) ? nbsegs[i] : nbsegs[0];
1140       if ( nbseg > 1 )
1141       {
1142         segmentSize = ( Params( i+2 ) - Params( i+1 )) * theLength;
1143         eltSize     = segmentSize / double( nbseg );
1144         tol         = Min( Precision::Confusion(), 0.01 * eltSize );
1145         if ( !divideIntoEqualSegments( theMesh, theC3d, nbseg + 1, tol,
1146                                        segmentSize, par1, par2, theParams ))
1147           return false;
1148       }
1149       theParams.push_back( par2 );
1150     }
1151     theParams.pop_back();
1152
1153     return true;
1154   }
1155
1156   case DEFLECTION:
1157   {
1158     GCPnts_UniformDeflection Discret( theC3d, _value[ DEFLECTION_IND ], f, l, true );
1159     if ( !Discret.IsDone() )
1160       return false;
1161
1162     int NbPoints = Discret.NbPoints();
1163     for ( int i = 2; i < NbPoints; i++ )
1164     {
1165       double param = Discret.Parameter(i);
1166       theParams.push_back( param );
1167     }
1168     return true;
1169   }
1170
1171   default:;
1172   }
1173
1174   return false;
1175 }
1176
1177 //=============================================================================
1178 /*!
1179  *
1180  */
1181 //=============================================================================
1182
1183 bool StdMeshers_Regular_1D::Compute(SMESH_Mesh & theMesh, const TopoDS_Shape & theShape)
1184 {
1185   SMESH_Hypothesis::Hypothesis_Status hyp_status;
1186   theMesh.Lock();
1187   bool ret = this->CheckHypothesis(theMesh, theShape, hyp_status);
1188   int hypType = _hypType;
1189   theMesh.Unlock();
1190
1191   if ( hypType == NONE )
1192       return false;
1193
1194   if ( hypType == ADAPTIVE )
1195   {
1196     _adaptiveHyp->GetAlgo()->InitComputeError();
1197     _adaptiveHyp->GetAlgo()->Compute( theMesh, theShape );
1198     return error( _adaptiveHyp->GetAlgo()->GetComputeError() );
1199   }
1200
1201   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1202
1203   theMesh.Lock();
1204
1205   const TopoDS_Edge & EE = TopoDS::Edge(theShape);
1206   TopoDS_Edge E = TopoDS::Edge(EE.Oriented(TopAbs_FORWARD));
1207   int shapeID = meshDS->ShapeToIndex( E );
1208
1209   double f, l;
1210   Handle(Geom_Curve) Curve = BRep_Tool::Curve(E, f, l);
1211
1212   TopoDS_Vertex VFirst, VLast;
1213   TopExp::Vertices(E, VFirst, VLast);   // Vfirst corresponds to f and Vlast to l
1214
1215   ASSERT(!VFirst.IsNull());
1216   ASSERT(!VLast.IsNull());
1217   const SMDS_MeshNode * nFirst = SMESH_Algo::VertexNode( VFirst, meshDS );
1218   const SMDS_MeshNode *  nLast = SMESH_Algo::VertexNode( VLast,  meshDS );
1219   if ( !nFirst || !nLast ){
1220     theMesh.Unlock();
1221     std::cout << "exit no node" << std::endl;
1222     return error( COMPERR_BAD_INPUT_MESH, "No node on vertex");
1223   }
1224   // remove elements created by e.g. pattern mapping (PAL21999)
1225   // CLEAN event is incorrectly ptopagated seemingly due to Propagation hyp
1226   // so TEMPORARY solution is to clean the submesh manually
1227   if (SMESHDS_SubMesh * subMeshDS = meshDS->MeshElements(theShape))
1228   {
1229     SMDS_ElemIteratorPtr ite = subMeshDS->GetElements();
1230     while (ite->more())
1231       meshDS->RemoveFreeElement(ite->next(), subMeshDS);
1232     SMDS_NodeIteratorPtr itn = subMeshDS->GetNodes();
1233     while (itn->more()) {
1234       const SMDS_MeshNode * node = itn->next();
1235       if ( node->NbInverseElements() == 0 )
1236         meshDS->RemoveFreeNode(node, subMeshDS);
1237       else
1238         meshDS->RemoveNode(node);
1239     }
1240   }
1241
1242   double length = EdgeLength( E );
1243   if ( !Curve.IsNull() && length > 0 )
1244   {
1245     list< double > params;
1246     bool reversed = false;
1247     if ( theMesh.GetShapeToMesh().ShapeType() >= TopAbs_WIRE && _revEdgesIDs.empty() ) {
1248       // if the shape to mesh is WIRE or EDGE
1249       reversed = ( EE.Orientation() == TopAbs_REVERSED );
1250     }
1251     if ( !_mainEdge.IsNull() ) {
1252       // take into account reversing the edge the hypothesis is propagated from
1253       // (_mainEdge.Orientation() marks mutual orientation of EDGEs in propagation chain)
1254       reversed = ( _mainEdge.Orientation() == TopAbs_REVERSED );
1255       if ( hypType != DISTRIB_PROPAGATION ) {
1256         int mainID = meshDS->ShapeToIndex(_mainEdge);
1257         if ( std::find( _revEdgesIDs.begin(), _revEdgesIDs.end(), mainID) != _revEdgesIDs.end())
1258           reversed = !reversed;
1259       }
1260     }
1261     // take into account this edge reversing
1262     if ( std::find( _revEdgesIDs.begin(), _revEdgesIDs.end(), shapeID) != _revEdgesIDs.end())
1263       reversed = !reversed;
1264
1265     BRepAdaptor_Curve C3d( E );
1266     if ( ! computeInternalParameters( theMesh, C3d, length, f, l, params, reversed, true )) {
1267       theMesh.Unlock();
1268     std::cout << "exit Compute internal failed" << std::endl;
1269
1270       return false;
1271     }
1272     redistributeNearVertices( theMesh, C3d, length, params, VFirst, VLast );
1273
1274     // edge extrema (indexes : 1 & NbPoints) already in SMDS (TopoDS_Vertex)
1275     // only internal nodes receive an edge position with param on curve
1276
1277     const SMDS_MeshNode * nPrev = nFirst;
1278     double parPrev = f;
1279     double parLast = l;
1280
1281     for (list<double>::iterator itU = params.begin(); itU != params.end(); itU++) {
1282       double param = *itU;
1283       gp_Pnt P = Curve->Value(param);
1284
1285       //Add the Node in the DataStructure
1286       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
1287       meshDS->SetNodeOnEdge(node, shapeID, param);
1288
1289       if(_quadraticMesh) {
1290         // create medium node
1291         double prm = ( parPrev + param )/2;
1292         gp_Pnt  PM = Curve->Value(prm);
1293         SMDS_MeshNode * NM = meshDS->AddNode(PM.X(), PM.Y(), PM.Z());
1294         meshDS->SetNodeOnEdge(NM, shapeID, prm);
1295         SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, node, NM);
1296         meshDS->SetMeshElementOnShape(edge, shapeID);
1297       }
1298       else {
1299         SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, node);
1300         meshDS->SetMeshElementOnShape(edge, shapeID);
1301       }
1302
1303       nPrev   = node;
1304       parPrev = param;
1305     }
1306     if(_quadraticMesh) {
1307       double prm = ( parPrev + parLast )/2;
1308       gp_Pnt PM = Curve->Value(prm);
1309       SMDS_MeshNode * NM = meshDS->AddNode(PM.X(), PM.Y(), PM.Z());
1310       meshDS->SetNodeOnEdge(NM, shapeID, prm);
1311       SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, nLast, NM);
1312       meshDS->SetMeshElementOnShape(edge, shapeID);
1313     }
1314     else {
1315       SMDS_MeshEdge* edge = meshDS->AddEdge(nPrev, nLast);
1316       meshDS->SetMeshElementOnShape(edge, shapeID);
1317     }
1318   }
1319   else
1320   {
1321     // Edge is a degenerated Edge : We put n = 5 points on the edge.
1322     const int NbPoints = 5;
1323     BRep_Tool::Range( E, f, l ); // PAL15185
1324     double du = (l - f) / (NbPoints - 1);
1325
1326     gp_Pnt P = BRep_Tool::Pnt(VFirst);
1327
1328     const SMDS_MeshNode * nPrev = nFirst;
1329     for (int i = 2; i < NbPoints; i++) {
1330       double param = f + (i - 1) * du;
1331       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
1332       if(_quadraticMesh) {
1333         // create medium node
1334         double prm = param - du/2.;
1335         SMDS_MeshNode * NM = meshDS->AddNode(P.X(), P.Y(), P.Z());
1336         meshDS->SetNodeOnEdge(NM, shapeID, prm);
1337         SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, node, NM);
1338         meshDS->SetMeshElementOnShape(edge, shapeID);
1339       }
1340       else {
1341         SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, node);
1342         meshDS->SetMeshElementOnShape(edge, shapeID);
1343       }
1344       meshDS->SetNodeOnEdge(node, shapeID, param);
1345       nPrev = node;
1346     }
1347     if(_quadraticMesh) {
1348       // create medium node
1349       double prm = l - du/2.;
1350       SMDS_MeshNode * NM = meshDS->AddNode(P.X(), P.Y(), P.Z());
1351       meshDS->SetNodeOnEdge(NM, shapeID, prm);
1352       SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, nLast, NM);
1353       meshDS->SetMeshElementOnShape(edge, shapeID);
1354     }
1355     else {
1356       SMDS_MeshEdge * edge = meshDS->AddEdge(nPrev, nLast);
1357       meshDS->SetMeshElementOnShape(edge, shapeID);
1358     }
1359   }
1360   theMesh.Unlock();
1361   std::cout << "exit normal" << std::endl;
1362
1363   return true;
1364 }
1365
1366
1367 //=============================================================================
1368 /*!
1369  *
1370  */
1371 //=============================================================================
1372
1373 bool StdMeshers_Regular_1D::Evaluate(SMESH_Mesh &         theMesh,
1374                                      const TopoDS_Shape & theShape,
1375                                      MapShapeNbElems&     theResMap)
1376 {
1377   if ( _hypType == NONE )
1378     return false;
1379
1380   if ( _hypType == ADAPTIVE )
1381   {
1382     _adaptiveHyp->GetAlgo()->InitComputeError();
1383     _adaptiveHyp->GetAlgo()->Evaluate( theMesh, theShape, theResMap );
1384     return error( _adaptiveHyp->GetAlgo()->GetComputeError() );
1385   }
1386
1387   const TopoDS_Edge & EE = TopoDS::Edge(theShape);
1388   TopoDS_Edge E = TopoDS::Edge(EE.Oriented(TopAbs_FORWARD));
1389
1390   double f, l;
1391   Handle(Geom_Curve) Curve = BRep_Tool::Curve(E, f, l);
1392
1393   TopoDS_Vertex VFirst, VLast;
1394   TopExp::Vertices(E, VFirst, VLast);   // Vfirst corresponds to f and Vlast to l
1395
1396   ASSERT(!VFirst.IsNull());
1397   ASSERT(!VLast.IsNull());
1398
1399   std::vector<smIdType> aVec(SMDSEntity_Last,0);
1400
1401   double length = EdgeLength( E );
1402   if ( !Curve.IsNull() && length > 0 )
1403   {
1404     list< double > params;
1405     BRepAdaptor_Curve C3d( E );
1406     if ( ! computeInternalParameters( theMesh, C3d, length, f, l, params, false, true )) {
1407       SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1408       theResMap.insert(std::make_pair(sm,aVec));
1409       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1410       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
1411       return false;
1412     }
1413     redistributeNearVertices( theMesh, C3d, length, params, VFirst, VLast );
1414
1415     if(_quadraticMesh) {
1416       aVec[SMDSEntity_Node     ] = 2*params.size() + 1;
1417       aVec[SMDSEntity_Quad_Edge] = params.size() + 1;
1418     }
1419     else {
1420       aVec[SMDSEntity_Node] = params.size();
1421       aVec[SMDSEntity_Edge] = params.size() + 1;
1422     }
1423
1424   }
1425   else {
1426     // Edge is a degenerated Edge : We put n = 5 points on the edge.
1427     if ( _quadraticMesh ) {
1428       aVec[SMDSEntity_Node     ] = 11;
1429       aVec[SMDSEntity_Quad_Edge] = 6;
1430     }
1431     else {
1432       aVec[SMDSEntity_Node] = 5;
1433       aVec[SMDSEntity_Edge] = 6;
1434     }
1435   }
1436
1437   SMESH_subMesh * sm = theMesh.GetSubMesh( theShape );
1438   theResMap.insert( std::make_pair( sm, aVec ));
1439
1440   return true;
1441 }
1442
1443
1444 //=============================================================================
1445 /*!
1446  *  See comments in SMESH_Algo.cxx
1447  */
1448 //=============================================================================
1449
1450 const list <const SMESHDS_Hypothesis *> &
1451 StdMeshers_Regular_1D::GetUsedHypothesis(SMESH_Mesh &         aMesh,
1452                                          const TopoDS_Shape & aShape,
1453                                          const bool           ignoreAuxiliary)
1454 {
1455   _usedHypList.clear();
1456   _mainEdge.Nullify();
1457
1458   SMESH_HypoFilter auxiliaryFilter( SMESH_HypoFilter::IsAuxiliary() );
1459   const SMESH_HypoFilter* compatibleFilter = GetCompatibleHypoFilter(/*ignoreAux=*/true );
1460
1461   // get non-auxiliary assigned directly to aShape
1462   int nbHyp = aMesh.GetHypotheses( aShape, *compatibleFilter, _usedHypList, false );
1463
1464   if (nbHyp == 0 && aShape.ShapeType() == TopAbs_EDGE)
1465   {
1466     // Check, if propagated from some other edge
1467     bool isPropagOfDistribution = false;
1468     _mainEdge = StdMeshers_Propagation::GetPropagationSource( aMesh, aShape,
1469                                                               isPropagOfDistribution );
1470     if ( !_mainEdge.IsNull() )
1471     {
1472       if ( isPropagOfDistribution )
1473         _hypType = DISTRIB_PROPAGATION;
1474       // Propagation of 1D hypothesis from <aMainEdge> on this edge;
1475       // get non-auxiliary assigned to _mainEdge
1476       nbHyp = aMesh.GetHypotheses( _mainEdge, *compatibleFilter, _usedHypList, true );
1477     }
1478   }
1479
1480   if (nbHyp == 0) // nothing propagated nor assigned to aShape
1481   {
1482     SMESH_Algo::GetUsedHypothesis( aMesh, aShape, ignoreAuxiliary );
1483     nbHyp = (int)_usedHypList.size();
1484   }
1485   else
1486   {
1487     // get auxiliary hyps from aShape
1488     aMesh.GetHypotheses( aShape, auxiliaryFilter, _usedHypList, true );
1489   }
1490   if ( nbHyp > 1 && ignoreAuxiliary )
1491     _usedHypList.clear(); //only one compatible non-auxiliary hypothesis allowed
1492
1493   return _usedHypList;
1494 }
1495
1496 //================================================================================
1497 /*!
1498  * \brief Pass CancelCompute() to a child algorithm
1499  */
1500 //================================================================================
1501
1502 void StdMeshers_Regular_1D::CancelCompute()
1503 {
1504   SMESH_Algo::CancelCompute();
1505   if ( _hypType == ADAPTIVE )
1506     _adaptiveHyp->GetAlgo()->CancelCompute();
1507 }