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