Salome HOME
SALOME Forum bug: http://www.salome-platform.org/forum/forum_10/967838025
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 // Copyright (C) 2007-2013  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
23 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 //  File   : SMESH_Algo.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27
28 #include "SMESH_Algo.hxx"
29
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_FacePosition.hxx"
32 #include "SMDS_MeshElement.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESHDS_SubMesh.hxx"
37 #include "SMESH_Comment.hxx"
38 #include "SMESH_Gen.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_TypeDefs.hxx"
43 #include "SMESH_subMesh.hxx"
44
45 #include <Basics_OCCTVersion.hxx>
46
47 #include <BRepAdaptor_Curve.hxx>
48 #include <BRepLProp.hxx>
49 #include <BRep_Tool.hxx>
50 #include <GCPnts_AbscissaPoint.hxx>
51 #include <GeomAdaptor_Curve.hxx>
52 #include <Geom_Surface.hxx>
53 #include <LDOMParser.hxx>
54 #include <TopExp.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <TopLoc_Location.hxx>
57 #include <TopTools_ListIteratorOfListOfShape.hxx>
58 #include <TopTools_ListOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <TopoDS_Edge.hxx>
61 #include <TopoDS_Face.hxx>
62 #include <TopoDS_Vertex.hxx>
63 #include <TopoDS_Wire.hxx>
64 #include <gp_Pnt.hxx>
65 #include <gp_Pnt2d.hxx>
66 #include <gp_Vec.hxx>
67
68 #include <Standard_ErrorHandler.hxx>
69 #include <Standard_Failure.hxx>
70
71 #include "utilities.h"
72
73 #include <algorithm>
74 #include <limits>
75 #include "SMESH_ProxyMesh.hxx"
76 #include "SMESH_MesherHelper.hxx"
77
78 using namespace std;
79
80 //================================================================================
81 /*!
82  * \brief Returns \a true if two algorithms (described by \a this and the given
83  *        algo data) are compatible by their output and input types of elements.
84  */
85 //================================================================================
86
87 bool SMESH_Algo::Features::IsCompatible( const SMESH_Algo::Features& algo2 ) const
88 {
89   if ( _dim > algo2._dim ) return algo2.IsCompatible( *this );
90   // algo2 is of highter dimension
91   if ( _outElemTypes.empty() || algo2._inElemTypes.empty() )
92     return false;
93   bool compatible = true;
94   set<SMDSAbs_GeometryType>::const_iterator myOutType = _outElemTypes.begin();
95   for ( ; myOutType != _outElemTypes.end() && compatible; ++myOutType )
96     compatible = algo2._inElemTypes.count( *myOutType );
97   return compatible;
98 }
99
100 //================================================================================
101 /*!
102  * \brief Return Data of the algorithm
103  */
104 //================================================================================
105
106 const SMESH_Algo::Features& SMESH_Algo::GetFeatures( const std::string& algoType )
107 {
108   static map< string, SMESH_Algo::Features > theFeaturesByName;
109   if ( theFeaturesByName.empty() )
110   {
111     // Read Plugin.xml files
112     vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
113     LDOMParser xmlParser;
114     for ( size_t iXML = 0; iXML < xmlPaths.size(); ++iXML )
115     {
116       bool error = xmlParser.parse( xmlPaths[iXML].c_str() );
117       if ( error )
118       {
119         TCollection_AsciiString data;
120         INFOS( xmlParser.GetError(data) );
121         continue;
122       }
123       // <algorithm type="Regular_1D"
124       //            ...
125       //            input="EDGE"
126       //            output="QUAD,TRIA">
127       //
128       LDOM_Document xmlDoc = xmlParser.getDocument();
129       LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
130       for ( int i = 0; i < algoNodeList.getLength(); ++i )
131       {
132         LDOM_Node     algoNode           = algoNodeList.item( i );
133         LDOM_Element& algoElem           = (LDOM_Element&) algoNode;
134         TCollection_AsciiString algoType = algoElem.getAttribute("type");
135         TCollection_AsciiString input    = algoElem.getAttribute("input");
136         TCollection_AsciiString output   = algoElem.getAttribute("output");
137         TCollection_AsciiString dim      = algoElem.getAttribute("dim");
138         TCollection_AsciiString label    = algoElem.getAttribute("label-id");
139         if ( algoType.IsEmpty() ) continue;
140
141         Features & data = theFeaturesByName[ algoType.ToCString() ];
142         data._dim   = dim.IntegerValue();
143         data._label = label.ToCString();
144         for ( int isInput = 0; isInput < 2; ++isInput )
145         {
146           TCollection_AsciiString&   typeStr = isInput ? input : output;
147           set<SMDSAbs_GeometryType>& typeSet = isInput ? data._inElemTypes : data._outElemTypes;
148           int beg = 1, end;
149           while ( beg <= typeStr.Length() )
150           {
151             while ( beg < typeStr.Length() && !isalpha( typeStr.Value( beg ) ))
152               ++beg;
153             end = beg;
154             while ( end < typeStr.Length() && isalpha( typeStr.Value( end + 1 ) ))
155               ++end;
156             if ( end > beg )
157             {
158               TCollection_AsciiString typeName = typeStr.SubString( beg, end );
159               if      ( typeName == "EDGE" ) typeSet.insert( SMDSGeom_EDGE );
160               else if ( typeName == "TRIA" ) typeSet.insert( SMDSGeom_TRIANGLE );
161               else if ( typeName == "QUAD" ) typeSet.insert( SMDSGeom_QUADRANGLE );
162             }
163             beg = end + 1;
164           }
165         }
166       }
167     }
168   }
169   return theFeaturesByName[ algoType ];
170 }
171
172 //=============================================================================
173 /*!
174  *  
175  */
176 //=============================================================================
177
178 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
179   : SMESH_Hypothesis(hypId, studyId, gen)
180 {
181   //gen->_mapAlgo[hypId] = this;
182
183   _onlyUnaryInput = _requireDiscreteBoundary = _requireShape = true;
184   _quadraticMesh = _supportSubmeshes = false;
185   _error = COMPERR_OK;
186   for ( int i = 0; i < 4; ++i )
187     _neededLowerHyps[ i ] = false;
188 }
189
190 //=============================================================================
191 /*!
192  *  
193  */
194 //=============================================================================
195
196 SMESH_Algo::~SMESH_Algo()
197 {
198 }
199
200 //=============================================================================
201 /*!
202  *  
203  */
204 //=============================================================================
205
206 SMESH_0D_Algo::SMESH_0D_Algo(int hypId, int studyId, SMESH_Gen* gen)
207   : SMESH_Algo(hypId, studyId, gen)
208 {
209   _shapeType = (1 << TopAbs_VERTEX);
210   _type = ALGO_0D;
211   //gen->_map0D_Algo[hypId] = this;
212 }
213 SMESH_1D_Algo::SMESH_1D_Algo(int hypId, int studyId, SMESH_Gen* gen)
214   : SMESH_Algo(hypId, studyId, gen)
215 {
216   _shapeType = (1 << TopAbs_EDGE);
217   _type = ALGO_1D;
218   //gen->_map1D_Algo[hypId] = this;
219 }
220 SMESH_2D_Algo::SMESH_2D_Algo(int hypId, int studyId, SMESH_Gen* gen)
221   : SMESH_Algo(hypId, studyId, gen)
222 {
223   _shapeType = (1 << TopAbs_FACE);
224   _type = ALGO_2D;
225   //gen->_map2D_Algo[hypId] = this;
226 }
227 SMESH_3D_Algo::SMESH_3D_Algo(int hypId, int studyId, SMESH_Gen* gen)
228   : SMESH_Algo(hypId, studyId, gen)
229 {
230   _shapeType = (1 << TopAbs_SOLID);
231   _type = ALGO_3D;
232   //gen->_map3D_Algo[hypId] = this;
233 }
234
235 //=============================================================================
236 /*!
237  * Usually an algoritm has nothing to save
238  */
239 //=============================================================================
240
241 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
242 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
243
244 //=============================================================================
245 /*!
246  *  
247  */
248 //=============================================================================
249
250 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
251 {
252   return _compatibleHypothesis;
253 }
254
255 //=============================================================================
256 /*!
257  *  List the hypothesis used by the algorithm associated to the shape.
258  *  Hypothesis associated to father shape -are- taken into account (see
259  *  GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
260  *  the algorithm. This method could be surcharged by specific algorithms, in 
261  *  case of several hypothesis simultaneously applicable.
262  */
263 //=============================================================================
264
265 const list <const SMESHDS_Hypothesis *> &
266 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh &         aMesh,
267                               const TopoDS_Shape & aShape,
268                               const bool           ignoreAuxiliary) const
269 {
270   SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
271   me->_usedHypList.clear();
272   SMESH_HypoFilter filter;
273   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
274   {
275     aMesh.GetHypotheses( aShape, filter, me->_usedHypList, true );
276     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
277       me->_usedHypList.clear(); //only one compatible hypothesis allowed
278   }
279   return _usedHypList;
280 }
281
282 //=============================================================================
283 /*!
284  *  List the relevant hypothesis associated to the shape. Relevant hypothesis
285  *  have a name (type) listed in the algorithm. Hypothesis associated to
286  *  father shape -are not- taken into account (see GetUsedHypothesis)
287  */
288 //=============================================================================
289
290 const list<const SMESHDS_Hypothesis *> &
291 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh &         aMesh,
292                                  const TopoDS_Shape & aShape,
293                                  const bool           ignoreAuxiliary) const
294 {
295   SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
296   me->_appliedHypList.clear();
297   SMESH_HypoFilter filter;
298   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
299     aMesh.GetHypotheses( aShape, filter, me->_appliedHypList, false );
300
301   return _appliedHypList;
302 }
303
304 //=============================================================================
305 /*!
306  *  Compute length of an edge
307  */
308 //=============================================================================
309
310 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
311 {
312   double UMin = 0, UMax = 0;
313   TopLoc_Location L;
314   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
315   if ( C.IsNull() )
316     return 0.;
317   GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
318   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
319   return length;
320 }
321
322 //================================================================================
323 /*!
324  * \brief Just return false as the algorithm does not hold parameters values
325  */
326 //================================================================================
327
328 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
329                                      const TopoDS_Shape& /*theShape*/)
330 {
331   return false;
332 }
333 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
334 {
335   return false;
336 }
337 //================================================================================
338 /*!
339  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
340  * \param theMesh - The mesh containing nodes
341  * \param theEdge - The geometrical edge of interest
342  * \param theParams - The resulting vector of sorted node parameters
343  * \retval bool - false if not all parameters are OK
344  */
345 //================================================================================
346
347 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
348                                     const TopoDS_Edge&  theEdge,
349                                     vector< double > &  theParams)
350 {
351   theParams.clear();
352
353   if ( !theMesh || theEdge.IsNull() )
354     return false;
355
356   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
357   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
358     return false; // edge is not meshed
359
360   //int nbEdgeNodes = 0;
361   set < double > paramSet;
362   if ( eSubMesh )
363   {
364     // loop on nodes of an edge: sort them by param on edge
365     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
366     while ( nIt->more() )
367     {
368       const SMDS_MeshNode* node = nIt->next();
369       const SMDS_PositionPtr& pos = node->GetPosition();
370       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
371         return false;
372       const SMDS_EdgePosition* epos =
373         static_cast<const SMDS_EdgePosition*>(node->GetPosition());
374       if ( !paramSet.insert( epos->GetUParameter() ).second )
375         return false; // equal parameters
376     }
377   }
378   // add vertex nodes params
379   TopoDS_Vertex V1,V2;
380   TopExp::Vertices( theEdge, V1, V2);
381   if ( VertexNode( V1, theMesh ) &&
382        !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
383     return false; // there are equal parameters
384   if ( VertexNode( V2, theMesh ) &&
385        !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
386     return false; // there are equal parameters
387
388   // fill the vector
389   theParams.resize( paramSet.size() );
390   set < double >::iterator   par    = paramSet.begin();
391   vector< double >::iterator vecPar = theParams.begin();
392   for ( ; par != paramSet.end(); ++par, ++vecPar )
393     *vecPar = *par;
394
395   return theParams.size() > 1;
396 }
397
398 //================================================================================
399 /*!
400  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
401  * \param theMesh - The mesh containing nodes
402  * \param theEdge - The geometrical edge of interest
403  * \param theParams - The resulting vector of sorted node parameters
404  * \retval bool - false if not all parameters are OK
405  */
406 //================================================================================
407
408 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
409                                       const TopoDS_Edge&                    theEdge,
410                                       const bool                            ignoreMediumNodes,
411                                       map< double, const SMDS_MeshNode* > & theNodes)
412 {
413   theNodes.clear();
414
415   if ( !theMesh || theEdge.IsNull() )
416     return false;
417
418   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
419   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
420     return false; // edge is not meshed
421
422   int nbNodes = 0;
423   set < double > paramSet;
424   if ( eSubMesh )
425   {
426     // loop on nodes of an edge: sort them by param on edge
427     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
428     while ( nIt->more() )
429     {
430       const SMDS_MeshNode* node = nIt->next();
431       if ( ignoreMediumNodes ) {
432         SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
433         if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
434           continue;
435       }
436       const SMDS_PositionPtr& pos = node->GetPosition();
437       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
438         return false;
439       const SMDS_EdgePosition* epos =
440         static_cast<const SMDS_EdgePosition*>(node->GetPosition());
441       theNodes.insert( theNodes.end(), make_pair( epos->GetUParameter(), node ));
442       //MESSAGE("U " << epos->GetUParameter() << " ID " << node->GetID());
443       ++nbNodes;
444     }
445   }
446   // add vertex nodes
447   TopoDS_Vertex v1, v2;
448   TopExp::Vertices(theEdge, v1, v2);
449   const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
450   const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
451   //MESSAGE("Vertices ID " << n1->GetID() << " " << n2->GetID());
452   Standard_Real f, l;
453   BRep_Tool::Range(theEdge, f, l);
454   if ( v1.Orientation() != TopAbs_FORWARD )
455     std::swap( f, l );
456   if ( n1 && ++nbNodes )
457     theNodes.insert( make_pair( f, n1 ));
458   if ( n2 && ++nbNodes )
459     theNodes.insert( make_pair( l, n2 ));
460
461   return theNodes.size() == nbNodes;
462 }
463
464 //================================================================================
465 /*!
466  * \brief Make filter recognize only compatible hypotheses
467  * \param theFilter - the filter to initialize
468  * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
469  */
470 //================================================================================
471
472 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
473                                            const bool         ignoreAuxiliary) const
474 {
475   if ( !_compatibleHypothesis.empty() )
476   {
477     theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
478     for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
479       theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
480
481     if ( ignoreAuxiliary )
482       theFilter.AndNot( theFilter.IsAuxiliary() );
483
484     return true;
485   }
486   return false;
487 }
488
489 //================================================================================
490 /*!
491  * \brief Return continuity of two edges
492  * \param E1 - the 1st edge
493  * \param E2 - the 2nd edge
494  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
495  */
496 //================================================================================
497
498 GeomAbs_Shape SMESH_Algo::Continuity(TopoDS_Edge E1,
499                                      TopoDS_Edge E2)
500 {
501   //E1.Orientation(TopAbs_FORWARD), E2.Orientation(TopAbs_FORWARD); // avoid pb with internal edges
502   if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
503     E1.Orientation( TopAbs_FORWARD );
504   if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
505     E2.Orientation( TopAbs_FORWARD );
506
507   TopoDS_Vertex V, VV1[2], VV2[2];
508   TopExp::Vertices( E1, VV1[0], VV1[1], true );
509   TopExp::Vertices( E2, VV2[0], VV2[1], true );
510   if      ( VV1[1].IsSame( VV2[0] ))  { V = VV1[1]; }
511   else if ( VV1[0].IsSame( VV2[1] ))  { V = VV1[0]; }
512   else if ( VV1[1].IsSame( VV2[1] ))  { V = VV1[1]; E1.Reverse(); }
513   else if ( VV1[0].IsSame( VV2[0] ))  { V = VV1[0]; E1.Reverse(); }
514   else { return GeomAbs_C0; }
515
516   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
517   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
518   BRepAdaptor_Curve C1( E1 ), C2( E2 );
519   Standard_Real tol = BRep_Tool::Tolerance( V );
520   Standard_Real angTol = 2e-3;
521   try {
522 #if OCC_VERSION_LARGE > 0x06010000
523     OCC_CATCH_SIGNALS;
524 #endif
525     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
526   }
527   catch (Standard_Failure) {
528   }
529   return GeomAbs_C0;
530 }
531
532 //================================================================================
533 /*!
534  * \brief Return true if an edge can be considered straight
535  */
536 //================================================================================
537
538 bool SMESH_Algo::isStraight( const TopoDS_Edge & E,
539                              const bool          degenResult)
540 {
541   {
542     double f,l;
543     if ( BRep_Tool::Curve( E, f, l ).IsNull())
544       return degenResult;
545   }
546   BRepAdaptor_Curve curve( E );
547   switch( curve.GetType() )
548   {
549   case GeomAbs_Line:
550     return true;
551   case GeomAbs_Circle:
552   case GeomAbs_Ellipse:
553   case GeomAbs_Hyperbola:
554   case GeomAbs_Parabola:
555     return false;
556   // case GeomAbs_BezierCurve:
557   // case GeomAbs_BSplineCurve:
558   // case GeomAbs_OtherCurve:
559   default:;
560   }
561   const double   f = curve.FirstParameter();
562   const double   l = curve.LastParameter();
563   const gp_Pnt  pf = curve.Value( f );
564   const gp_Pnt  pl = curve.Value( l );
565   const gp_Vec v1( pf, pl );
566   const double v1Len = v1.Magnitude();
567   if ( v1Len < std::numeric_limits< double >::min() )
568     return false; // E seems closed
569   const double tol = Min( 10 * curve.Tolerance(), v1Len * 1e-2 );
570   const int nbSamples = 7;
571   for ( int i = 0; i < nbSamples; ++i )
572   {
573     const double  r = ( i + 1 ) / nbSamples;
574     const gp_Pnt pi = curve.Value( f * r + l * ( 1 - r ));
575     const gp_Vec vi( pf, pi );
576     const double  h = 0.5 * v1.Crossed( vi ).Magnitude() / v1Len;
577     if ( h > tol )
578       return false;
579   }
580   return true;
581 }
582
583 //================================================================================
584 /*!
585  * \brief Return true if an edge has no 3D curve
586  */
587 //================================================================================
588
589 bool SMESH_Algo::isDegenerated( const TopoDS_Edge & E )
590 {
591   double f,l;
592   TopLoc_Location loc;
593   Handle(Geom_Curve) C = BRep_Tool::Curve( E, loc, f,l );
594   return C.IsNull();
595 }
596
597 //================================================================================
598 /*!
599  * \brief Return the node built on a vertex
600  * \param V - the vertex
601  * \param meshDS - mesh
602  * \retval const SMDS_MeshNode* - found node or NULL
603  */
604 //================================================================================
605
606 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
607                                             const SMESHDS_Mesh*  meshDS)
608 {
609   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
610     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
611     if (nIt->more())
612       return nIt->next();
613   }
614   return 0;
615 }
616
617 //=======================================================================
618 //function : GetMeshError
619 //purpose  : Finds topological errors of a sub-mesh
620 //WARNING  : 1D check is NOT implemented so far
621 //=======================================================================
622
623 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
624 {
625   EMeshError err = MEr_OK;
626
627   SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
628   if ( !smDS )
629     return MEr_EMPTY;
630
631   switch ( subMesh->GetSubShape().ShapeType() )
632   {
633   case TopAbs_FACE: { // ====================== 2D =====================
634
635     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
636     if ( !fIt->more() )
637       return MEr_EMPTY;
638
639     // We check that olny links on EDGEs encouter once, the rest links, twice
640     set< SMESH_TLink > links;
641     while ( fIt->more() )
642     {
643       const SMDS_MeshElement* f = fIt->next();
644       int nbNodes = f->NbCornerNodes(); // ignore medium nodes
645       for ( int i = 0; i < nbNodes; ++i )
646       {
647         const SMDS_MeshNode* n1 = f->GetNode( i );
648         const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
649         std::pair< set< SMESH_TLink >::iterator, bool > it_added =
650           links.insert( SMESH_TLink( n1, n2 ));
651         if ( !it_added.second )
652           // As we do NOT(!) check if mesh is manifold, we believe that a link can
653           // encounter once or twice only (not three times), we erase a link as soon
654           // as it encounters twice to speed up search in the <links> map.
655           links.erase( it_added.first );
656       }
657     }
658     // the links remaining in the <links> should all be on EDGE
659     set< SMESH_TLink >::iterator linkIt = links.begin();
660     for ( ; linkIt != links.end(); ++linkIt )
661     {
662       const SMESH_TLink& link = *linkIt;
663       if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
664            link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
665         return MEr_HOLES;
666     }
667     // TODO: to check orientation
668     break;
669   }
670   case TopAbs_SOLID: { // ====================== 3D =====================
671
672     SMDS_ElemIteratorPtr vIt = smDS->GetElements();
673     if ( !vIt->more() )
674       return MEr_EMPTY;
675
676     SMDS_VolumeTool vTool;
677     while ( !vIt->more() )
678     {
679       if (!vTool.Set( vIt->next() ))
680         continue; // strange
681
682       for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
683         if ( vTool.IsFreeFace( iF ))
684         {
685           int nbN = vTool.NbFaceNodes( iF );
686           const SMDS_MeshNode** nodes =  vTool.GetFaceNodes( iF );
687           for ( int i = 0; i < nbN; ++i )
688             if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
689               return MEr_HOLES;
690         }
691     }
692     break;
693   }
694   default:;
695   }
696   return err;
697 }
698
699 //================================================================================
700 /*!
701  * \brief Sets event listener to submeshes if necessary
702  * \param subMesh - submesh where algo is set
703  * 
704  * After being set, event listener is notified on each event of a submesh.
705  * By default non listener is set
706  */
707 //================================================================================
708
709 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
710 {
711 }
712
713 //================================================================================
714 /*!
715  * \brief Allow algo to do something after persistent restoration
716  * \param subMesh - restored submesh
717  *
718  * This method is called only if a submesh has HYP_OK algo_state.
719  */
720 //================================================================================
721
722 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
723 {
724 }
725
726 //================================================================================
727 /*!
728  * \brief Computes mesh without geometry
729  * \param aMesh - the mesh
730  * \param aHelper - helper that must be used for adding elements to \aaMesh
731  * \retval bool - is a success
732  */
733 //================================================================================
734
735 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
736 {
737   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
738 }
739
740 //=======================================================================
741 //function : CancelCompute
742 //purpose  : Sets _computeCanceled to true. It's usage depends on
743 //  *        implementation of a particular mesher.
744 //=======================================================================
745
746 void SMESH_Algo::CancelCompute()
747 {
748   _computeCanceled = true;
749   _error = COMPERR_CANCELED;
750 }
751
752 //================================================================================
753 /*
754  * If possible, returns progress of computation [0.,1.]
755  */
756 //================================================================================
757
758 double SMESH_Algo::GetProgress() const
759 {
760   return _progress;
761 }
762
763 //================================================================================
764 /*!
765  * \brief store error and comment and then return ( error == COMPERR_OK )
766  */
767 //================================================================================
768
769 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
770 {
771   _error   = error;
772   _comment = comment;
773   return ( error == COMPERR_OK );
774 }
775
776 //================================================================================
777 /*!
778  * \brief store error and return ( error == COMPERR_OK )
779  */
780 //================================================================================
781
782 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
783 {
784   if ( error ) {
785     _error   = error->myName;
786     _comment = error->myComment;
787     _badInputElements = error->myBadElements;
788     return error->IsOK();
789   }
790   return true;
791 }
792
793 //================================================================================
794 /*!
795  * \brief return compute error
796  */
797 //================================================================================
798
799 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
800 {
801   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
802   // hope this method is called by only SMESH_subMesh after this->Compute()
803   err->myBadElements.splice( err->myBadElements.end(),
804                              (list<const SMDS_MeshElement*>&) _badInputElements );
805   return err;
806 }
807
808 //================================================================================
809 /*!
810  * \brief initialize compute error before call of Compute()
811  */
812 //================================================================================
813
814 void SMESH_Algo::InitComputeError()
815 {
816   _error = COMPERR_OK;
817   _comment.clear();
818   list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
819   for ( ; elem != _badInputElements.end(); ++elem )
820     if ( (*elem)->GetID() < 1 )
821       delete *elem;
822   _badInputElements.clear();
823
824   _computeCanceled = false;
825   _progressTic     = 0;
826   _progress        = 0.;
827 }
828
829 //================================================================================
830 /*!
831  * \brief Return compute progress by nb of calls of this method
832  */
833 //================================================================================
834
835 double SMESH_Algo::GetProgressByTic() const
836 {
837   int computeCost = 0;
838   for ( size_t i = 0; i < _smToCompute.size(); ++i )
839     computeCost += _smToCompute[i]->GetComputeCost();
840
841   const_cast<SMESH_Algo*>( this )->_progressTic++;
842
843   double x = 5 * _progressTic;
844   x = ( x < computeCost ) ? ( x / computeCost ) : 1.;
845   return 0.9 * sin( x * M_PI / 2 );
846 }
847
848 //================================================================================
849 /*!
850  * \brief store a bad input element preventing computation,
851  *        which may be a temporary one i.e. not residing the mesh,
852  *        then it will be deleted by InitComputeError()
853  */
854 //================================================================================
855
856 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
857 {
858   if ( elem )
859     _badInputElements.push_back( elem );
860 }
861
862 //=======================================================================
863 //function : addBadInputElements
864 //purpose  : store a bad input elements or nodes preventing computation
865 //=======================================================================
866
867 void SMESH_Algo::addBadInputElements(const SMESHDS_SubMesh* sm,
868                                      const bool             addNodes)
869 {
870   if ( sm )
871   {
872     if ( addNodes )
873     {
874       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
875       while ( nIt->more() ) addBadInputElement( nIt->next() );
876     }
877     else
878     {
879       SMDS_ElemIteratorPtr eIt = sm->GetElements();
880       while ( eIt->more() ) addBadInputElement( eIt->next() );
881     }
882   }
883 }
884
885 //=============================================================================
886 /*!
887  *  
888  */
889 //=============================================================================
890
891 // int SMESH_Algo::NumberOfWires(const TopoDS_Shape& S)
892 // {
893 //   int i = 0;
894 //   for (TopExp_Explorer exp(S,TopAbs_WIRE); exp.More(); exp.Next())
895 //     i++;
896 //   return i;
897 // }
898
899 //=============================================================================
900 /*!
901  *  
902  */
903 //=============================================================================
904
905 int SMESH_Algo::NumberOfPoints(SMESH_Mesh& aMesh, const TopoDS_Wire& W)
906 {
907   int nbPoints = 0;
908   for (TopExp_Explorer exp(W,TopAbs_EDGE); exp.More(); exp.Next()) {
909     const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
910     int nb = aMesh.GetSubMesh(E)->GetSubMeshDS()->NbNodes();
911     if(_quadraticMesh)
912       nb = nb/2;
913     nbPoints += nb + 1; // internal points plus 1 vertex of 2 (last point ?)
914   }
915   return nbPoints;
916 }
917
918
919 //================================================================================
920 /*!
921  * Method in which an algorithm generating a structured mesh
922  * fixes positions of in-face nodes after there movement
923  * due to insertion of viscous layers.
924  */
925 //================================================================================
926
927 bool SMESH_2D_Algo::FixInternalNodes(const SMESH_ProxyMesh& mesh,
928                                      const TopoDS_Face&     face)
929 {
930   const SMESHDS_SubMesh* smDS = mesh.GetSubMesh(face);
931   if ( !smDS || smDS->NbElements() < 1 )
932     return false;
933
934   SMESH_MesherHelper helper( *mesh.GetMesh() );
935
936   // get all faces from a proxy sub-mesh
937   typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TIterator;
938   TIDSortedElemSet allFaces( TIterator( smDS->GetElements() ), TIterator() );
939   TIDSortedElemSet avoidSet, firstRowQuads;
940
941   // indices of nodes to pass to a neighbour quad using SMESH_MeshAlgos::FindFaceInSet()
942   int iN1, iN2;
943
944   // get two first rows of nodes by passing through the first row of faces
945   vector< vector< const SMDS_MeshNode* > > nodeRows;
946   int iRow1 = 0, iRow2 = 1;
947   const SMDS_MeshElement* quad;
948   {
949     // look for a corner quadrangle and it's corner node
950     const SMDS_MeshElement* cornerQuad = 0;
951     int                     cornerNodeInd = -1;
952     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
953     while ( !cornerQuad && fIt->more() )
954     {
955       cornerQuad = fIt->next();
956       if ( cornerQuad->NbCornerNodes() != 4 )
957         return false;
958       SMDS_NodeIteratorPtr nIt = cornerQuad->nodeIterator();
959       for ( int i = 0; i < 4; ++i )
960       {
961         int nbInverseQuads = 0;
962         SMDS_ElemIteratorPtr fIt = nIt->next()->GetInverseElementIterator(SMDSAbs_Face);
963         while ( fIt->more() )
964           nbInverseQuads += allFaces.count( fIt->next() );
965         if ( nbInverseQuads == 1 )
966           cornerNodeInd = i, i = 4;
967       }
968       if ( cornerNodeInd < 0 )
969         cornerQuad = 0;
970     }
971     if ( !cornerQuad || cornerNodeInd < 0 )
972       return false;
973
974     iN1     = helper.WrapIndex( cornerNodeInd + 1, 4 );
975     iN2     = helper.WrapIndex( cornerNodeInd + 2, 4 );
976     int iN3 = helper.WrapIndex( cornerNodeInd + 3, 4 );
977     nodeRows.resize(2);
978     nodeRows[iRow1].push_back( cornerQuad->GetNode( cornerNodeInd ));
979     nodeRows[iRow1].push_back( cornerQuad->GetNode( iN1 ));
980     nodeRows[iRow2].push_back( cornerQuad->GetNode( iN3 ));
981     nodeRows[iRow2].push_back( cornerQuad->GetNode( iN2 ));
982     firstRowQuads.insert( cornerQuad );
983
984     // pass through the rest quads in a face row
985     quad = cornerQuad;
986     while ( quad )
987     {
988       avoidSet.clear();
989       avoidSet.insert( quad );
990       if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1].back(),
991                                                    nodeRows[iRow2].back(),
992                                                    allFaces, avoidSet, &iN1, &iN2)))
993       {
994         nodeRows[iRow1].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
995         nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
996         if ( quad->NbCornerNodes() != 4 )
997           return false;
998       }
999     }
1000     if ( nodeRows[iRow1].size() < 3 )
1001       return true; // there is nothing to fix
1002   }
1003
1004   nodeRows.reserve( smDS->NbElements() / nodeRows[iRow1].size() );
1005
1006   // get the rest node rows
1007   while ( true )
1008   {
1009     ++iRow1, ++iRow2;
1010
1011     // get the first quad in the next face row 
1012     if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][0],
1013                                                  nodeRows[iRow1][1],
1014                                                  allFaces, /*avoid=*/firstRowQuads,
1015                                                  &iN1, &iN2)))
1016     {
1017       if ( quad->NbCornerNodes() != 4 )
1018         return false;
1019       nodeRows.resize( iRow2+1 );
1020       nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1021       nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1022       firstRowQuads.insert( quad );
1023     }
1024     else
1025     {
1026       break; // no more rows
1027     }
1028
1029     // pass through the rest quads in a face row
1030     while ( quad )
1031     {
1032       avoidSet.clear();
1033       avoidSet.insert( quad );
1034       if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][ nodeRows[iRow2].size()-1 ],
1035                                                    nodeRows[iRow2].back(),
1036                                                    allFaces, avoidSet, &iN1, &iN2)))
1037       {
1038         if ( quad->NbCornerNodes() != 4 )
1039           return false;
1040         nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1041       }
1042     }
1043     if ( nodeRows[iRow1].size() != nodeRows[iRow2].size() )
1044       return false;
1045   }
1046   if ( nodeRows.size() < 3 )
1047     return true; // there is nothing to fix
1048
1049   // get params of the first (bottom) and last (top) node rows
1050   UVPtStructVec uvB( nodeRows[0].size() ), uvT( nodeRows[0].size() );
1051   for ( int isBot = 0; isBot < 2; ++isBot )
1052   {
1053     UVPtStructVec &                  uvps = isBot ? uvB : uvT;
1054     vector< const SMDS_MeshNode* >& nodes = nodeRows[ isBot ? 0 : nodeRows.size()-1 ];
1055     for ( size_t i = 0; i < nodes.size(); ++i )
1056     {
1057       uvps[i].node = nodes[i];
1058       gp_XY uv = helper.GetNodeUV( face, uvps[i].node );
1059       uvps[i].u = uv.Coord(1);
1060       uvps[i].v = uv.Coord(2);
1061       uvps[i].x = 0;
1062     }
1063     // calculate x (normalized param)
1064     for ( size_t i = 1; i < nodes.size(); ++i )
1065       uvps[i].x = uvps[i-1].x + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1066     for ( size_t i = 1; i < nodes.size(); ++i )
1067       uvps[i].x /= uvps.back().x;
1068   }
1069
1070   // get params of the left and right node rows
1071   UVPtStructVec uvL( nodeRows.size() ), uvR( nodeRows.size() );
1072   for ( int isLeft = 0; isLeft < 2; ++isLeft )
1073   {
1074     UVPtStructVec & uvps = isLeft ? uvL : uvR;
1075     const int       iCol = isLeft ? 0 : nodeRows[0].size() - 1;
1076     for ( size_t i = 0; i < nodeRows.size(); ++i )
1077     {
1078       uvps[i].node = nodeRows[i][iCol];
1079       gp_XY uv = helper.GetNodeUV( face, uvps[i].node );
1080       uvps[i].u = uv.Coord(1);
1081       uvps[i].v = uv.Coord(2);
1082       uvps[i].y = 0;
1083     }
1084     // calculate y (normalized param)
1085     for ( size_t i = 1; i < nodeRows.size(); ++i )
1086       uvps[i].y = uvps[i-1].y + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1087     for ( size_t i = 1; i < nodeRows.size(); ++i )
1088       uvps[i].y /= uvps.back().y;
1089   }
1090
1091   // update node coordinates
1092   SMESHDS_Mesh*   meshDS = mesh.GetMeshDS();
1093   Handle(Geom_Surface) S = BRep_Tool::Surface( face );
1094   gp_XY a0 ( uvB.front().u, uvB.front().v );
1095   gp_XY a1 ( uvB.back().u,  uvB.back().v );
1096   gp_XY a2 ( uvT.back().u,  uvT.back().v );
1097   gp_XY a3 ( uvT.front().u, uvT.front().v );
1098   for ( size_t iRow = 1; iRow < nodeRows.size()-1; ++iRow )
1099   {
1100     gp_XY p1 ( uvR[ iRow ].u, uvR[ iRow ].v );
1101     gp_XY p3 ( uvL[ iRow ].u, uvL[ iRow ].v );
1102     const double y0 = uvL[ iRow ].y;
1103     const double y1 = uvR[ iRow ].y;
1104     for ( size_t iCol = 1; iCol < nodeRows[0].size()-1; ++iCol )
1105     {
1106       gp_XY p0 ( uvB[ iCol ].u, uvB[ iCol ].v );
1107       gp_XY p2 ( uvT[ iCol ].u, uvT[ iCol ].v );
1108       const double x0 = uvB[ iCol ].x;
1109       const double x1 = uvT[ iCol ].x;
1110       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1111       double y = y0 + x * (y1 - y0);
1112       gp_XY uv = helper.calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
1113       gp_Pnt p = S->Value( uv.Coord(1), uv.Coord(2));
1114       const SMDS_MeshNode* n = nodeRows[iRow][iCol];
1115       meshDS->MoveNode( n, p.X(), p.Y(), p.Z() );
1116       if ( SMDS_FacePosition* pos = dynamic_cast< SMDS_FacePosition*>( n->GetPosition() ))
1117         pos->SetParameters( uv.Coord(1), uv.Coord(2) );
1118     }
1119   }
1120   return true;
1121 }