Salome HOME
PR: synchro V7_main tag mergefrom_V6_main_28Feb13
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 // Copyright (C) 2007-2012  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_TypeDefs.hxx"
42 #include "SMESH_subMesh.hxx"
43
44 #include <Basics_OCCTVersion.hxx>
45
46 #include <BRepAdaptor_Curve.hxx>
47 #include <BRepLProp.hxx>
48 #include <BRep_Tool.hxx>
49 #include <GCPnts_AbscissaPoint.hxx>
50 #include <GeomAdaptor_Curve.hxx>
51 #include <Geom_Surface.hxx>
52 #include <LDOMParser.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopLoc_Location.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <TopTools_ListOfShape.hxx>
58 #include <TopoDS.hxx>
59 #include <TopoDS_Edge.hxx>
60 #include <TopoDS_Face.hxx>
61 #include <TopoDS_Vertex.hxx>
62 #include <TopoDS_Wire.hxx>
63 #include <gp_Pnt.hxx>
64 #include <gp_Pnt2d.hxx>
65 #include <gp_Vec.hxx>
66
67 #include <Standard_ErrorHandler.hxx>
68 #include <Standard_Failure.hxx>
69
70 #include "utilities.h"
71
72 #include <algorithm>
73 #include <limits>
74
75 using namespace std;
76
77 //================================================================================
78 /*!
79  * \brief Returns \a true if two algorithms (described by \a this and the given
80  *        algo data) are compatible by their output and input types of elements.
81  */
82 //================================================================================
83
84 bool SMESH_Algo::Features::IsCompatible( const SMESH_Algo::Features& algo2 ) const
85 {
86   if ( _dim > algo2._dim ) return algo2.IsCompatible( *this );
87   // algo2 is of highter dimension
88   if ( _outElemTypes.empty() || algo2._inElemTypes.empty() )
89     return false;
90   bool compatible = true;
91   set<SMDSAbs_GeometryType>::const_iterator myOutType = _outElemTypes.begin();
92   for ( ; myOutType != _outElemTypes.end() && compatible; ++myOutType )
93     compatible = algo2._inElemTypes.count( *myOutType );
94   return compatible;
95 }
96
97 //================================================================================
98 /*!
99  * \brief Return Data of the algorithm
100  */
101 //================================================================================
102
103 const SMESH_Algo::Features& SMESH_Algo::GetFeatures( const std::string& algoType )
104 {
105   static map< string, SMESH_Algo::Features > theFeaturesByName;
106   if ( theFeaturesByName.empty() )
107   {
108     // Read Plugin.xml files
109     vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
110     LDOMParser xmlParser;
111     for ( size_t iXML = 0; iXML < xmlPaths.size(); ++iXML )
112     {
113       bool error = xmlParser.parse( xmlPaths[iXML].c_str() );
114       if ( error )
115       {
116         TCollection_AsciiString data;
117         INFOS( xmlParser.GetError(data) );
118         continue;
119       }
120       // <algorithm type="Regular_1D"
121       //            ...
122       //            input="EDGE"
123       //            output="QUAD,TRIA">
124       //
125       LDOM_Document xmlDoc = xmlParser.getDocument();
126       LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
127       for ( int i = 0; i < algoNodeList.getLength(); ++i )
128       {
129         LDOM_Node     algoNode           = algoNodeList.item( i );
130         LDOM_Element& algoElem           = (LDOM_Element&) algoNode;
131         TCollection_AsciiString algoType = algoElem.getAttribute("type");
132         TCollection_AsciiString input    = algoElem.getAttribute("input");
133         TCollection_AsciiString output   = algoElem.getAttribute("output");
134         TCollection_AsciiString dim      = algoElem.getAttribute("dim");
135         TCollection_AsciiString label    = algoElem.getAttribute("label-id");
136         if ( algoType.IsEmpty() ) continue;
137
138         Features & data = theFeaturesByName[ algoType.ToCString() ];
139         data._dim   = dim.IntegerValue();
140         data._label = label.ToCString();
141         for ( int isInput = 0; isInput < 2; ++isInput )
142         {
143           TCollection_AsciiString&   typeStr = isInput ? input : output;
144           set<SMDSAbs_GeometryType>& typeSet = isInput ? data._inElemTypes : data._outElemTypes;
145           int beg = 1, end;
146           while ( beg <= typeStr.Length() )
147           {
148             while ( beg < typeStr.Length() && !isalpha( typeStr.Value( beg ) ))
149               ++beg;
150             end = beg;
151             while ( end < typeStr.Length() && isalpha( typeStr.Value( end + 1 ) ))
152               ++end;
153             if ( end > beg )
154             {
155               TCollection_AsciiString typeName = typeStr.SubString( beg, end );
156               if      ( typeName == "EDGE" ) typeSet.insert( SMDSGeom_EDGE );
157               else if ( typeName == "TRIA" ) typeSet.insert( SMDSGeom_TRIANGLE );
158               else if ( typeName == "QUAD" ) typeSet.insert( SMDSGeom_QUADRANGLE );
159             }
160             beg = end + 1;
161           }
162         }
163       }
164     }
165   }
166   return theFeaturesByName[ algoType ];
167 }
168
169 //=============================================================================
170 /*!
171  *  
172  */
173 //=============================================================================
174
175 SMESH_Algo::SMESH_Algo (int hypId, int studyId, SMESH_Gen * gen)
176   : SMESH_Hypothesis(hypId, studyId, gen)
177 {
178   gen->_mapAlgo[hypId] = this;
179
180   _onlyUnaryInput = _requireDiscreteBoundary = _requireShape = true;
181   _quadraticMesh = _supportSubmeshes = false;
182   _error = COMPERR_OK;
183   for ( int i = 0; i < 4; ++i )
184     _neededLowerHyps[ i ] = false;
185 }
186
187 //=============================================================================
188 /*!
189  *  
190  */
191 //=============================================================================
192
193 SMESH_Algo::~SMESH_Algo()
194 {
195 }
196
197 //=============================================================================
198 /*!
199  *  
200  */
201 //=============================================================================
202
203 SMESH_0D_Algo::SMESH_0D_Algo(int hypId, int studyId, SMESH_Gen* gen)
204   : SMESH_Algo(hypId, studyId, gen)
205 {
206   _shapeType = (1 << TopAbs_VERTEX);
207   _type = ALGO_0D;
208   gen->_map0D_Algo[hypId] = this;
209 }
210 SMESH_1D_Algo::SMESH_1D_Algo(int hypId, int studyId, SMESH_Gen* gen)
211   : SMESH_Algo(hypId, studyId, gen)
212 {
213   _shapeType = (1 << TopAbs_EDGE);
214   _type = ALGO_1D;
215   gen->_map1D_Algo[hypId] = this;
216 }
217 SMESH_2D_Algo::SMESH_2D_Algo(int hypId, int studyId, SMESH_Gen* gen)
218   : SMESH_Algo(hypId, studyId, gen)
219 {
220   _shapeType = (1 << TopAbs_FACE);
221   _type = ALGO_2D;
222   gen->_map2D_Algo[hypId] = this;
223 }
224 SMESH_3D_Algo::SMESH_3D_Algo(int hypId, int studyId, SMESH_Gen* gen)
225   : SMESH_Algo(hypId, studyId, gen)
226 {
227   _shapeType = (1 << TopAbs_SOLID);
228   _type = ALGO_3D;
229   gen->_map3D_Algo[hypId] = this;
230 }
231
232 //=============================================================================
233 /*!
234  * Usually an algoritm has nothing to save
235  */
236 //=============================================================================
237
238 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
239 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
240
241 //=============================================================================
242 /*!
243  *  
244  */
245 //=============================================================================
246
247 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
248 {
249   return _compatibleHypothesis;
250 }
251
252 //=============================================================================
253 /*!
254  *  List the hypothesis used by the algorithm associated to the shape.
255  *  Hypothesis associated to father shape -are- taken into account (see
256  *  GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
257  *  the algorithm. This method could be surcharged by specific algorithms, in 
258  *  case of several hypothesis simultaneously applicable.
259  */
260 //=============================================================================
261
262 const list <const SMESHDS_Hypothesis *> &
263 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh &         aMesh,
264                               const TopoDS_Shape & aShape,
265                               const bool           ignoreAuxiliary)
266 {
267   _usedHypList.clear();
268   SMESH_HypoFilter filter;
269   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
270   {
271     aMesh.GetHypotheses( aShape, filter, _usedHypList, true );
272     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
273       _usedHypList.clear(); //only one compatible hypothesis allowed
274   }
275   return _usedHypList;
276 }
277
278 //=============================================================================
279 /*!
280  *  List the relevant hypothesis associated to the shape. Relevant hypothesis
281  *  have a name (type) listed in the algorithm. Hypothesis associated to
282  *  father shape -are not- taken into account (see GetUsedHypothesis)
283  */
284 //=============================================================================
285
286 const list<const SMESHDS_Hypothesis *> &
287 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh &         aMesh,
288                                  const TopoDS_Shape & aShape,
289                                  const bool           ignoreAuxiliary)
290 {
291   _appliedHypList.clear();
292   SMESH_HypoFilter filter;
293   if ( InitCompatibleHypoFilter( filter, ignoreAuxiliary ))
294     aMesh.GetHypotheses( aShape, filter, _appliedHypList, false );
295
296   return _appliedHypList;
297 }
298
299 //=============================================================================
300 /*!
301  *  Compute length of an edge
302  */
303 //=============================================================================
304
305 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
306 {
307   double UMin = 0, UMax = 0;
308   if (BRep_Tool::Degenerated(E))
309     return 0;
310   TopLoc_Location L;
311   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
312   GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
313   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
314   return length;
315 }
316
317 //================================================================================
318 /*!
319  * \brief Calculate normal of a mesh face
320  */
321 //================================================================================
322
323 bool SMESH_Algo::FaceNormal(const SMDS_MeshElement* F, gp_XYZ& normal, bool normalized)
324 {
325   if ( !F || F->GetType() != SMDSAbs_Face )
326     return false;
327
328   normal.SetCoord(0,0,0);
329   int nbNodes = F->IsQuadratic() ? F->NbNodes()/2 : F->NbNodes();
330   for ( int i = 0; i < nbNodes-2; ++i )
331   {
332     gp_XYZ p[3];
333     for ( int n = 0; n < 3; ++n )
334     {
335       const SMDS_MeshNode* node = F->GetNode( i + n );
336       p[n].SetCoord( node->X(), node->Y(), node->Z() );
337     }
338     normal += ( p[2] - p[1] ) ^ ( p[0] - p[1] );
339   }
340   double size2 = normal.SquareModulus();
341   bool ok = ( size2 > numeric_limits<double>::min() * numeric_limits<double>::min());
342   if ( normalized && ok )
343     normal /= sqrt( size2 );
344
345   return ok;
346 }
347
348 /*
349  * Moved to SMESH_MesherHelper
350  */
351 // bool SMESH_Algo::IsReversedSubMesh (const TopoDS_Face&  theFace,
352 //                                     SMESHDS_Mesh*       theMeshDS)
353 // {
354 // }
355
356 //================================================================================
357 /*!
358  * \brief Just return false as the algorithm does not hold parameters values
359  */
360 //================================================================================
361
362 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
363                                      const TopoDS_Shape& /*theShape*/)
364 {
365   return false;
366 }
367 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
368 {
369   return false;
370 }
371 //================================================================================
372 /*!
373  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
374  * \param theMesh - The mesh containing nodes
375  * \param theEdge - The geometrical edge of interest
376  * \param theParams - The resulting vector of sorted node parameters
377  * \retval bool - false if not all parameters are OK
378  */
379 //================================================================================
380
381 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
382                                     const TopoDS_Edge&  theEdge,
383                                     vector< double > &  theParams)
384 {
385   theParams.clear();
386
387   if ( !theMesh || theEdge.IsNull() )
388     return false;
389
390   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
391   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
392     return false; // edge is not meshed
393
394   //int nbEdgeNodes = 0;
395   set < double > paramSet;
396   if ( eSubMesh )
397   {
398     // loop on nodes of an edge: sort them by param on edge
399     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
400     while ( nIt->more() )
401     {
402       const SMDS_MeshNode* node = nIt->next();
403       const SMDS_PositionPtr& pos = node->GetPosition();
404       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
405         return false;
406       const SMDS_EdgePosition* epos =
407         static_cast<const SMDS_EdgePosition*>(node->GetPosition());
408       if ( !paramSet.insert( epos->GetUParameter() ).second )
409         return false; // equal parameters
410     }
411   }
412   // add vertex nodes params
413   TopoDS_Vertex V1,V2;
414   TopExp::Vertices( theEdge, V1, V2);
415   if ( VertexNode( V1, theMesh ) &&
416        !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
417     return false; // there are equal parameters
418   if ( VertexNode( V2, theMesh ) &&
419        !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
420     return false; // there are equal parameters
421
422   // fill the vector
423   theParams.resize( paramSet.size() );
424   set < double >::iterator   par    = paramSet.begin();
425   vector< double >::iterator vecPar = theParams.begin();
426   for ( ; par != paramSet.end(); ++par, ++vecPar )
427     *vecPar = *par;
428
429   return theParams.size() > 1;
430 }
431
432 //================================================================================
433 /*!
434  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
435  * \param theMesh - The mesh containing nodes
436  * \param theEdge - The geometrical edge of interest
437  * \param theParams - The resulting vector of sorted node parameters
438  * \retval bool - false if not all parameters are OK
439  */
440 //================================================================================
441
442 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
443                                       const TopoDS_Edge&                    theEdge,
444                                       const bool                            ignoreMediumNodes,
445                                       map< double, const SMDS_MeshNode* > & theNodes)
446 {
447   theNodes.clear();
448
449   if ( !theMesh || theEdge.IsNull() )
450     return false;
451
452   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
453   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
454     return false; // edge is not meshed
455
456   int nbNodes = 0;
457   set < double > paramSet;
458   if ( eSubMesh )
459   {
460     // loop on nodes of an edge: sort them by param on edge
461     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
462     while ( nIt->more() )
463     {
464       const SMDS_MeshNode* node = nIt->next();
465       if ( ignoreMediumNodes ) {
466         SMDS_ElemIteratorPtr elemIt = node->GetInverseElementIterator();
467         if ( elemIt->more() && elemIt->next()->IsMediumNode( node ))
468           continue;
469       }
470       const SMDS_PositionPtr& pos = node->GetPosition();
471       if ( pos->GetTypeOfPosition() != SMDS_TOP_EDGE )
472         return false;
473       const SMDS_EdgePosition* epos =
474         static_cast<const SMDS_EdgePosition*>(node->GetPosition());
475       theNodes.insert( theNodes.end(), make_pair( epos->GetUParameter(), node ));
476       //MESSAGE("U " << epos->GetUParameter() << " ID " << node->GetID());
477       ++nbNodes;
478     }
479   }
480   // add vertex nodes
481   TopoDS_Vertex v1, v2;
482   TopExp::Vertices(theEdge, v1, v2);
483   const SMDS_MeshNode* n1 = VertexNode( v1, (SMESHDS_Mesh*) theMesh );
484   const SMDS_MeshNode* n2 = VertexNode( v2, (SMESHDS_Mesh*) theMesh );
485   //MESSAGE("Vertices ID " << n1->GetID() << " " << n2->GetID());
486   Standard_Real f, l;
487   BRep_Tool::Range(theEdge, f, l);
488   if ( v1.Orientation() != TopAbs_FORWARD )
489     std::swap( f, l );
490   if ( n1 && ++nbNodes )
491     theNodes.insert( make_pair( f, n1 ));
492   if ( n2 && ++nbNodes )
493     theNodes.insert( make_pair( l, n2 ));
494
495   return theNodes.size() == nbNodes;
496 }
497
498 //================================================================================
499 /*!
500  * \brief Make filter recognize only compatible hypotheses
501  * \param theFilter - the filter to initialize
502  * \param ignoreAuxiliary - make filter ignore compatible auxiliary hypotheses
503  */
504 //================================================================================
505
506 bool SMESH_Algo::InitCompatibleHypoFilter( SMESH_HypoFilter & theFilter,
507                                            const bool         ignoreAuxiliary) const
508 {
509   if ( !_compatibleHypothesis.empty() )
510   {
511     theFilter.Init( theFilter.HasName( _compatibleHypothesis[0] ));
512     for ( int i = 1; i < _compatibleHypothesis.size(); ++i )
513       theFilter.Or( theFilter.HasName( _compatibleHypothesis[ i ] ));
514
515     if ( ignoreAuxiliary )
516       theFilter.AndNot( theFilter.IsAuxiliary() );
517
518     return true;
519   }
520   return false;
521 }
522
523 //================================================================================
524 /*!
525  * \brief Return continuity of two edges
526  * \param E1 - the 1st edge
527  * \param E2 - the 2nd edge
528  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
529  */
530 //================================================================================
531
532 GeomAbs_Shape SMESH_Algo::Continuity(TopoDS_Edge E1,
533                                      TopoDS_Edge E2)
534 {
535   //E1.Orientation(TopAbs_FORWARD), E2.Orientation(TopAbs_FORWARD); // avoid pb with internal edges
536   if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
537     E1.Orientation( TopAbs_FORWARD );
538   if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
539     E2.Orientation( TopAbs_FORWARD );
540
541   TopoDS_Vertex V, VV1[2], VV2[2];
542   TopExp::Vertices( E1, VV1[0], VV1[1], true );
543   TopExp::Vertices( E2, VV2[0], VV2[1], true );
544   if      ( VV1[1].IsSame( VV2[0] ))  { V = VV1[1]; }
545   else if ( VV1[0].IsSame( VV2[1] ))  { V = VV1[0]; }
546   else if ( VV1[1].IsSame( VV2[1] ))  { V = VV1[1]; E1.Reverse(); }
547   else if ( VV1[0].IsSame( VV2[0] ))  { V = VV1[0]; E1.Reverse(); }
548   else { return GeomAbs_C0; }
549
550   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
551   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
552   BRepAdaptor_Curve C1( E1 ), C2( E2 );
553   Standard_Real tol = BRep_Tool::Tolerance( V );
554   Standard_Real angTol = 2e-3;
555   try {
556 #if OCC_VERSION_LARGE > 0x06010000
557     OCC_CATCH_SIGNALS;
558 #endif
559     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
560   }
561   catch (Standard_Failure) {
562   }
563   return GeomAbs_C0;
564 }
565
566 //================================================================================
567 /*!
568  * \brief Return the node built on a vertex
569  * \param V - the vertex
570  * \param meshDS - mesh
571  * \retval const SMDS_MeshNode* - found node or NULL
572  */
573 //================================================================================
574
575 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
576                                             const SMESHDS_Mesh*  meshDS)
577 {
578   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
579     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
580     if (nIt->more())
581       return nIt->next();
582   }
583   return 0;
584 }
585
586 //=======================================================================
587 //function : GetCommonNodes
588 //purpose  : Return nodes common to two elements
589 //=======================================================================
590
591 vector< const SMDS_MeshNode*> SMESH_Algo::GetCommonNodes(const SMDS_MeshElement* e1,
592                                                          const SMDS_MeshElement* e2)
593 {
594   vector< const SMDS_MeshNode*> common;
595   for ( int i = 0 ; i < e1->NbNodes(); ++i )
596     if ( e2->GetNodeIndex( e1->GetNode( i )) >= 0 )
597       common.push_back( e1->GetNode( i ));
598   return common;
599 }
600
601 //=======================================================================
602 //function : GetMeshError
603 //purpose  : Finds topological errors of a sub-mesh
604 //WARNING  : 1D check is NOT implemented so far
605 //=======================================================================
606
607 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
608 {
609   EMeshError err = MEr_OK;
610
611   SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
612   if ( !smDS )
613     return MEr_EMPTY;
614
615   switch ( subMesh->GetSubShape().ShapeType() )
616   {
617   case TopAbs_FACE: { // ====================== 2D =====================
618
619     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
620     if ( !fIt->more() )
621       return MEr_EMPTY;
622
623     // We check that olny links on EDGEs encouter once, the rest links, twice
624     set< SMESH_TLink > links;
625     while ( fIt->more() )
626     {
627       const SMDS_MeshElement* f = fIt->next();
628       int nbNodes = f->NbCornerNodes(); // ignore medium nodes
629       for ( int i = 0; i < nbNodes; ++i )
630       {
631         const SMDS_MeshNode* n1 = f->GetNode( i );
632         const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
633         std::pair< set< SMESH_TLink >::iterator, bool > it_added =
634           links.insert( SMESH_TLink( n1, n2 ));
635         if ( !it_added.second )
636           // As we do NOT(!) check if mesh is manifold, we believe that a link can
637           // encounter once or twice only (not three times), we erase a link as soon
638           // as it encounters twice to speed up search in the <links> map.
639           links.erase( it_added.first );
640       }
641     }
642     // the links remaining in the <links> should all be on EDGE
643     set< SMESH_TLink >::iterator linkIt = links.begin();
644     for ( ; linkIt != links.end(); ++linkIt )
645     {
646       const SMESH_TLink& link = *linkIt;
647       if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
648            link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
649         return MEr_HOLES;
650     }
651     // TODO: to check orientation
652     break;
653   }
654   case TopAbs_SOLID: { // ====================== 3D =====================
655
656     SMDS_ElemIteratorPtr vIt = smDS->GetElements();
657     if ( !vIt->more() )
658       return MEr_EMPTY;
659
660     SMDS_VolumeTool vTool;
661     while ( !vIt->more() )
662     {
663       if (!vTool.Set( vIt->next() ))
664         continue; // strange
665
666       for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
667         if ( vTool.IsFreeFace( iF ))
668         {
669           int nbN = vTool.NbFaceNodes( iF );
670           const SMDS_MeshNode** nodes =  vTool.GetFaceNodes( iF );
671           for ( int i = 0; i < nbN; ++i )
672             if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
673               return MEr_HOLES;
674         }
675     }
676     break;
677   }
678   default:;
679   }
680   return err;
681 }
682
683 //================================================================================
684 /*!
685  * \brief Sets event listener to submeshes if necessary
686  * \param subMesh - submesh where algo is set
687  * 
688  * After being set, event listener is notified on each event of a submesh.
689  * By default non listener is set
690  */
691 //================================================================================
692
693 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
694 {
695 }
696
697 //================================================================================
698 /*!
699  * \brief Allow algo to do something after persistent restoration
700  * \param subMesh - restored submesh
701  *
702  * This method is called only if a submesh has HYP_OK algo_state.
703  */
704 //================================================================================
705
706 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
707 {
708 }
709
710 //================================================================================
711 /*!
712  * \brief Computes mesh without geometry
713  * \param aMesh - the mesh
714  * \param aHelper - helper that must be used for adding elements to \aaMesh
715  * \retval bool - is a success
716  */
717 //================================================================================
718
719 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
720 {
721   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
722 }
723
724 //=======================================================================
725 //function : CancelCompute
726 //purpose  : Sets _computeCanceled to true. It's usage depends on
727 //  *        implementation of a particular mesher.
728 //=======================================================================
729
730 void SMESH_Algo::CancelCompute()
731 {
732   _computeCanceled = true;
733   _error = COMPERR_CANCELED;
734 }
735
736 //================================================================================
737 /*!
738  * \brief store error and comment and then return ( error == COMPERR_OK )
739  */
740 //================================================================================
741
742 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
743 {
744   _error   = error;
745   _comment = comment;
746   return ( error == COMPERR_OK );
747 }
748
749 //================================================================================
750 /*!
751  * \brief store error and return ( error == COMPERR_OK )
752  */
753 //================================================================================
754
755 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
756 {
757   if ( error ) {
758     _error   = error->myName;
759     _comment = error->myComment;
760     _badInputElements = error->myBadElements;
761     return error->IsOK();
762   }
763   return true;
764 }
765
766 //================================================================================
767 /*!
768  * \brief return compute error
769  */
770 //================================================================================
771
772 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
773 {
774   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New( _error, _comment, this );
775   // hope this method is called by only SMESH_subMesh after this->Compute()
776   err->myBadElements.splice( err->myBadElements.end(),
777                              (list<const SMDS_MeshElement*>&) _badInputElements );
778   return err;
779 }
780
781 //================================================================================
782 /*!
783  * \brief initialize compute error
784  */
785 //================================================================================
786
787 void SMESH_Algo::InitComputeError()
788 {
789   _error = COMPERR_OK;
790   _comment.clear();
791   list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
792   for ( ; elem != _badInputElements.end(); ++elem )
793     if ( (*elem)->GetID() < 1 )
794       delete *elem;
795   _badInputElements.clear();
796
797   _computeCanceled = false;
798 }
799
800 //================================================================================
801 /*!
802  * \brief store a bad input element preventing computation,
803  *        which may be a temporary one i.e. not residing the mesh,
804  *        then it will be deleted by InitComputeError()
805  */
806 //================================================================================
807
808 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
809 {
810   if ( elem )
811     _badInputElements.push_back( elem );
812 }
813
814 //=======================================================================
815 //function : addBadInputElements
816 //purpose  : store a bad input elements or nodes preventing computation
817 //=======================================================================
818
819 void SMESH_Algo::addBadInputElements(const SMESHDS_SubMesh* sm,
820                                      const bool             addNodes)
821 {
822   if ( sm )
823   {
824     if ( addNodes )
825     {
826       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
827       while ( nIt->more() ) addBadInputElement( nIt->next() );
828     }
829     else
830     {
831       SMDS_ElemIteratorPtr eIt = sm->GetElements();
832       while ( eIt->more() ) addBadInputElement( eIt->next() );
833     }
834   }
835 }
836
837 //=============================================================================
838 /*!
839  *  
840  */
841 //=============================================================================
842
843 // int SMESH_Algo::NumberOfWires(const TopoDS_Shape& S)
844 // {
845 //   int i = 0;
846 //   for (TopExp_Explorer exp(S,TopAbs_WIRE); exp.More(); exp.Next())
847 //     i++;
848 //   return i;
849 // }
850
851 //=============================================================================
852 /*!
853  *  
854  */
855 //=============================================================================
856
857 int SMESH_Algo::NumberOfPoints(SMESH_Mesh& aMesh, const TopoDS_Wire& W)
858 {
859   int nbPoints = 0;
860   for (TopExp_Explorer exp(W,TopAbs_EDGE); exp.More(); exp.Next()) {
861     const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
862     int nb = aMesh.GetSubMesh(E)->GetSubMeshDS()->NbNodes();
863     if(_quadraticMesh)
864       nb = nb/2;
865     nbPoints += nb + 1; // internal points plus 1 vertex of 2 (last point ?)
866   }
867   return nbPoints;
868 }
869
870