Salome HOME
Windows compatibility.
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
1 // Copyright (C) 2007-2016  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 //  NETGENPlugin : C++ implementation
24 // File      : NETGENPlugin_Mesher.cxx
25 // Author    : Michael Sazonov (OCN)
26 // Date      : 31/03/2006
27 // Project   : SALOME
28 //=============================================================================
29
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
33
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
50
51 #include <SALOMEDS_Tool.hxx>
52
53 #include <utilities.h>
54
55 #include <BRepBuilderAPI_Copy.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B3d.hxx>
58 #include <NCollection_Map.hxx>
59 #include <Standard_ErrorHandler.hxx>
60 #include <Standard_ProgramError.hxx>
61 #include <TColStd_MapOfInteger.hxx>
62 #include <TopExp.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
65 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
66 #include <TopTools_DataMapOfShapeInteger.hxx>
67 #include <TopTools_DataMapOfShapeShape.hxx>
68 #include <TopTools_MapOfShape.hxx>
69 #include <TopoDS.hxx>
70
71 // Netgen include files
72 #ifndef OCCGEOMETRY
73 #define OCCGEOMETRY
74 #endif
75 #include <occgeom.hpp>
76 #include <meshing.hpp>
77 //#include <ngexception.hpp>
78 namespace netgen {
79 #ifdef NETGEN_V5
80   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
81 #else
82   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
83 #endif
84   //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
85 #ifdef NETGEN_V5 && WIN32
86   DLL_HEADER 
87 #endif
88   extern MeshingParameters mparam;
89 #ifdef NETGEN_V5 && WIN32
90   DLL_HEADER 
91 #endif
92   extern volatile multithreadt multithread;
93
94 #ifdef NETGEN_V5 && WIN32
95   DLL_HEADER 
96 #endif
97   extern bool merge_solids;
98
99   // values used for occgeo.facemeshstatus
100   enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
101                          FACE_FAILED = -1,
102                          FACE_MESHED_OK = 1,
103   };
104 }
105
106 #include <vector>
107 #include <limits>
108
109 #ifdef WIN32
110 #include <process.h>
111 #endif
112 using namespace nglib;
113 using namespace std;
114
115 #ifdef _DEBUG_
116 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
117 #else
118 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
119 #endif
120
121 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
122
123 #ifdef _DEBUG_
124 // dump elements added to ng mesh
125 //#define DUMP_SEGMENTS
126 //#define DUMP_TRIANGLES
127 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
128 #endif
129
130 TopTools_IndexedMapOfShape ShapesWithLocalSize;
131 std::map<int,double> VertexId2LocalSize;
132 std::map<int,double> EdgeId2LocalSize;
133 std::map<int,double> FaceId2LocalSize;
134 std::map<int,double> SolidId2LocalSize;
135
136 std::vector<SMESHUtils::ControlPnt> ControlPoints;
137 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
138
139 //=============================================================================
140 /*!
141  *
142  */
143 //=============================================================================
144
145 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
146                                           const TopoDS_Shape& aShape,
147                                           const bool          isVolume)
148   : _mesh    (mesh),
149     _shape   (aShape),
150     _isVolume(isVolume),
151     _optimize(true),
152     _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
153     _isViscousLayers2D(false),
154     _ngMesh(NULL),
155     _occgeom(NULL),
156     _curShapeIndex(-1),
157     _progressTic(1),
158     _totalTime(1.0),
159     _simpleHyp(NULL),
160     _ptrToMe(NULL)
161 {
162   SetDefaultParameters();
163   ShapesWithLocalSize.Clear();
164   VertexId2LocalSize.clear();
165   EdgeId2LocalSize.clear();
166   FaceId2LocalSize.clear();
167   SolidId2LocalSize.clear();
168   ControlPoints.clear();
169   ShapesWithControlPoints.clear();
170 }
171
172 //================================================================================
173 /*!
174  * Destuctor
175  */
176 //================================================================================
177
178 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
179 {
180   if ( _ptrToMe )
181     *_ptrToMe = NULL;
182   _ptrToMe = 0;
183   _ngMesh = NULL;
184 }
185
186 //================================================================================
187 /*!
188  * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
189  * nullified at destruction of this
190  */
191 //================================================================================
192
193 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
194 {
195   if ( _ptrToMe )
196     *_ptrToMe = NULL;
197
198   _ptrToMe = ptr;
199
200   if ( _ptrToMe )
201     *_ptrToMe = this;
202 }
203
204 //================================================================================
205 /*!
206  * \brief Initialize global NETGEN parameters with default values
207  */
208 //================================================================================
209
210 void NETGENPlugin_Mesher::SetDefaultParameters()
211 {
212   netgen::MeshingParameters& mparams = netgen::mparam;
213   // maximal mesh edge size
214   mparams.maxh            = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
215   mparams.minh            = 0;
216   // minimal number of segments per edge
217   mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
218   // rate of growth of size between elements
219   mparams.grading         = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
220   // safety factor for curvatures (elements per radius)
221   mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
222   // create elements of second order
223   mparams.secondorder     = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
224   // quad-dominated surface meshing
225   if (_isVolume)
226     mparams.quad          = 0;
227   else
228     mparams.quad          = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
229   _fineness               = NETGENPlugin_Hypothesis::GetDefaultFineness();
230   mparams.uselocalh       = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
231   netgen::merge_solids    = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
232 }
233
234 //=============================================================================
235 /*!
236  *
237  */
238 //=============================================================================
239
240 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
241 {
242   if ( GeomShape.IsNull() ) return;
243   TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
244   if (GeomType == TopAbs_COMPOUND) {
245     for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
246       SetLocalSize(it.Value(), LocalSize);
247     }
248     return;
249   }
250   int key;
251   if (! ShapesWithLocalSize.Contains(GeomShape))
252     key = ShapesWithLocalSize.Add(GeomShape);
253   else
254     key = ShapesWithLocalSize.FindIndex(GeomShape);
255   if (GeomType == TopAbs_VERTEX) {
256     VertexId2LocalSize[key] = LocalSize;
257   } else if (GeomType == TopAbs_EDGE) {
258     EdgeId2LocalSize[key] = LocalSize;
259   } else if (GeomType == TopAbs_FACE) {
260     FaceId2LocalSize[key] = LocalSize;
261   } else if (GeomType == TopAbs_SOLID) {
262     SolidId2LocalSize[key] = LocalSize;
263   }
264 }
265
266 //=============================================================================
267 /*!
268  * Pass parameters to NETGEN
269  */
270 //=============================================================================
271 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
272 {
273   if (hyp)
274   {
275     netgen::MeshingParameters& mparams = netgen::mparam;
276     // Initialize global NETGEN parameters:
277     // maximal mesh segment size
278     mparams.maxh            = hyp->GetMaxSize();
279     // maximal mesh element linear size
280     mparams.minh            = hyp->GetMinSize();
281     // minimal number of segments per edge
282     mparams.segmentsperedge = hyp->GetNbSegPerEdge();
283     // rate of growth of size between elements
284     mparams.grading         = hyp->GetGrowthRate();
285     // safety factor for curvatures (elements per radius)
286     mparams.curvaturesafety = hyp->GetNbSegPerRadius();
287     // create elements of second order
288     mparams.secondorder     = hyp->GetSecondOrder() ? 1 : 0;
289     // quad-dominated surface meshing
290     mparams.quad            = hyp->GetQuadAllowed() ? 1 : 0;
291     _optimize               = hyp->GetOptimize();
292     _fineness               = hyp->GetFineness();
293     mparams.uselocalh       = hyp->GetSurfaceCurvature();
294     netgen::merge_solids    = hyp->GetFuseEdges();
295     _simpleHyp              = NULL;
296     // mesh size file
297     mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
298
299     SMESH_Gen_i*              smeshGen_i = SMESH_Gen_i::GetSMESHGen();
300     CORBA::Object_var           anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
301     SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
302     SALOMEDS::Study_var          myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
303     if ( !myStudy->_is_nil() )
304     {
305       const NETGENPlugin_Hypothesis::TLocalSize   localSizes = hyp->GetLocalSizesAndEntries();
306       NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
307       for ( ; it != localSizes.end() ; it++)
308       {
309         std::string entry = (*it).first;
310         double        val = (*it).second;
311         // --
312         GEOM::GEOM_Object_var aGeomObj;
313         SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
314         if ( !aSObj->_is_nil() ) {
315           CORBA::Object_var obj = aSObj->GetObject();
316           aGeomObj = GEOM::GEOM_Object::_narrow(obj);
317           aSObj->UnRegister();
318         }
319         TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
320         ::SetLocalSize(S, val);
321       }
322     }
323   }
324 }
325
326 //=============================================================================
327 /*!
328  * Pass simple parameters to NETGEN
329  */
330 //=============================================================================
331
332 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
333 {
334   _simpleHyp = hyp;
335   if ( _simpleHyp )
336     SetDefaultParameters();
337 }
338
339 //=============================================================================
340 /*!
341  *  Link - a pair of integer numbers
342  */
343 //=============================================================================
344 struct Link
345 {
346   int n1, n2;
347   Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
348   Link() : n1(0), n2(0) {}
349   bool Contains( int n ) const { return n == n1 || n == n2; }
350   bool IsConnected( const Link& other ) const
351   {
352     return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
353   }
354 };
355
356 int HashCode(const Link& aLink, int aLimit)
357 {
358   return HashCode(aLink.n1 + aLink.n2, aLimit);
359 }
360
361 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
362 {
363   return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
364           ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
365 }
366
367 namespace
368 {
369   //================================================================================
370   /*!
371    * \brief return id of netgen point corresponding to SMDS node
372    */
373   //================================================================================
374   typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
375
376   int ngNodeId( const SMDS_MeshNode* node,
377                 netgen::Mesh&        ngMesh,
378                 TNode2IdMap&         nodeNgIdMap)
379   {
380     int newNgId = ngMesh.GetNP() + 1;
381
382     TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
383
384     if ( node_id->second == newNgId)
385     {
386 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
387       cout << "Ng " << newNgId << " - " << node;
388 #endif
389       netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
390       ngMesh.AddPoint( p );
391     }
392     return node_id->second;
393   }
394
395   //================================================================================
396   /*!
397    * \brief Return computed EDGEs connected to the given one
398    */
399   //================================================================================
400
401   list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge&                 edge,
402                                          const TopoDS_Face&                 face,
403                                          const set< SMESH_subMesh* > &      computedSM,
404                                          const SMESH_MesherHelper&          helper,
405                                          map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
406   {
407     // get ordered EDGEs
408     list< TopoDS_Edge > edges;
409     list< int > nbEdgesInWire;
410     /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
411
412     // find <edge> within <edges>
413     list< TopoDS_Edge >::iterator eItFwd = edges.begin();
414     for ( ; eItFwd != edges.end(); ++eItFwd )
415       if ( edge.IsSame( *eItFwd ))
416         break;
417     if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
418
419     if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
420     {
421       // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
422       // so treat each INTERNAL edge separately
423       TopoDS_Edge e = *eItFwd;
424       edges.clear();
425       edges.push_back( e );
426       return edges;
427     }
428
429     // get all computed EDGEs connected to <edge>
430
431     list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
432     TopoDS_Vertex vCommon;
433     TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
434     eAdded.Add( edge );
435
436     // put edges before <edge> to <edges> back
437     while ( edges.begin() != eItFwd )
438       edges.splice( edges.end(), edges, edges.begin() );
439
440     // search forward
441     ePrev = eItFwd;
442     while ( ++eItFwd != edges.end() )
443     {
444       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
445
446       bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
447       bool computed  = sm->IsMeshComputed();
448       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
449       bool doubled   = !eAdded.Add( *eItFwd );
450       bool orientOK  = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
451                         ( eItFwd->Orientation() < TopAbs_INTERNAL )    );
452       if ( !connected || !computed || !orientOK || added || doubled )
453       {
454         // stop advancement; move edges from tail to head
455         while ( edges.back() != *ePrev )
456           edges.splice( edges.begin(), edges, --edges.end() );
457         break;
458       }
459       ePrev = eItFwd;
460     }
461     // search backward
462     while ( eItBack != edges.begin() )
463     {
464       ePrev = eItBack;
465       --eItBack;
466       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
467
468       bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
469       bool computed  = sm->IsMeshComputed();
470       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
471       bool doubled   = !eAdded.Add( *eItBack );
472       bool orientOK  = (( ePrev  ->Orientation() < TopAbs_INTERNAL ) ==
473                         ( eItBack->Orientation() < TopAbs_INTERNAL )    );
474       if ( !connected || !computed || !orientOK || added || doubled)
475       {
476         // stop advancement
477         edges.erase( edges.begin(), ePrev );
478         break;
479       }
480     }
481     if ( edges.front() != edges.back() )
482     {
483       // assure that the 1st vertex is meshed
484       TopoDS_Edge eLast = edges.back();
485       while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
486               &&
487               edges.front() != eLast )
488         edges.splice( edges.end(), edges, edges.begin() );
489     }
490     return edges;
491   }
492
493   //================================================================================
494   /*!
495    * \brief Make triangulation of a shape precise enough
496    */
497   //================================================================================
498
499   void updateTriangulation( const TopoDS_Shape& shape )
500   {
501     // static set< Poly_Triangulation* > updated;
502
503     // TopLoc_Location loc;
504     // TopExp_Explorer fExp( shape, TopAbs_FACE );
505     // for ( ; fExp.More(); fExp.Next() )
506     // {
507     //   Handle(Poly_Triangulation) triangulation =
508     //     BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
509     //   if ( triangulation.IsNull() ||
510     //        updated.insert( triangulation.operator->() ).second )
511     //   {
512     //     BRepTools::Clean (shape);
513         try {
514           OCC_CATCH_SIGNALS;
515           BRepMesh_IncrementalMesh e(shape, 0.01, true);
516         }
517         catch (Standard_Failure)
518         {
519         }
520   //       updated.erase( triangulation.operator->() );
521   //       triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
522   //       updated.insert( triangulation.operator->() );
523   //     }
524   //   }
525   }
526   //================================================================================
527   /*!
528    * \brief Returns a medium node either existing in SMESH of created by NETGEN
529    *  \param [in] corner1 - corner node 1
530    *  \param [in] corner2 - corner node 2
531    *  \param [in] defaultMedium - the node created by NETGEN
532    *  \param [in] helper - holder of medium nodes existing in SMESH
533    *  \return const SMDS_MeshNode* - the result node
534    */
535   //================================================================================
536
537   const SMDS_MeshNode* mediumNode( const SMDS_MeshNode*      corner1,
538                                    const SMDS_MeshNode*      corner2,
539                                    const SMDS_MeshNode*      defaultMedium,
540                                    const SMESH_MesherHelper* helper)
541   {
542     if ( helper )
543     {
544       TLinkNodeMap::const_iterator l2n =
545         helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
546       if ( l2n != helper->GetTLinkNodeMap().end() )
547         defaultMedium = l2n->second;
548     }
549     return defaultMedium;
550   }
551
552   //================================================================================
553   /*!
554    * \brief Assure that mesh on given shapes is quadratic
555    */
556   //================================================================================
557
558   // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
559   //                     SMESH_Mesh*                       mesh )
560   // {
561   //   for ( int i = 1; i <= shapes.Extent(); ++i )
562   //   {
563   //     SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
564   //     if ( !smDS ) continue;
565   //     SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
566   //     if ( !elemIt->more() ) continue;
567   //     const SMDS_MeshElement* e = elemIt->next();
568   //     if ( !e || e->IsQuadratic() )
569   //       continue;
570
571   //     TIDSortedElemSet elems;
572   //     elems.insert( e );
573   //     while ( elemIt->more() )
574   //       elems.insert( elems.end(), elemIt->next() );
575
576   //     SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
577   //   }
578   // }
579
580   //================================================================================
581   /*!
582    * \brief Restrict size of elements on the given edge 
583    */
584   //================================================================================
585
586   void setLocalSize(const TopoDS_Edge& edge,
587                     double             size,
588                     netgen::Mesh&      mesh)
589   {
590     if ( size <= std::numeric_limits<double>::min() )
591       return;
592     Standard_Real u1, u2;
593     Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
594     if ( curve.IsNull() )
595     {
596       TopoDS_Iterator vIt( edge );
597       if ( !vIt.More() ) return;
598       gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
599       NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
600     }
601     else
602     {
603       const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
604       Standard_Real delta = (u2-u1)/nb;
605       for(int i=0; i<nb; i++)
606       {
607         Standard_Real u = u1 + delta*i;
608         gp_Pnt p = curve->Value(u);
609         NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
610         netgen::Point3d pi(p.X(), p.Y(), p.Z());
611         double resultSize = mesh.GetH(pi);
612         if ( resultSize - size > 0.1*size )
613           // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
614           NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
615       }
616     }
617   }
618 } // namespace
619
620 //================================================================================
621 /*!
622  * \brief Set local size on shapes defined by SetParameters()
623  */
624 //================================================================================
625
626 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
627                                         netgen::Mesh&        ngMesh )
628 {
629   for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
630   {
631     int   key = (*it).first;
632     double hi = (*it).second;
633     const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
634     setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
635   }
636   for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
637   {
638     int   key = (*it).first;
639     double hi = (*it).second;
640     const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
641     gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
642     NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
643   }
644   for(map<int,double>::const_iterator it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
645   {
646     int    key = (*it).first;
647     double val = (*it).second;
648     const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
649     int faceNgID = occgeo.fmap.FindIndex(shape);
650     if ( faceNgID >= 1 )
651     {
652       occgeo.SetFaceMaxH(faceNgID, val);
653       for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
654         setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
655     }
656     else if ( !ShapesWithControlPoints.count( key ))
657     {
658       SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
659       ShapesWithControlPoints.insert( key );
660     }
661   }
662   for(map<int,double>::const_iterator it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
663   {
664     int    key = (*it).first;
665     double val = (*it).second;
666     if ( !ShapesWithControlPoints.count( key ))
667     {
668       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
669       SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
670       ShapesWithControlPoints.insert( key );
671     }
672   }
673
674   if ( !ControlPoints.empty() )
675   {
676     for ( size_t i = 0; i < ControlPoints.size(); ++i )
677       NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
678   }
679 }
680
681 //================================================================================
682 /*!
683  * \brief Initialize netgen::OCCGeometry with OCCT shape
684  */
685 //================================================================================
686
687 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
688                                              const TopoDS_Shape&      shape,
689                                              SMESH_Mesh&              mesh,
690                                              list< SMESH_subMesh* > * meshedSM,
691                                              NETGENPlugin_Internals*  intern)
692 {
693   updateTriangulation( shape );
694
695   Bnd_Box bb;
696   BRepBndLib::Add (shape, bb);
697   double x1,y1,z1,x2,y2,z2;
698   bb.Get (x1,y1,z1,x2,y2,z2);
699   netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
700   netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
701   occgeo.boundingbox = netgen::Box<3> (p1,p2);
702
703   occgeo.shape = shape;
704   occgeo.changed = 1;
705
706   // fill maps of shapes of occgeo with not yet meshed subshapes
707
708   // get root submeshes
709   list< SMESH_subMesh* > rootSM;
710   const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
711   if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
712     rootSM.push_back( mesh.GetSubMesh( shape ));
713   }
714   else {
715     for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
716       rootSM.push_back( mesh.GetSubMesh( it.Value() ));
717   }
718
719   int totNbFaces = 0;
720
721   // add subshapes of empty submeshes
722   list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
723   for ( ; rootIt != rootEnd; ++rootIt ) {
724     SMESH_subMesh * root = *rootIt;
725     SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
726                                                                /*complexShapeFirst=*/true);
727     // to find a right orientation of subshapes (PAL20462)
728     TopTools_IndexedMapOfShape subShapes;
729     TopExp::MapShapes(root->GetSubShape(), subShapes);
730     while ( smIt->more() )
731     {
732       SMESH_subMesh*  sm = smIt->next();
733       TopoDS_Shape shape = sm->GetSubShape();
734       totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
735       if ( intern && intern->isShapeToPrecompute( shape ))
736         continue;
737       if ( !meshedSM || sm->IsEmpty() )
738       {
739         if ( shape.ShapeType() != TopAbs_VERTEX )
740           shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
741         if ( shape.Orientation() >= TopAbs_INTERNAL )
742           shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
743         switch ( shape.ShapeType() ) {
744         case TopAbs_FACE  : occgeo.fmap.Add( shape ); break;
745         case TopAbs_EDGE  : occgeo.emap.Add( shape ); break;
746         case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
747         case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
748         default:;
749         }
750       }
751       // collect submeshes of meshed shapes
752       else if (meshedSM)
753       {
754         const int dim = SMESH_Gen::GetShapeDim( shape );
755         meshedSM[ dim ].push_back( sm );
756       }
757     }
758   }
759   occgeo.facemeshstatus.SetSize (totNbFaces);
760   occgeo.facemeshstatus = 0;
761   occgeo.face_maxh_modified.SetSize(totNbFaces);
762   occgeo.face_maxh_modified = 0;
763   occgeo.face_maxh.SetSize(totNbFaces);
764   occgeo.face_maxh = netgen::mparam.maxh;
765 }
766
767 //================================================================================
768 /*!
769  * \brief Return a default min size value suitable for the given geometry.
770  */
771 //================================================================================
772
773 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
774                                               const double        maxSize)
775 {
776   updateTriangulation( geom );
777
778   TopLoc_Location loc;
779   int i1, i2, i3;
780   const int* pi[4] = { &i1, &i2, &i3, &i1 };
781   double minh = 1e100;
782   Bnd_B3d bb;
783   TopExp_Explorer fExp( geom, TopAbs_FACE );
784   for ( ; fExp.More(); fExp.Next() )
785   {
786     Handle(Poly_Triangulation) triangulation =
787       BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
788     if ( triangulation.IsNull() ) continue;
789     const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
790     const TColgp_Array1OfPnt&   points = triangulation->Nodes();
791     const Poly_Array1OfTriangle& trias = triangulation->Triangles();
792     for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
793     {
794       trias(iT).Get( i1, i2, i3 );
795       for ( int j = 0; j < 3; ++j )
796       {
797         double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
798         if ( dist2 < minh && fTol*fTol < dist2 )
799           minh = dist2;
800         bb.Add( points(*pi[j]));
801       }
802     }
803   }
804   if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
805   {
806     minh = 1e-3 * sqrt( bb.SquareExtent());
807     //cout << "BND BOX minh = " <<minh << endl;
808   }
809   else
810   {
811     minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
812     //cout << "TRIANGULATION minh = " <<minh << endl;
813   }
814   if ( minh > 0.5 * maxSize )
815     minh = maxSize / 3.;
816
817   return minh;
818 }
819
820 //================================================================================
821 /*!
822  * \brief Restrict size of elements at a given point
823  */
824 //================================================================================
825
826 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
827                                             const gp_XYZ& p,
828                                             double        size,
829                                             const bool    overrideMinH)
830 {
831   if ( size <= std::numeric_limits<double>::min() )
832     return;
833   if ( netgen::mparam.minh > size )
834   {
835     if ( overrideMinH )
836     {
837       ngMesh.SetMinimalH( size );
838       netgen::mparam.minh = size;
839     }
840     else
841     {
842       size = netgen::mparam.minh;
843     }
844   }
845   netgen::Point3d pi(p.X(), p.Y(), p.Z());
846   ngMesh.RestrictLocalH( pi, size );
847 }
848
849 //================================================================================
850 /*!
851  * \brief fill ngMesh with nodes and elements of computed submeshes
852  */
853 //================================================================================
854
855 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
856                                      netgen::Mesh&                  ngMesh,
857                                      vector<const SMDS_MeshNode*>&  nodeVec,
858                                      const list< SMESH_subMesh* > & meshedSM,
859                                      SMESH_MesherHelper*            quadHelper,
860                                      SMESH_ProxyMesh::Ptr           proxyMesh)
861 {
862   TNode2IdMap nodeNgIdMap;
863   for ( size_t i = 1; i < nodeVec.size(); ++i )
864     nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
865
866   TopTools_MapOfShape visitedShapes;
867   map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
868   set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
869
870   SMESH_MesherHelper helper (*_mesh);
871
872   int faceNgID = ngMesh.GetNFD();
873
874   list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
875   for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
876   {
877     SMESH_subMesh* sm = *smIt;
878     if ( !visitedShapes.Add( sm->GetSubShape() ))
879       continue;
880
881     const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
882     if ( !smDS ) continue;
883
884     switch ( sm->GetSubShape().ShapeType() )
885     {
886     case TopAbs_EDGE: { // EDGE
887       // ----------------------
888       TopoDS_Edge geomEdge  = TopoDS::Edge( sm->GetSubShape() );
889       if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
890         geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
891
892       // Add ng segments for each not meshed FACE the EDGE bounds
893       PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
894       while ( const TopoDS_Shape * anc = fIt->next() )
895       {
896         faceNgID = occgeom.fmap.FindIndex( *anc );
897         if ( faceNgID < 1 )
898           continue; // meshed face
899
900         int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
901         if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
902           continue; // already treated EDGE
903
904         TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
905         if ( face.Orientation() >= TopAbs_INTERNAL )
906           face.Orientation( TopAbs_FORWARD ); // issue 0020676
907
908         // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
909         helper.SetSubShape( face );
910         list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
911                                                        visitedEdgeSM2Faces );
912         if ( edges.empty() )
913           continue; // wrong ancestor?
914
915         // find out orientation of <edges> within <face>
916         TopoDS_Edge eNotSeam = edges.front();
917         if ( helper.HasSeam() )
918         {
919           list< TopoDS_Edge >::iterator eIt = edges.begin();
920           while ( helper.IsRealSeam( *eIt )) ++eIt;
921           if ( eIt != edges.end() )
922             eNotSeam = *eIt;
923         }
924         TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
925         bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
926
927         // get all nodes from connected <edges>
928         const bool isQuad = smDS->IsQuadratic();
929         StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
930         const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
931         if ( points.empty() )
932           return false; // invalid node params?
933         int i, nbSeg = fSide.NbSegments();
934
935         // remember EDGEs of fSide to treat only once
936         for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
937           visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
938
939         double otherSeamParam = 0;
940         bool isSeam = false;
941
942         // add segments
943
944         int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
945
946         for ( i = 0; i < nbSeg; ++i )
947         {
948           const UVPtStruct& p1 = points[ i ];
949           const UVPtStruct& p2 = points[ i+1 ];
950
951           if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
952           {
953             isSeam = false;
954             if ( helper.IsRealSeam( p1.node->getshapeId() ))
955             {
956               TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
957               isSeam = helper.IsRealSeam( e );
958               if ( isSeam )
959               {
960                 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
961               }
962             }
963           }
964           netgen::Segment seg;
965           // ng node ids
966           seg[0] = prevNgId;
967           seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
968           // node param on curve
969           seg.epgeominfo[ 0 ].dist = p1.param;
970           seg.epgeominfo[ 1 ].dist = p2.param;
971           // uv on face
972           seg.epgeominfo[ 0 ].u = p1.u;
973           seg.epgeominfo[ 0 ].v = p1.v;
974           seg.epgeominfo[ 1 ].u = p2.u;
975           seg.epgeominfo[ 1 ].v = p2.v;
976
977           //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
978           //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
979
980           //seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
981           seg.si = faceNgID;                   // = geom.fmap.FindIndex (face);
982           seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
983           ngMesh.AddSegment (seg);
984
985           SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
986           RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
987
988 #ifdef DUMP_SEGMENTS
989           cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
990                << "\tface index: " << seg.si << endl
991                << "\tp1: " << seg[0] << endl
992                << "\tp2: " << seg[1] << endl
993                << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
994                << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
995             //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
996                << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
997                << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
998             //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
999 #endif
1000           if ( isSeam )
1001           {
1002             if ( helper.GetPeriodicIndex() && 1 ) {
1003               seg.epgeominfo[ 0 ].u = otherSeamParam;
1004               seg.epgeominfo[ 1 ].u = otherSeamParam;
1005               swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1006             } else {
1007               seg.epgeominfo[ 0 ].v = otherSeamParam;
1008               seg.epgeominfo[ 1 ].v = otherSeamParam;
1009               swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1010             }
1011             swap( seg[0], seg[1] );
1012             swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1013             seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1014             ngMesh.AddSegment( seg );
1015 #ifdef DUMP_SEGMENTS
1016             cout << "Segment: " << seg.edgenr << endl
1017                  << "\t is SEAM (reverse) of the previous. "
1018                  << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1019                  << " = " << otherSeamParam << endl;
1020 #endif
1021           }
1022           else if ( fOri == TopAbs_INTERNAL )
1023           {
1024             swap( seg[0], seg[1] );
1025             swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1026             seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1027             ngMesh.AddSegment( seg );
1028 #ifdef DUMP_SEGMENTS
1029             cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1030 #endif
1031           }
1032         }
1033       } // loop on geomEdge ancestors
1034
1035       if ( quadHelper ) // remember medium nodes of sub-meshes
1036       {
1037         SMDS_ElemIteratorPtr edges = smDS->GetElements();
1038         while ( edges->more() )
1039         {
1040           const SMDS_MeshElement* e = edges->next();
1041           if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1042             break;
1043         }
1044       }
1045
1046       break;
1047     } // case TopAbs_EDGE
1048
1049     case TopAbs_FACE: { // FACE
1050       // ----------------------
1051       const TopoDS_Face& geomFace  = TopoDS::Face( sm->GetSubShape() );
1052       helper.SetSubShape( geomFace );
1053       bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1054
1055       // Find solids the geomFace bounds
1056       int solidID1 = 0, solidID2 = 0;
1057       StdMeshers_QuadToTriaAdaptor* quadAdaptor =
1058         dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
1059       if ( quadAdaptor )
1060       {
1061         solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
1062       }
1063       else
1064       {
1065         PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1066         while ( const TopoDS_Shape * solid = solidIt->next() )
1067         {
1068           int id = occgeom.somap.FindIndex ( *solid );
1069           if ( solidID1 && id != solidID1 ) solidID2 = id;
1070           else                              solidID1 = id;
1071         }
1072       }
1073       // Add ng face descriptors of meshed faces
1074       faceNgID++;
1075       ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1076
1077       // if second oreder is required, even already meshed faces must be passed to NETGEN
1078       int fID = occgeom.fmap.Add( geomFace );
1079       if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1080       occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1081       while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1082       {
1083         fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1084         if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1085         occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1086       }
1087       // Problem with the second order in a quadrangular mesh remains.
1088       // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1089       //    by FillSMesh() (find "AddFaceDescriptor")
1090       // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1091       //    are on faces where quadrangles were.
1092       // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1093       // of the mentioned above quadrangles and triangles
1094
1095       // Orient the face correctly in solidID1 (issue 0020206)
1096       bool reverse = false;
1097       if ( solidID1 ) {
1098         TopoDS_Shape solid = occgeom.somap( solidID1 );
1099         TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1100         if ( faceOriInSolid >= 0 )
1101           reverse =
1102             helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1103       }
1104
1105       // Add surface elements
1106
1107       netgen::Element2d tri(3);
1108       tri.SetIndex( faceNgID );
1109       SMESH_TNodeXYZ xyz[3];
1110
1111 #ifdef DUMP_TRIANGLES
1112       cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
1113            << " internal="<<isInternalFace << endl;
1114 #endif
1115       if ( proxyMesh )
1116         smDS = proxyMesh->GetSubMesh( geomFace );
1117
1118       SMDS_ElemIteratorPtr faces = smDS->GetElements();
1119       while ( faces->more() )
1120       {
1121         const SMDS_MeshElement* f = faces->next();
1122         if ( f->NbNodes() % 3 != 0 ) // not triangle
1123         {
1124           PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1125           if ( const TopoDS_Shape * solid = solidIt->next() )
1126             sm = _mesh->GetSubMesh( *solid );
1127           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1128           smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle sub-mesh"));
1129           smError->myBadElements.push_back( f );
1130           return false;
1131         }
1132
1133         for ( int i = 0; i < 3; ++i )
1134         {
1135           const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1136           xyz[i].Set( node );
1137
1138           // get node UV on face
1139           int shapeID = node->getshapeId();
1140           if ( helper.IsSeamShape( shapeID ))
1141           {
1142             if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
1143               inFaceNode = f->GetNodeWrap( i-1 );
1144             else
1145               inFaceNode = f->GetNodeWrap( i+1 );
1146           }
1147           gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1148
1149           int ind = reverse ? 3-i : i+1;
1150           tri.GeomInfoPi(ind).u = uv.X();
1151           tri.GeomInfoPi(ind).v = uv.Y();
1152           tri.PNum      (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1153         }
1154
1155         // pass a triangle size to NG size-map
1156         double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1157                         ( xyz[1] - xyz[2] ).Modulus() +
1158                         ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1159         gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1160         RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1161
1162         ngMesh.AddSurfaceElement (tri);
1163 #ifdef DUMP_TRIANGLES
1164         cout << tri << endl;
1165 #endif
1166
1167         if ( isInternalFace )
1168         {
1169           swap( tri[1], tri[2] );
1170           ngMesh.AddSurfaceElement (tri);
1171 #ifdef DUMP_TRIANGLES
1172           cout << tri << endl;
1173 #endif
1174         }
1175       }
1176
1177       if ( quadHelper ) // remember medium nodes of sub-meshes
1178       {
1179         SMDS_ElemIteratorPtr faces = smDS->GetElements();
1180         while ( faces->more() )
1181         {
1182           const SMDS_MeshElement* f = faces->next();
1183           if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1184             break;
1185         }
1186       }
1187
1188       break;
1189     } // case TopAbs_FACE
1190
1191     case TopAbs_VERTEX: { // VERTEX
1192       // --------------------------
1193       // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1194       // else netgen removes a free node and nodeVector becomes invalid
1195       PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1196                                                      *sm->GetFather(),
1197                                                      TopAbs_EDGE );
1198       bool toAdd = false;
1199       while ( const TopoDS_Shape* e = ansIt->next() )
1200       {
1201         SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1202         if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1203           break;
1204       }
1205       if ( toAdd )
1206       {
1207         SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1208         if ( nodeIt->more() )
1209           ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1210       }
1211       break;
1212     }
1213     default:;
1214     } // switch
1215   } // loop on submeshes
1216
1217   // fill nodeVec
1218   nodeVec.resize( ngMesh.GetNP() + 1 );
1219   TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1220   for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1221     nodeVec[ node_NgId->second ] = node_NgId->first;
1222
1223   return true;
1224 }
1225
1226 //================================================================================
1227 /*!
1228  * \brief Duplicate mesh faces on internal geom faces
1229  */
1230 //================================================================================
1231
1232 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1233                                       netgen::Mesh&              ngMesh,
1234                                       NETGENPlugin_Internals&    internalShapes)
1235 {
1236   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1237   
1238   // find ng indices of internal faces
1239   set<int> ngFaceIds;
1240   for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1241   {
1242     int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1243     if ( internalShapes.isInternalShape( smeshID ))
1244       ngFaceIds.insert( ngFaceID );
1245   }
1246   if ( !ngFaceIds.empty() )
1247   {
1248     // duplicate faces
1249     int i, nbFaces = ngMesh.GetNSE();
1250     for ( i = 1; i <= nbFaces; ++i)
1251     {
1252       netgen::Element2d elem = ngMesh.SurfaceElement(i);
1253       if ( ngFaceIds.count( elem.GetIndex() ))
1254       {
1255         swap( elem[1], elem[2] );
1256         ngMesh.AddSurfaceElement (elem);
1257       }
1258     }
1259   }
1260 }
1261
1262 //================================================================================
1263 /*!
1264  * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1265  *        meshed due to NETGEN failure
1266  *  \param [in] occgeom - geometry
1267  *  \param [in,out] ngMesh - the mesh to fix
1268  *  \param [inout] faceID - ID of the FACE to fix the mesh on
1269  *  \return bool - is mesh is or becomes OK
1270  */
1271 //================================================================================
1272
1273 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1274                                       netgen::Mesh&              ngMesh,
1275                                       const int                  faceID)
1276 {
1277   // we address a case where the FACE is almost fully meshed except small holes
1278   // of usually triangular shape at FACE boundary (IPAL52861)
1279
1280   // The case appeared to be not simple: holes only look triangular but
1281   // indeed are a self intersecting polygon. A reason of the bug was in coincident
1282   // NG points on a seam edge. But the code below is very nice, leave it for
1283   // another case.
1284   return false;
1285
1286
1287   if ( occgeom.fmap.Extent() < faceID )
1288     return false;
1289   //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1290
1291   // find free links on the FACE
1292   NCollection_Map<Link> linkMap;
1293   for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1294   {
1295     const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1296     if ( faceID != elem.GetIndex() )
1297       continue;
1298     int n0 = elem[ elem.GetNP() - 1 ];
1299     for ( int i = 0; i < elem.GetNP(); ++i )
1300     {
1301       int n1 = elem[i];
1302       Link link( n0, n1 );
1303       if ( !linkMap.Add( link ))
1304         linkMap.Remove( link );
1305       n0 = n1;
1306     }
1307   }
1308   // add/remove boundary links
1309   for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1310   {
1311     const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1312     if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1313       continue;
1314     Link link( seg[1], seg[0] ); // reverse!!!
1315     if ( !linkMap.Add( link ))
1316       linkMap.Remove( link );
1317   }
1318   if ( linkMap.IsEmpty() )
1319     return true;
1320   if ( linkMap.Extent() < 3 )
1321     return false;
1322
1323   // make triangles of the links
1324
1325   netgen::Element2d tri(3);
1326   tri.SetIndex ( faceID );
1327
1328   NCollection_Map<Link>::Iterator linkIt( linkMap );
1329   Link link1 = linkIt.Value();
1330   // look for a link connected to link1
1331   NCollection_Map<Link>::Iterator linkIt2 = linkIt;
1332   for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1333   {
1334     const Link& link2 = linkIt2.Value();
1335     if ( link2.IsConnected( link1 ))
1336     {
1337       // look for a link connected to both link1 and link2
1338       NCollection_Map<Link>::Iterator linkIt3 = linkIt2;
1339       for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1340       {
1341         const Link& link3 = linkIt3.Value();
1342         if ( link3.IsConnected( link1 ) &&
1343              link3.IsConnected( link2 ) )
1344         {
1345           // add a triangle
1346           tri[0] = link1.n2;
1347           tri[1] = link1.n1;
1348           tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1349           if ( tri[0] == tri[2] || tri[1] == tri[2] )
1350             return false;
1351           ngMesh.AddSurfaceElement( tri );
1352
1353           // prepare for the next tria search
1354           if ( linkMap.Extent() == 3 )
1355             return true;
1356           linkMap.Remove( link3 );
1357           linkMap.Remove( link2 );
1358           linkIt.Next();
1359           linkMap.Remove( link1 );
1360           link1 = linkIt.Value();
1361           linkIt2 = linkIt;
1362           break;
1363         }
1364       }
1365     }
1366   }
1367   return false;
1368
1369 } // FixFaceMesh()
1370
1371 namespace
1372 {
1373   //================================================================================
1374   // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1375   gp_XY_FunPtr(Subtracted);
1376   //gp_XY_FunPtr(Added);
1377
1378   //================================================================================
1379   /*!
1380    * \brief Evaluate distance between two 2d points along the surface
1381    */
1382   //================================================================================
1383
1384   double evalDist( const gp_XY&                uv1,
1385                    const gp_XY&                uv2,
1386                    const Handle(Geom_Surface)& surf,
1387                    const int                   stopHandler=-1)
1388   {
1389     if ( stopHandler > 0 ) // continue recursion
1390     {
1391       gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1392       return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1393     }
1394     double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1395     if ( stopHandler == 0 ) // stop recursion
1396       return dist3D;
1397     
1398     // start recursion if necessary
1399     double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1400     if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1401       return dist3D; // equal parametrization of a planar surface
1402
1403     return evalDist( uv1, uv2, surf, 3 ); // start recursion
1404   }
1405
1406   //================================================================================
1407   /*!
1408    * \brief Data of vertex internal in geom face
1409    */
1410   //================================================================================
1411
1412   struct TIntVData
1413   {
1414     gp_XY uv;        //!< UV in face parametric space
1415     int   ngId;      //!< ng id of corrsponding node
1416     gp_XY uvClose;   //!< UV of closest boundary node
1417     int   ngIdClose; //!< ng id of closest boundary node
1418   };
1419
1420   //================================================================================
1421   /*!
1422    * \brief Data of vertex internal in solid
1423    */
1424   //================================================================================
1425
1426   struct TIntVSoData
1427   {
1428     int   ngId;      //!< ng id of corresponding node
1429     int   ngIdClose; //!< ng id of closest 2d mesh element
1430     int   ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1431   };
1432
1433   inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1434   {
1435     return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1436   }
1437 }
1438
1439 //================================================================================
1440 /*!
1441  * \brief Make netgen take internal vertices in faces into account by adding
1442  *        segments including internal vertices
1443  *
1444  * This function works in supposition that 1D mesh is already computed in ngMesh
1445  */
1446 //================================================================================
1447
1448 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry&     occgeom,
1449                                                 netgen::Mesh&                  ngMesh,
1450                                                 vector<const SMDS_MeshNode*>&  nodeVec,
1451                                                 NETGENPlugin_Internals&        internalShapes)
1452 {
1453   if ((int) nodeVec.size() < ngMesh.GetNP() )
1454     nodeVec.resize( ngMesh.GetNP(), 0 );
1455
1456   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1457   SMESH_MesherHelper helper( internalShapes.getMesh() );
1458
1459   const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1460   map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1461   for ( ; f2v != face2Vert.end(); ++f2v )
1462   {
1463     const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1464     if ( face.IsNull() ) continue;
1465     int faceNgID = occgeom.fmap.FindIndex (face);
1466     if ( faceNgID < 0 ) continue;
1467
1468     TopLoc_Location loc;
1469     Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1470
1471     helper.SetSubShape( face );
1472     helper.SetElementsOnShape( true );
1473
1474     // Get data of internal vertices and add them to ngMesh
1475
1476     multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1477
1478     int i, nbSegInit = ngMesh.GetNSeg();
1479
1480     // boundary characteristics
1481     double totSegLen2D = 0;
1482     int totNbSeg = 0;
1483
1484     const list<int>& iVertices = f2v->second;
1485     list<int>::const_iterator iv = iVertices.begin();
1486     for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1487     {
1488       TIntVData vData;
1489       // get node on vertex
1490       const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1491       const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1492       if ( !nV )
1493       {
1494         SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1495         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1496         nV = SMESH_Algo::VertexNode( V, meshDS );
1497         if ( !nV ) continue;
1498       }
1499       // add ng node
1500       netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1501       ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1502       vData.ngId = ngMesh.GetNP();
1503       nodeVec.push_back( nV );
1504
1505       // get node UV
1506       bool uvOK = true;
1507       vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1508       if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1509
1510       // loop on all segments of the face to find the node closest to vertex and to count
1511       // average segment 2d length
1512       double closeDist2 = numeric_limits<double>::max(), dist2;
1513       int ngIdLast = 0;
1514       for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1515       {
1516         netgen::Segment & seg = ngMesh.LineSegment(i);
1517         if ( seg.si != faceNgID ) continue;
1518         gp_XY uv[2];
1519         for ( int iEnd = 0; iEnd < 2; ++iEnd)
1520         {
1521           uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1522           if ( ngIdLast == seg[ iEnd ] ) continue;
1523           dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1524           if ( dist2 < closeDist2 )
1525             vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1526           ngIdLast = seg[ iEnd ];
1527         }
1528         if ( !nbV )
1529         {
1530           totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1531           totNbSeg++;
1532         }
1533       }
1534       dist2VData.insert( make_pair( closeDist2, vData ));
1535     }
1536
1537     if ( totNbSeg == 0 ) break;
1538     double avgSegLen2d = totSegLen2D / totNbSeg;
1539
1540     // Loop on vertices to add segments
1541
1542     multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1543     for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1544     {
1545       double closeDist2 = dist_vData->first, dist2;
1546       TIntVData & vData = dist_vData->second;
1547
1548       // try to find more close node among segments added for internal vertices
1549       for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1550       {
1551         netgen::Segment & seg = ngMesh.LineSegment(i);
1552         if ( seg.si != faceNgID ) continue;
1553         gp_XY uv[2];
1554         for ( int iEnd = 0; iEnd < 2; ++iEnd)
1555         {
1556           uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1557           dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1558           if ( dist2 < closeDist2 )
1559             vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1560         }
1561       }
1562       // decide whether to use the closest node as the second end of segment or to
1563       // create a new point
1564       int segEnd1 = vData.ngId;
1565       int segEnd2 = vData.ngIdClose; // to use closest node
1566       gp_XY uvV = vData.uv, uvP = vData.uvClose;
1567       double segLenHint  = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1568       double nodeDist2D  = sqrt( closeDist2 );
1569       double nodeDist3D  = evalDist( vData.uv, vData.uvClose, surf );
1570       bool avgLenOK  = ( avgSegLen2d < 0.75 * nodeDist2D );
1571       bool hintLenOK = ( segLenHint  < 0.75 * nodeDist3D );
1572       //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1573       if ( hintLenOK || avgLenOK )
1574       {
1575         // create a point between the closest node and V
1576
1577         // how far from V
1578         double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1579         // direction from V to closet node in 2D
1580         gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1581         // new point
1582         uvP = vData.uv + r * nodeDist2D * v2n.XY();
1583         gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1584
1585         netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1586         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1587         segEnd2 = ngMesh.GetNP();
1588         //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1589         SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1590         nodeVec.push_back( nP );
1591       }
1592       //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1593
1594       // Add the segment
1595       netgen::Segment seg;
1596
1597       if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1598       seg[0] = segEnd1;  // ng node id
1599       seg[1] = segEnd2;  // ng node id
1600       seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1601       seg.si = faceNgID;
1602
1603       seg.epgeominfo[ 0 ].dist = 0; // param on curve
1604       seg.epgeominfo[ 0 ].u    = uvV.X();
1605       seg.epgeominfo[ 0 ].v    = uvV.Y();
1606       seg.epgeominfo[ 1 ].dist = 1; // param on curve
1607       seg.epgeominfo[ 1 ].u    = uvP.X();
1608       seg.epgeominfo[ 1 ].v    = uvP.Y();
1609
1610 //       seg.epgeominfo[ 0 ].edgenr = 10; //  = geom.emap.FindIndex(edge);
1611 //       seg.epgeominfo[ 1 ].edgenr = 10; //  = geom.emap.FindIndex(edge);
1612
1613       ngMesh.AddSegment (seg);
1614
1615       // add reverse segment
1616       swap( seg[0], seg[1] );
1617       swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1618       seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1619       ngMesh.AddSegment (seg);
1620     }
1621
1622   }
1623 }
1624
1625 //================================================================================
1626 /*!
1627  * \brief Make netgen take internal vertices in solids into account by adding
1628  *        faces including internal vertices
1629  *
1630  * This function works in supposition that 2D mesh is already computed in ngMesh
1631  */
1632 //================================================================================
1633
1634 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry&     occgeom,
1635                                                  netgen::Mesh&                  ngMesh,
1636                                                  vector<const SMDS_MeshNode*>&  nodeVec,
1637                                                  NETGENPlugin_Internals&        internalShapes)
1638 {
1639 #ifdef DUMP_TRIANGLES_SCRIPT
1640   // create a python script making a mesh containing triangles added for internal vertices
1641   ofstream py(DUMP_TRIANGLES_SCRIPT);
1642   py << "import SMESH"<< endl
1643      << "from salome.smesh import smeshBuilder"<<endl
1644      << "smesh = smeshBuilder.New(salome.myStudy)"<<endl
1645      << "m = smesh.Mesh(name='triangles')" << endl;
1646 #endif
1647   if ((int) nodeVec.size() < ngMesh.GetNP() )
1648     nodeVec.resize( ngMesh.GetNP(), 0 );
1649
1650   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1651   SMESH_MesherHelper helper( internalShapes.getMesh() );
1652
1653   const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1654   map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1655   for ( ; s2v != so2Vert.end(); ++s2v )
1656   {
1657     const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1658     if ( solid.IsNull() ) continue;
1659     int solidNgID = occgeom.somap.FindIndex (solid);
1660     if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1661
1662     helper.SetSubShape( solid );
1663     helper.SetElementsOnShape( true );
1664
1665     // find ng indices of faces within the solid
1666     set<int> ngFaceIds;
1667     for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1668       ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1669     if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1670       ngFaceIds.insert( 1 );
1671
1672     // Get data of internal vertices and add them to ngMesh
1673
1674     multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1675
1676     int i, nbFaceInit = ngMesh.GetNSE();
1677
1678     // boundary characteristics
1679     double totSegLen = 0;
1680     int totNbSeg = 0;
1681
1682     const list<int>& iVertices = s2v->second;
1683     list<int>::const_iterator iv = iVertices.begin();
1684     for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1685     {
1686       TIntVSoData vData;
1687       const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1688
1689       // get node on vertex
1690       const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1691       if ( !nV )
1692       {
1693         SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1694         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1695         nV = SMESH_Algo::VertexNode( V, meshDS );
1696         if ( !nV ) continue;
1697       }
1698       // add ng node
1699       netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1700       ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1701       vData.ngId = ngMesh.GetNP();
1702       nodeVec.push_back( nV );
1703
1704       // loop on all 2d elements to find the one closest to vertex and to count
1705       // average segment length
1706       double closeDist2 = numeric_limits<double>::max(), avgDist2;
1707       for (i = 1; i <= ngMesh.GetNSE(); ++i)
1708       {
1709         const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1710         if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1711         avgDist2 = 0;
1712         multimap< double, int> dist2nID; // sort nodes of element by distance from V
1713         for ( int j = 0; j < elem.GetNP(); ++j)
1714         {
1715           netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1716           double d2 = dist2( mpV, mp );
1717           dist2nID.insert( make_pair( d2, elem[j] ));
1718           avgDist2 += d2 / elem.GetNP();
1719           if ( !nbV )
1720             totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1721         }
1722         double dist = dist2nID.begin()->first; //avgDist2;
1723         if ( dist < closeDist2 )
1724           vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1725       }
1726       dist2VData.insert( make_pair( closeDist2, vData ));
1727     }
1728
1729     if ( totNbSeg == 0 ) break;
1730     double avgSegLen = totSegLen / totNbSeg;
1731
1732     // Loop on vertices to add triangles
1733
1734     multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1735     for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1736     {
1737       double closeDist2   = dist_vData->first;
1738       TIntVSoData & vData = dist_vData->second;
1739
1740       const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1741
1742       // try to find more close face among ones added for internal vertices
1743       for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1744       {
1745         double avgDist2 = 0;
1746         multimap< double, int> dist2nID;
1747         const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1748         for ( int j = 0; j < elem.GetNP(); ++j)
1749         {
1750           double d = dist2( mpV, ngMesh.Point( elem[j] ));
1751           dist2nID.insert( make_pair( d, elem[j] ));
1752           avgDist2 += d / elem.GetNP();
1753           if ( avgDist2 < closeDist2 )
1754             vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1755         }
1756       }
1757       // sort nodes of the closest face by angle with vector from V to the closest node
1758       const double tol = numeric_limits<double>::min();
1759       map< double, int > angle2ID;
1760       const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1761       netgen::MeshPoint mp[2];
1762       mp[0] = ngMesh.Point( vData.ngIdCloseN );
1763       gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1764       gp_XYZ pV( NGPOINT_COORDS( mpV ));
1765       gp_Vec v2p1( pV, p1 );
1766       double distN1 = v2p1.Magnitude();
1767       if ( distN1 <= tol ) continue;
1768       v2p1 /= distN1;
1769       for ( int j = 0; j < closeFace.GetNP(); ++j)
1770       {
1771         mp[1] = ngMesh.Point( closeFace[j] );
1772         gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1773         angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1774       }
1775       // get node with angle of 60 degrees or greater
1776       map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1777       if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1778       const double minAngle = 30. * M_PI / 180.;
1779       const double angle = angle_id->first;
1780       bool angleOK = ( angle > minAngle );
1781
1782       // find points to create a triangle
1783       netgen::Element2d tri(3);
1784       tri.SetIndex ( 1 );
1785       tri[0] = vData.ngId;
1786       tri[1] = vData.ngIdCloseN; // to use the closest nodes
1787       tri[2] = angle_id->second; // to use the node with best angle
1788
1789       // decide whether to use the closest node and the node with best angle or to create new ones
1790       for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1791       {
1792         bool createNew = !angleOK; //, distOK = true;
1793         double distFromV;
1794         int triInd = isBestAngleN ? 2 : 1;
1795         mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1796         if ( isBestAngleN )
1797         {
1798           if ( angleOK )
1799           {
1800             double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1801             createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1802           }
1803           else if ( angle < tol )
1804           {
1805             v2p1.SetX( v2p1.X() + 1e-3 );
1806           }
1807           distFromV = distN1;
1808         }
1809         else
1810         {
1811           double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1812           bool     avgLenOK = ( avgSegLen < 0.75 * distN1 );
1813           bool    hintLenOK = ( segLenHint  < 0.75 * distN1 );
1814           createNew = (createNew || avgLenOK || hintLenOK );
1815           // we create a new node not closer than 0.5 to the closest face
1816           // in order not to clash with other close face
1817           double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1818           distFromV = r * distN1;
1819         }
1820         if ( createNew )
1821         {
1822           // create a new point, between the node and the vertex if angleOK
1823           gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1824           gp_Vec v2p( pV, p ); v2p.Normalize();
1825           if ( isBestAngleN && !angleOK )
1826             p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1827           else
1828             p = pV + v2p.XYZ() * distFromV;
1829
1830           if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1831
1832           mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1833           ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1834           tri[triInd] = ngMesh.GetNP();
1835           nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1836         }
1837       }
1838       ngMesh.AddSurfaceElement (tri);
1839       swap( tri[1], tri[2] );
1840       ngMesh.AddSurfaceElement (tri);
1841
1842 #ifdef DUMP_TRIANGLES_SCRIPT
1843       py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
1844          << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
1845          << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
1846          << "m.AddFace([n1,n2,n3])" << endl;
1847 #endif
1848     } // loop on internal vertices of a solid
1849
1850   } // loop on solids with internal vertices
1851 }
1852
1853 //================================================================================
1854 /*!
1855  * \brief Fill netgen mesh with segments of a FACE
1856  *  \param ngMesh - netgen mesh
1857  *  \param geom - container of OCCT geometry to mesh
1858  *  \param wires - data of nodes on FACE boundary
1859  *  \param helper - mesher helper holding the FACE
1860  *  \param nodeVec - vector of nodes in which node index == netgen ID
1861  *  \retval SMESH_ComputeErrorPtr - error description 
1862  */
1863 //================================================================================
1864
1865 SMESH_ComputeErrorPtr
1866 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
1867                                        netgen::OCCGeometry&             geom,
1868                                        const TSideVector&               wires,
1869                                        SMESH_MesherHelper&              helper,
1870                                        vector< const SMDS_MeshNode* > & nodeVec,
1871                                        const bool                       overrideMinH)
1872 {
1873   // ----------------------------
1874   // Check wires and count nodes
1875   // ----------------------------
1876   int nbNodes = 0;
1877   for ( size_t iW = 0; iW < wires.size(); ++iW )
1878   {
1879     StdMeshers_FaceSidePtr wire = wires[ iW ];
1880     if ( wire->MissVertexNode() )
1881     {
1882       // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1883       // It seems that there is no reason for this limitation
1884 //       return TError
1885 //         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1886     }
1887     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1888     if ((int) uvPtVec.size() != wire->NbPoints() )
1889       return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1890                                      SMESH_Comment("Unexpected nb of points on wire ") << iW
1891                                      << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1892     nbNodes += wire->NbPoints();
1893   }
1894   nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1895   if ( nodeVec.empty() )
1896     nodeVec.push_back( 0 );
1897
1898   // -----------------
1899   // Fill netgen mesh
1900   // -----------------
1901
1902   const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1903                                                          NETGENPlugin_NETGEN_2D_ONLY */
1904
1905   // map for nodes on vertices since they can be shared between wires
1906   // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1907   map<const SMDS_MeshNode*, int > node2ngID;
1908   if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1909   {
1910     set< int > subIDs; // ids of sub-shapes of the FACE
1911     for ( size_t iW = 0; iW < wires.size(); ++iW )
1912     {
1913       StdMeshers_FaceSidePtr wire = wires[ iW ];
1914       for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1915       {
1916         subIDs.insert( wire->EdgeID( iE ));
1917         subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1918       }
1919     }
1920     for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1921       if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1922         node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1923   }
1924
1925   const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1926   if ( ngMesh.GetNFD() < 1 )
1927     ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
1928
1929   for ( size_t iW = 0; iW < wires.size(); ++iW )
1930   {
1931     StdMeshers_FaceSidePtr       wire = wires[ iW ];
1932     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1933     const int              nbSegments = wire->NbPoints() - 1;
1934
1935     // assure the 1st node to be in node2ngID, which is needed to correctly
1936     // "close chain of segments" (see below) in case if the 1st node is not
1937     // onVertex because it is on a Viscous layer
1938     node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1939
1940     // compute length of every segment
1941     vector<double> segLen( nbSegments );
1942     for ( int i = 0; i < nbSegments; ++i )
1943       segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1944
1945     int edgeID = 1, posID = -2;
1946     bool isInternalWire = false;
1947     double vertexNormPar = 0;
1948     const int prevNbNGSeg = ngMesh.GetNSeg();
1949     for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1950     {
1951       // Add the first point of a segment
1952
1953       const SMDS_MeshNode * n = uvPtVec[ i ].node;
1954       const int posShapeID = n->getshapeId();
1955       bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1956       bool onEdge   = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE   );
1957
1958       // skip nodes on degenerated edges
1959       if ( helper.IsDegenShape( posShapeID ) &&
1960            helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1961         continue;
1962
1963       int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1964       if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
1965         ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1966       if ( ngID1 > ngMesh.GetNP() )
1967       {
1968         netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1969         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1970         nodeVec.push_back( n );
1971       }
1972       else // n is in ngMesh already, and ngID2 in prev segment is wrong
1973       {
1974         ngID2 = ngMesh.GetNP() + 1;
1975         if ( i > 0 ) // prev segment belongs to same wire
1976         {
1977           netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1978           prevSeg[1] = ngID1;
1979         }
1980       }
1981
1982       // Add the segment
1983
1984       netgen::Segment seg;
1985
1986       seg[0]     = ngID1;                // ng node id
1987       seg[1]     = ngID2;                // ng node id
1988       seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1989       seg.si     = faceID;               // = geom.fmap.FindIndex (face);
1990
1991       for ( int iEnd = 0; iEnd < 2; ++iEnd)
1992       {
1993         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1994
1995         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1996         seg.epgeominfo[ iEnd ].u    = pnt.u;
1997         seg.epgeominfo[ iEnd ].v    = pnt.v;
1998
1999         // find out edge id and node parameter on edge
2000         onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2001         if ( onVertex || posShapeID != posID )
2002         {
2003           // get edge id
2004           double normParam = pnt.normParam;
2005           if ( onVertex )
2006             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2007           int edgeIndexInWire = wire->EdgeIndex( normParam );
2008           vertexNormPar = wire->LastParameter( edgeIndexInWire );
2009           const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2010           edgeID = geom.emap.FindIndex( edge );
2011           posID  = posShapeID;
2012           isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2013           // if ( onVertex ) // param on curve is different on each of two edges
2014           //   seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2015         }
2016         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
2017       }
2018
2019       ngMesh.AddSegment (seg);
2020       {
2021         // restrict size of elements near the segment
2022         SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2023         // get an average size of adjacent segments to avoid sharp change of
2024         // element size (regression on issue 0020452, note 0010898)
2025         int   iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
2026         int   iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
2027         double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2028         int   nbSeg = ( int( segLen[ iPrev ] > sumH / 100.)  +
2029                         int( segLen[ i     ] > sumH / 100.)  +
2030                         int( segLen[ iNext ] > sumH / 100.));
2031         if ( nbSeg > 0 )
2032           RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2033       }
2034       if ( isInternalWire )
2035       {
2036         swap (seg[0], seg[1]);
2037         swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2038         seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2039         ngMesh.AddSegment (seg);
2040       }
2041     } // loop on segments on a wire
2042
2043     // close chain of segments
2044     if ( nbSegments > 0 )
2045     {
2046       netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2047       const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2048       lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2049       if ( lastSeg[1] > ngMesh.GetNP() )
2050       {
2051         netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2052         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2053         nodeVec.push_back( lastNode );
2054       }
2055       if ( isInternalWire )
2056       {
2057         netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2058         realLastSeg[0] = lastSeg[1];
2059       }
2060     }
2061
2062 #ifdef DUMP_SEGMENTS
2063     cout << "BEGIN WIRE " << iW << endl;
2064     for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2065     {
2066       netgen::Segment& seg = ngMesh.LineSegment( i );
2067       if ( i > 1 ) {
2068         netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2069         if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2070         {
2071           cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
2072           continue;
2073         }
2074       }
2075       cout << "Segment: " << seg.edgenr << endl
2076            << "\tp1: " << seg[0] << "   n" << nodeVec[ seg[0]]->GetID() << endl
2077            << "\tp2: " << seg[1] << "   n" << nodeVec[ seg[1]]->GetID() <<  endl
2078            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2079            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2080            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2081            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2082            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2083            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2084     }
2085     cout << "--END WIRE " << iW << endl;
2086 #else
2087     SMESH_Comment __not_unused_variable( prevNbNGSeg );
2088 #endif
2089
2090   } // loop on WIREs of a FACE
2091
2092   // add a segment instead of an internal vertex
2093   if ( wasNgMeshEmpty )
2094   {
2095     NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2096     AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2097   }
2098   ngMesh.CalcSurfacesOfNode();
2099
2100   return TError();
2101 }
2102
2103 //================================================================================
2104 /*!
2105  * \brief Fill SMESH mesh according to contents of netgen mesh
2106  *  \param occgeo - container of OCCT geometry to mesh
2107  *  \param ngMesh - netgen mesh
2108  *  \param initState - bn of entities in netgen mesh before computing
2109  *  \param sMesh - SMESH mesh to fill in
2110  *  \param nodeVec - vector of nodes in which node index == netgen ID
2111  *  \param comment - returns problem description
2112  *  \param quadHelper - holder of medium nodes of sub-meshes
2113  *  \retval int - error
2114  */
2115 //================================================================================
2116
2117 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
2118                                    netgen::Mesh&                       ngMesh,
2119                                    const NETGENPlugin_ngMeshInfo&      initState,
2120                                    SMESH_Mesh&                         sMesh,
2121                                    std::vector<const SMDS_MeshNode*>&  nodeVec,
2122                                    SMESH_Comment&                      comment,
2123                                    SMESH_MesherHelper*                 quadHelper)
2124 {
2125   int nbNod = ngMesh.GetNP();
2126   int nbSeg = ngMesh.GetNSeg();
2127   int nbFac = ngMesh.GetNSE();
2128   int nbVol = ngMesh.GetNE();
2129
2130   SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2131
2132   // quadHelper is used for either
2133   // 1) making quadratic elements when a lower dimention mesh is loaded
2134   //    to SMESH before convertion to quadratic by NETGEN
2135   // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2136   if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2137     quadHelper = 0;
2138
2139   // -------------------------------------
2140   // Create and insert nodes into nodeVec
2141   // -------------------------------------
2142
2143   nodeVec.resize( nbNod + 1 );
2144   int i, nbInitNod = initState._nbNodes;
2145   for (i = nbInitNod+1; i <= nbNod; ++i )
2146   {
2147     const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2148     SMDS_MeshNode* node = NULL;
2149     TopoDS_Vertex aVert;
2150     // First, netgen creates nodes on vertices in occgeo.vmap,
2151     // so node index corresponds to vertex index
2152     // but (issue 0020776) netgen does not create nodes with equal coordinates
2153     if ( i-nbInitNod <= occgeo.vmap.Extent() )
2154     {
2155       gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2156       for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2157       {
2158         aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2159         gp_Pnt pV = BRep_Tool::Pnt( aVert );
2160         if ( p.SquareDistance( pV ) > 1e-20 )
2161           aVert.Nullify();
2162         else
2163           node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2164       }
2165     }
2166     if (!node) // node not found on vertex
2167     {
2168       node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2169       if (!aVert.IsNull())
2170         meshDS->SetNodeOnVertex(node, aVert);
2171     }
2172     nodeVec[i] = node;
2173   }
2174
2175   // -------------------------------------------
2176   // Create mesh segments along geometric edges
2177   // -------------------------------------------
2178
2179   int nbInitSeg = initState._nbSegments;
2180   for (i = nbInitSeg+1; i <= nbSeg; ++i )
2181   {
2182     const netgen::Segment& seg = ngMesh.LineSegment(i);
2183     TopoDS_Edge aEdge;
2184     int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2185     int nbp = 0;
2186     double param2 = 0;
2187     for (int j=0; j < 3; ++j)
2188     {
2189       int pind = pinds[j];
2190       if (pind <= 0 || !nodeVec_ACCESS(pind))
2191         break;
2192       ++nbp;
2193       double param;
2194       if (j < 2)
2195       {
2196         if (aEdge.IsNull())
2197         {
2198           int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2199           if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2200             aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2201         }
2202         param = seg.epgeominfo[j].dist;
2203         param2 += param;
2204       }
2205       else // middle point
2206       {
2207         param = param2 * 0.5;
2208       }
2209       if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
2210       {
2211         meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2212       }
2213     }
2214     if ( nbp > 1 )
2215     {
2216       SMDS_MeshEdge* edge = 0;
2217       if (nbp == 2) // second order ?
2218       {
2219         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2220           continue;
2221         if ( quadHelper ) // final mesh must be quadratic
2222           edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2223         else
2224           edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2225       }
2226       else
2227       {
2228         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2229                                nodeVec_ACCESS(pinds[2])))
2230           continue;
2231         edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2232                                nodeVec_ACCESS(pinds[2]));
2233       }
2234       if (!edge)
2235       {
2236         if ( comment.empty() ) comment << "Cannot create a mesh edge";
2237         MESSAGE("Cannot create a mesh edge");
2238         nbSeg = nbFac = nbVol = 0;
2239         break;
2240       }
2241       if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
2242         meshDS->SetMeshElementOnShape(edge, aEdge);
2243     }
2244     else if ( comment.empty() )
2245     {
2246       comment << "Invalid netgen segment #" << i;
2247     }
2248   }
2249
2250   // ----------------------------------------
2251   // Create mesh faces along geometric faces
2252   // ----------------------------------------
2253
2254   int nbInitFac = initState._nbFaces;
2255   int quadFaceID = ngMesh.GetNFD() + 1;
2256   if ( nbInitFac < nbFac )
2257     // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2258     // from computation of 3D mesh
2259     ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2260
2261   vector<const SMDS_MeshNode*> nodes;
2262   for (i = nbInitFac+1; i <= nbFac; ++i )
2263   {
2264     const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2265     const int        aGeomFaceInd = elem.GetIndex();
2266     TopoDS_Face aFace;
2267     if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2268       aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2269     nodes.clear();
2270     for ( int j = 1; j <= elem.GetNP(); ++j )
2271     {
2272       int pind = elem.PNum(j);
2273       if ( pind < 1 || pind >= (int) nodeVec.size() )
2274         break;
2275       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2276       {
2277         nodes.push_back( node );
2278         if (!aFace.IsNull() && node->getshapeId() < 1)
2279         {
2280           const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2281           meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2282         }
2283       }
2284     }
2285     if ((int) nodes.size() != elem.GetNP() )
2286     {
2287       if ( comment.empty() )
2288         comment << "Invalid netgen 2d element #" << i;
2289       continue; // bad node ids
2290     }
2291     SMDS_MeshFace* face = NULL;
2292     switch (elem.GetType())
2293     {
2294     case netgen::TRIG:
2295       if ( quadHelper ) // final mesh must be quadratic
2296         face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2297       else
2298         face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2299       break;
2300     case netgen::QUAD:
2301       if ( quadHelper ) // final mesh must be quadratic
2302         face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2303       else
2304         face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2305       // exclude qudrangle elements from computation of 3D mesh
2306       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2307       break;
2308     case netgen::TRIG6:
2309       nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2310       nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2311       nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2312       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2313       break;
2314     case netgen::QUAD8:
2315       nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2316       nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2317       nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2318       nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2319       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2320                              nodes[4],nodes[7],nodes[5],nodes[6]);
2321       // exclude qudrangle elements from computation of 3D mesh
2322       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2323       break;
2324     default:
2325       MESSAGE("NETGEN created a face of unexpected type, ignoring");
2326       continue;
2327     }
2328     if ( !face )
2329     {
2330       if ( comment.empty() ) comment << "Cannot create a mesh face";
2331       MESSAGE("Cannot create a mesh face");
2332       nbSeg = nbFac = nbVol = 0;
2333       break;
2334     }
2335     if ( !aFace.IsNull() )
2336       meshDS->SetMeshElementOnShape( face, aFace );
2337   }
2338
2339   // ------------------
2340   // Create tetrahedra
2341   // ------------------
2342
2343   for ( i = 1; i <= nbVol; ++i )
2344   {
2345     const netgen::Element& elem = ngMesh.VolumeElement(i);      
2346     int aSolidInd = elem.GetIndex();
2347     TopoDS_Solid aSolid;
2348     if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2349       aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2350     nodes.clear();
2351     for ( int j = 1; j <= elem.GetNP(); ++j )
2352     {
2353       int pind = elem.PNum(j);
2354       if ( pind < 1 || pind >= (int)nodeVec.size() )
2355         break;
2356       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2357       {
2358         nodes.push_back(node);
2359         if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2360           meshDS->SetNodeInVolume(node, aSolid);
2361       }
2362     }
2363     if ((int) nodes.size() != elem.GetNP() )
2364     {
2365       if ( comment.empty() )
2366         comment << "Invalid netgen 3d element #" << i;
2367       continue;
2368     }
2369     SMDS_MeshVolume* vol = NULL;
2370     switch ( elem.GetType() )
2371     {
2372     case netgen::TET:
2373       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2374       break;
2375     case netgen::TET10:
2376       nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2377       nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2378       nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2379       nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2380       nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2381       nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2382       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2383                               nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2384       break;
2385     default:
2386       MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2387       continue;
2388     }
2389     if (!vol)
2390     {
2391       if ( comment.empty() ) comment << "Cannot create a mesh volume";
2392       MESSAGE("Cannot create a mesh volume");
2393       nbSeg = nbFac = nbVol = 0;
2394       break;
2395     }
2396     if (!aSolid.IsNull())
2397       meshDS->SetMeshElementOnShape(vol, aSolid);
2398   }
2399   return comment.empty() ? 0 : 1;
2400 }
2401
2402 namespace
2403 {
2404   //================================================================================
2405   /*!
2406    * \brief Convert error into text
2407    */
2408   //================================================================================
2409
2410   std::string text(int err)
2411   {
2412     if ( !err )
2413       return string("");
2414     return
2415       SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2416   }
2417
2418   //================================================================================
2419   /*!
2420    * \brief Convert exception into text
2421    */
2422   //================================================================================
2423
2424   std::string text(Standard_Failure& ex)
2425   {
2426     SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2427     str << " at " << netgen::multithread.task
2428         << ": " << ex.DynamicType()->Name();
2429     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2430       str << ": " << ex.GetMessageString();
2431     return str;
2432   }
2433   //================================================================================
2434   /*!
2435    * \brief Convert exception into text
2436    */
2437   //================================================================================
2438
2439   std::string text(netgen::NgException& ex)
2440   {
2441     SMESH_Comment str("NgException");
2442     if ( strlen( netgen::multithread.task ) > 0 )
2443       str << " at " << netgen::multithread.task;
2444     str << ": " << ex.What();
2445     return str;
2446   }
2447
2448   //================================================================================
2449   /*!
2450    * \brief Looks for triangles lying on a SOLID
2451    */
2452   //================================================================================
2453
2454   bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2455                           SMESH_subMesh*                       solidSM )
2456   {
2457     TopTools_IndexedMapOfShape solidSubs;
2458     TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2459     SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2460
2461     list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2462     for ( ; e != elems.end(); ++e )
2463     {
2464       const SMDS_MeshElement* elem = *e;
2465       // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2466       //   continue;
2467       int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2468       SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2469       while ( nIt->more() )
2470       {
2471         const SMDS_MeshNode* n = nIt->next();
2472         const TopoDS_Shape&  s = mesh->IndexToShape( n->getshapeId() );
2473         nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2474         if ( nbNodesOnSolid > 2 ||
2475              nbNodesOnSolid == nbNodes)
2476           return true;
2477       }
2478     }
2479     return false;
2480   }
2481
2482   const double edgeMeshingTime = 0.001;
2483   const double faceMeshingTime = 0.019;
2484   const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2485   const double faceOptimizTime = 0.06;
2486   const double voluMeshingTime = 0.15;
2487   const double volOptimizeTime = 0.77;
2488 }
2489
2490 //=============================================================================
2491 /*!
2492  * Here we are going to use the NETGEN mesher
2493  */
2494 //=============================================================================
2495
2496 bool NETGENPlugin_Mesher::Compute()
2497 {
2498   NETGENPlugin_NetgenLibWrapper ngLib;
2499
2500   netgen::MeshingParameters& mparams = netgen::mparam;
2501
2502   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2503   SMESH_MesherHelper quadHelper( *_mesh );
2504   quadHelper.SetIsQuadratic( mparams.secondorder );
2505
2506   static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( _ngMesh, debugFile )
2507                                                  while debugging netgen */
2508   // -------------------------
2509   // Prepare OCC geometry
2510   // -------------------------
2511
2512   netgen::OCCGeometry occgeo;
2513   list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2514   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2515   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2516   _occgeom = &occgeo;
2517
2518   _totalTime = edgeFaceMeshingTime;
2519   if ( _optimize )
2520     _totalTime += faceOptimizTime;
2521   if ( _isVolume )
2522     _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2523   double doneTime = 0;
2524   _ticTime = -1;
2525   _progressTic = 1;
2526   _curShapeIndex = -1;
2527
2528   // -------------------------
2529   // Generate the mesh
2530   // -------------------------
2531
2532   _ngMesh = NULL;
2533   NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2534
2535   SMESH_Comment comment;
2536   int err = 0;
2537
2538   // vector of nodes in which node index == netgen ID
2539   vector< const SMDS_MeshNode* > nodeVec;
2540   
2541   {
2542     // ----------------
2543     // compute 1D mesh
2544     // ----------------
2545     if ( _simpleHyp )
2546     {
2547       // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2548       mparams.uselocalh = false;
2549       mparams.grading = 0.8; // not limitited size growth
2550
2551       if ( _simpleHyp->GetNumberOfSegments() )
2552         // nb of segments
2553         mparams.maxh = occgeo.boundingbox.Diam();
2554       else
2555         // segment length
2556         mparams.maxh = _simpleHyp->GetLocalLength();
2557     }
2558
2559     if ( mparams.maxh == 0.0 )
2560       mparams.maxh = occgeo.boundingbox.Diam();
2561     if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2562       mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2563
2564     // Local size on faces
2565     occgeo.face_maxh = mparams.maxh;
2566
2567     // Let netgen create _ngMesh and calculate element size on not meshed shapes
2568 #ifndef NETGEN_V5
2569     char *optstr = 0;
2570 #endif
2571     int startWith = netgen::MESHCONST_ANALYSE;
2572     int endWith   = netgen::MESHCONST_ANALYSE;
2573     try
2574     {
2575       OCC_CATCH_SIGNALS;
2576 #ifdef NETGEN_V5
2577       err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2578 #else
2579       err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2580 #endif
2581       if(netgen::multithread.terminate)
2582         return false;
2583
2584       comment << text(err);
2585     }
2586     catch (Standard_Failure& ex)
2587     {
2588       comment << text(ex);
2589     }
2590     catch (netgen::NgException & ex)
2591     {
2592       comment << text(ex);
2593       if ( mparams.meshsizefilename )
2594         throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2595     }
2596     err = 0; //- MESHCONST_ANALYSE isn't so important step
2597     if ( !_ngMesh )
2598       return false;
2599     ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2600
2601     _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2602
2603     if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2604       _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2605
2606     if ( _simpleHyp )
2607     {
2608       // Pass 1D simple parameters to NETGEN
2609       // --------------------------------
2610       int      nbSeg = _simpleHyp->GetNumberOfSegments();
2611       double segSize = _simpleHyp->GetLocalLength();
2612       for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2613       {
2614         const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2615         if ( nbSeg )
2616           segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2617         setLocalSize( e, segSize, *_ngMesh );
2618       }
2619     }
2620     else // if ( ! _simpleHyp )
2621     {
2622       // Local size on shapes
2623       SetLocalSize( occgeo, *_ngMesh );
2624     }
2625
2626     // Precompute internal edges (issue 0020676) in order to
2627     // add mesh on them correctly (twice) to netgen mesh
2628     if ( !err && internals.hasInternalEdges() )
2629     {
2630       // load internal shapes into OCCGeometry
2631       netgen::OCCGeometry intOccgeo;
2632       internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2633       intOccgeo.boundingbox = occgeo.boundingbox;
2634       intOccgeo.shape = occgeo.shape;
2635       intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2636       intOccgeo.face_maxh = netgen::mparam.maxh;
2637       netgen::Mesh *tmpNgMesh = NULL;
2638       try
2639       {
2640         OCC_CATCH_SIGNALS;
2641         // compute local H on internal shapes in the main mesh
2642         //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2643
2644         // let netgen create a temporary mesh
2645 #ifdef NETGEN_V5
2646         netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2647 #else
2648         netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2649 #endif
2650         if(netgen::multithread.terminate)
2651           return false;
2652
2653         // copy LocalH from the main to temporary mesh
2654         initState.transferLocalH( _ngMesh, tmpNgMesh );
2655
2656         // compute mesh on internal edges
2657         startWith = endWith = netgen::MESHCONST_MESHEDGES;
2658 #ifdef NETGEN_V5
2659         err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2660 #else
2661         err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2662 #endif
2663         comment << text(err);
2664       }
2665       catch (Standard_Failure& ex)
2666       {
2667         comment << text(ex);
2668         err = 1;
2669       }
2670       initState.restoreLocalH( tmpNgMesh );
2671
2672       // fill SMESH by netgen mesh
2673       vector< const SMDS_MeshNode* > tmpNodeVec;
2674       FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2675       err = ( err || !comment.empty() );
2676
2677       nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2678     }
2679
2680     // Fill _ngMesh with nodes and segments of computed submeshes
2681     if ( !err )
2682     {
2683       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2684                 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2685     }
2686     initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2687
2688     // Compute 1d mesh
2689     if (!err)
2690     {
2691       startWith = endWith = netgen::MESHCONST_MESHEDGES;
2692       try
2693       {
2694         OCC_CATCH_SIGNALS;
2695 #ifdef NETGEN_V5
2696         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2697 #else
2698         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2699 #endif
2700         if(netgen::multithread.terminate)
2701           return false;
2702
2703         comment << text(err);
2704       }
2705       catch (Standard_Failure& ex)
2706       {
2707         comment << text(ex);
2708         err = 1;
2709       }
2710     }
2711     if ( _isVolume )
2712       _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2713
2714     mparams.uselocalh = true; // restore as it is used at surface optimization
2715
2716     // ---------------------
2717     // compute surface mesh
2718     // ---------------------
2719     if (!err)
2720     {
2721       // Pass 2D simple parameters to NETGEN
2722       if ( _simpleHyp ) {
2723         if ( double area = _simpleHyp->GetMaxElementArea() ) {
2724           // face area
2725           mparams.maxh = sqrt(2. * area/sqrt(3.0));
2726           mparams.grading = 0.4; // moderate size growth
2727         }
2728         else {
2729           // length from edges
2730           if ( _ngMesh->GetNSeg() ) {
2731             double edgeLength = 0;
2732             TopTools_MapOfShape visitedEdges;
2733             for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2734               if( visitedEdges.Add(exp.Current()) )
2735                 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2736             // we have to multiply length by 2 since for each TopoDS_Edge there
2737             // are double set of NETGEN edges, in other words, we have to
2738             // divide _ngMesh->GetNSeg() by 2.
2739             mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2740           }
2741           else {
2742             mparams.maxh = 1000;
2743           }
2744           mparams.grading = 0.2; // slow size growth
2745         }
2746         mparams.quad = _simpleHyp->GetAllowQuadrangles();
2747         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2748         _ngMesh->SetGlobalH (mparams.maxh);
2749         netgen::Box<3> bb = occgeo.GetBoundingBox();
2750         bb.Increase (bb.Diam()/20);
2751         _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2752       }
2753
2754       // Care of vertices internal in faces (issue 0020676)
2755       if ( internals.hasInternalVertexInFace() )
2756       {
2757         // store computed segments in SMESH in order not to create SMESH
2758         // edges for ng segments added by AddIntVerticesInFaces()
2759         FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2760         // add segments to faces with internal vertices
2761         AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2762         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2763       }
2764
2765       // Build viscous layers
2766       if ( _isViscousLayers2D ||
2767            StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh ))
2768       {
2769         if ( !internals.hasInternalVertexInFace() ) {
2770           FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2771           initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2772         }
2773         SMESH_ProxyMesh::Ptr viscousMesh;
2774         SMESH_MesherHelper   helper( *_mesh );
2775         for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2776         {
2777           const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2778           viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2779           if ( !viscousMesh )
2780             return false;
2781           if ( viscousMesh->NbProxySubMeshes() == 0 )
2782             continue;
2783           // exclude from computation ng segments built on EDGEs of F
2784           for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2785           {
2786             netgen::Segment & seg = _ngMesh->LineSegment(i);
2787             if (seg.si == faceID)
2788               seg.si = 0;
2789           }
2790           // add new segments to _ngMesh instead of excluded ones
2791           helper.SetSubShape( F );
2792           TSideVector wires =
2793             StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2794                                                error, viscousMesh );
2795           error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2796
2797           if ( !error ) error = SMESH_ComputeError::New();
2798         }
2799         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2800       }
2801
2802       // Let netgen compute 2D mesh
2803       startWith = netgen::MESHCONST_MESHSURFACE;
2804       endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2805       try
2806       {
2807         OCC_CATCH_SIGNALS;
2808 #ifdef NETGEN_V5
2809         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2810 #else
2811         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2812 #endif
2813         if(netgen::multithread.terminate)
2814           return false;
2815
2816         comment << text (err);
2817       }
2818       catch (Standard_Failure& ex)
2819       {
2820         comment << text(ex);
2821         //err = 1; -- try to make volumes anyway
2822       }
2823       catch (netgen::NgException exc)
2824       {
2825         comment << text(exc);
2826         //err = 1; -- try to make volumes anyway
2827       }
2828     }
2829     if ( _isVolume )
2830     {
2831       doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2832       _ticTime = doneTime / _totalTime / _progressTic;
2833     }
2834     // ---------------------
2835     // generate volume mesh
2836     // ---------------------
2837     // Fill _ngMesh with nodes and faces of computed 2D submeshes
2838     if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2839     {
2840       // load SMESH with computed segments and faces
2841       FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2842
2843       // compute pyramids on quadrangles
2844       SMESH_ProxyMesh::Ptr proxyMesh;
2845       if ( _mesh->NbQuadrangles() > 0 )
2846         for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2847         {
2848           StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2849           proxyMesh.reset( Adaptor );
2850
2851           int nbPyrams = _mesh->NbPyramids();
2852           Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2853           if ( nbPyrams != _mesh->NbPyramids() )
2854           {
2855             list< SMESH_subMesh* > quadFaceSM;
2856             for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2857               if ( Adaptor->GetProxySubMesh( face.Current() ))
2858               {
2859                 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2860                 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2861               }
2862             FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh);
2863           }
2864         }
2865       // fill _ngMesh with faces of sub-meshes
2866       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
2867       initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2868       //toPython( _ngMesh, "/tmp/ngPython.py");
2869     }
2870     if (!err && _isVolume)
2871     {
2872       // Pass 3D simple parameters to NETGEN
2873       const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2874         dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2875       if ( simple3d ) {
2876         if ( double vol = simple3d->GetMaxElementVolume() ) {
2877           // max volume
2878           mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2879           mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2880         }
2881         else {
2882           // length from faces
2883           mparams.maxh = _ngMesh->AverageH();
2884         }
2885         _ngMesh->SetGlobalH (mparams.maxh);
2886         mparams.grading = 0.4;
2887 #ifdef NETGEN_V5
2888         _ngMesh->CalcLocalH(mparams.grading);
2889 #else
2890         _ngMesh->CalcLocalH();
2891 #endif
2892       }
2893       // Care of vertices internal in solids and internal faces (issue 0020676)
2894       if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2895       {
2896         // store computed faces in SMESH in order not to create SMESH
2897         // faces for ng faces added here
2898         FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2899         // add ng faces to solids with internal vertices
2900         AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2901         // duplicate mesh faces on internal faces
2902         FixIntFaces( occgeo, *_ngMesh, internals );
2903         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2904       }
2905       // Let netgen compute 3D mesh
2906       startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2907       try
2908       {
2909         OCC_CATCH_SIGNALS;
2910 #ifdef NETGEN_V5
2911         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2912 #else
2913         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2914 #endif
2915         if(netgen::multithread.terminate)
2916           return false;
2917
2918         if ( comment.empty() ) // do not overwrite a previos error
2919           comment << text(err);
2920       }
2921       catch (Standard_Failure& ex)
2922       {
2923         if ( comment.empty() ) // do not overwrite a previos error
2924           comment << text(ex);
2925         err = 1;
2926       }
2927       catch (netgen::NgException exc)
2928       {
2929         if ( comment.empty() ) // do not overwrite a previos error
2930           comment << text(exc);
2931         err = 1;
2932       }
2933       _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2934
2935       // Let netgen optimize 3D mesh
2936       if ( !err && _optimize )
2937       {
2938         startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2939         try
2940         {
2941           OCC_CATCH_SIGNALS;
2942 #ifdef NETGEN_V5
2943           err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2944 #else
2945           err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2946 #endif
2947           if(netgen::multithread.terminate)
2948             return false;
2949
2950           if ( comment.empty() ) // do not overwrite a previos error
2951             comment << text(err);
2952         }
2953         catch (Standard_Failure& ex)
2954         {
2955           if ( comment.empty() ) // do not overwrite a previos error
2956             comment << text(ex);
2957         }
2958         catch (netgen::NgException exc)
2959         {
2960           if ( comment.empty() ) // do not overwrite a previos error
2961             comment << text(exc);
2962         }
2963       }
2964     }
2965     if (!err && mparams.secondorder > 0)
2966     {
2967       try
2968       {
2969         OCC_CATCH_SIGNALS;
2970         if ( !meshedSM[ MeshDim_1D ].empty() )
2971         {
2972           // remove segments not attached to geometry (IPAL0052479)
2973           for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
2974           {
2975             const netgen::Segment & seg = _ngMesh->LineSegment (i);
2976             if ( seg.epgeominfo[ 0 ].edgenr == 0 )
2977               _ngMesh->DeleteSegment( i );
2978           }
2979           _ngMesh->Compress();
2980         }
2981         // convert to quadratic
2982         netgen::OCCRefinementSurfaces ref (occgeo);
2983         ref.MakeSecondOrder (*_ngMesh);
2984
2985         // care of elements already loaded to SMESH
2986         // if ( initState._nbSegments > 0 )
2987         //   makeQuadratic( occgeo.emap, _mesh );
2988         // if ( initState._nbFaces > 0 )
2989         //   makeQuadratic( occgeo.fmap, _mesh );
2990       }
2991       catch (Standard_Failure& ex)
2992       {
2993         if ( comment.empty() ) // do not overwrite a previos error
2994           comment << "Exception in netgen at passing to 2nd order ";
2995       }
2996       catch (netgen::NgException exc)
2997       {
2998         if ( comment.empty() ) // do not overwrite a previos error
2999           comment << exc.What();
3000       }
3001     }
3002   }
3003
3004   _ticTime = 0.98 / _progressTic;
3005
3006   //int nbNod = _ngMesh->GetNP();
3007   //int nbSeg = _ngMesh->GetNSeg();
3008   int nbFac = _ngMesh->GetNSE();
3009   int nbVol = _ngMesh->GetNE();
3010   bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3011
3012   // Feed back the SMESHDS with the generated Nodes and Elements
3013   if ( true /*isOK*/ ) // get whatever built
3014   {
3015     FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3016
3017     if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3018       for ( size_t i = 0; i < nodeVec.size(); ++i )
3019         if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3020           _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3021   }
3022   SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3023   if ( readErr && !readErr->myBadElements.empty() )
3024   {
3025     error = readErr;
3026     if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3027     comment += readErr->myComment;
3028   }
3029   if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3030     error->myName = COMPERR_ALGO_FAILED;
3031   if ( !comment.empty() )
3032     error->myComment = comment;
3033
3034   // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3035   // appear if the geometry contains coincident sub-shape due
3036   // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3037   const int nbMaps = 2;
3038   const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3039     { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3040   for ( int iMap = 0; iMap < nbMaps; ++iMap )
3041     for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3042       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3043         if ( !sm->IsMeshComputed() )
3044           sm->SetIsAlwaysComputed( true );
3045
3046   // set bad compute error to subshapes of all failed sub-shapes
3047   if ( !error->IsOK() )
3048   {
3049     bool pb2D = false, pb3D = false;
3050     for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3051       int status = occgeo.facemeshstatus[i-1];
3052       if (status == netgen::FACE_MESHED_OK ) continue;
3053       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3054         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3055         if ( !smError || smError->IsOK() ) {
3056           if ( status == netgen::FACE_FAILED )
3057             smError.reset( new SMESH_ComputeError( *error ));
3058           else
3059             smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3060           if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3061             smError->myName = COMPERR_WARNING;
3062         }
3063         pb2D = pb2D || smError->IsKO();
3064       }
3065     }
3066     if ( !pb2D ) // all faces are OK
3067       for (int i = 1; i <= occgeo.somap.Extent(); i++)
3068         if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3069         {
3070           bool smComputed = nbVol && !sm->IsEmpty();
3071           if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3072           {
3073             int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3074             SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3075             smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
3076           }
3077           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3078           if ( !smComputed && ( !smError || smError->IsOK() ))
3079           {
3080             smError.reset( new SMESH_ComputeError( *error ));
3081             if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3082             {
3083               smError->myName = COMPERR_WARNING;
3084             }
3085             else if ( !smError->myBadElements.empty() ) // bad surface mesh
3086             {
3087               if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
3088                 smError.reset();
3089             }
3090           }
3091           pb3D = pb3D || ( smError && smError->IsKO() );
3092         }
3093     if ( !pb2D && !pb3D )
3094       err = 0; // no fatal errors, only warnings
3095   }
3096
3097   ngLib._isComputeOk = !err;
3098
3099   return !err;
3100 }
3101
3102 //=============================================================================
3103 /*!
3104  * Evaluate
3105  */
3106 //=============================================================================
3107 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3108 {
3109   netgen::MeshingParameters& mparams = netgen::mparam;
3110
3111
3112   // -------------------------
3113   // Prepare OCC geometry
3114   // -------------------------
3115   netgen::OCCGeometry occgeo;
3116   list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
3117   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3118   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
3119
3120   bool tooManyElems = false;
3121   const int hugeNb = std::numeric_limits<int>::max() / 100;
3122
3123   // ----------------
3124   // evaluate 1D 
3125   // ----------------
3126   // pass 1D simple parameters to NETGEN
3127   if ( _simpleHyp )
3128   {
3129     // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3130     mparams.uselocalh = false;
3131     mparams.grading = 0.8; // not limitited size growth
3132
3133     if ( _simpleHyp->GetNumberOfSegments() )
3134       // nb of segments
3135       mparams.maxh = occgeo.boundingbox.Diam();
3136     else
3137       // segment length
3138       mparams.maxh = _simpleHyp->GetLocalLength();
3139   }
3140
3141   if ( mparams.maxh == 0.0 )
3142     mparams.maxh = occgeo.boundingbox.Diam();
3143   if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3144     mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3145
3146   // let netgen create _ngMesh and calculate element size on not meshed shapes
3147   NETGENPlugin_NetgenLibWrapper ngLib;
3148   netgen::Mesh *ngMesh = NULL;
3149 #ifndef NETGEN_V5
3150   char *optstr = 0;
3151 #endif
3152   int startWith = netgen::MESHCONST_ANALYSE;
3153   int endWith   = netgen::MESHCONST_MESHEDGES;
3154 #ifdef NETGEN_V5
3155   int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
3156 #else
3157   int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
3158 #endif
3159
3160   if(netgen::multithread.terminate)
3161     return false;
3162
3163   ngLib.setMesh(( Ng_Mesh*) ngMesh );
3164   if (err) {
3165     if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3166       sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3167     return false;
3168   }
3169   if ( _simpleHyp )
3170   {
3171     // Pass 1D simple parameters to NETGEN
3172     // --------------------------------
3173     int      nbSeg = _simpleHyp->GetNumberOfSegments();
3174     double segSize = _simpleHyp->GetLocalLength();
3175     for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3176     {
3177       const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3178       if ( nbSeg )
3179         segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3180       setLocalSize( e, segSize, *ngMesh );
3181     }
3182   }
3183   else // if ( ! _simpleHyp )
3184   {
3185     // Local size on shapes
3186     SetLocalSize( occgeo, *ngMesh );
3187   }
3188   // calculate total nb of segments and length of edges
3189   double fullLen = 0.0;
3190   int fullNbSeg = 0;
3191   int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3192   TopTools_DataMapOfShapeInteger Edge2NbSeg;
3193   for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3194   {
3195     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3196     if( !Edge2NbSeg.Bind(E,0) )
3197       continue;
3198
3199     double aLen = SMESH_Algo::EdgeLength(E);
3200     fullLen += aLen;
3201
3202     vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3203     if ( aVec.empty() )
3204       aVec.resize( SMDSEntity_Last, 0);
3205     else
3206       fullNbSeg += aVec[ entity ];
3207   }
3208
3209   // store nb of segments computed by Netgen
3210   NCollection_Map<Link> linkMap;
3211   for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3212   {
3213     const netgen::Segment& seg = ngMesh->LineSegment(i);
3214     Link link(seg[0], seg[1]);
3215     if ( !linkMap.Add( link )) continue;
3216     int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3217     if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3218     {
3219       vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3220       aVec[ entity ]++;
3221     }
3222   }
3223   // store nb of nodes on edges computed by Netgen
3224   TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3225   for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3226   {
3227     vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3228     if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3229       aVec[SMDSEntity_Node] = mparams.secondorder > 0  ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3230
3231     fullNbSeg += aVec[ entity ];
3232     Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3233   }
3234   if ( fullNbSeg == 0 )
3235     return false;
3236
3237   // ----------------
3238   // evaluate 2D 
3239   // ----------------
3240   if ( _simpleHyp ) {
3241     if ( double area = _simpleHyp->GetMaxElementArea() ) {
3242       // face area
3243       mparams.maxh = sqrt(2. * area/sqrt(3.0));
3244       mparams.grading = 0.4; // moderate size growth
3245     }
3246     else {
3247       // length from edges
3248       mparams.maxh = fullLen/fullNbSeg;
3249       mparams.grading = 0.2; // slow size growth
3250     }
3251   }
3252   mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3253   mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3254
3255   for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3256   {
3257     TopoDS_Face F = TopoDS::Face( exp.Current() );
3258     SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3259     GProp_GProps G;
3260     BRepGProp::SurfaceProperties(F,G);
3261     double anArea = G.Mass();
3262     tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3263     int nb1d = 0;
3264     if ( !tooManyElems )
3265     {
3266       TopTools_MapOfShape egdes;
3267       for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3268         if ( egdes.Add( exp1.Current() ))
3269           nb1d += Edge2NbSeg.Find(exp1.Current());
3270     }
3271     int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3272     int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3273
3274     vector<int> aVec(SMDSEntity_Last, 0);
3275     if( mparams.secondorder > 0 ) {
3276       int nb1d_in = (nbFaces*3 - nb1d) / 2;
3277       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3278       aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3279     }
3280     else {
3281       aVec[SMDSEntity_Node] = Max ( nbNodes, 0  );
3282       aVec[SMDSEntity_Triangle] = nbFaces;
3283     }
3284     aResMap[sm].swap(aVec);
3285   }
3286
3287   // ----------------
3288   // evaluate 3D
3289   // ----------------
3290   if(_isVolume) {
3291     // pass 3D simple parameters to NETGEN
3292     const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3293       dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3294     if ( simple3d ) {
3295       if ( double vol = simple3d->GetMaxElementVolume() ) {
3296         // max volume
3297         mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3298         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3299       }
3300       else {
3301         // using previous length from faces
3302       }
3303       mparams.grading = 0.4;
3304       mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3305     }
3306     GProp_GProps G;
3307     BRepGProp::VolumeProperties(_shape,G);
3308     double aVolume = G.Mass();
3309     double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3310     tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3311     int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3312     int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3313     vector<int> aVec(SMDSEntity_Last, 0 );
3314     if ( tooManyElems ) // avoid FPE
3315     {
3316       aVec[SMDSEntity_Node] = hugeNb;
3317       aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3318     }
3319     else
3320     {
3321       if( mparams.secondorder > 0 ) {
3322         aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3323         aVec[SMDSEntity_Quad_Tetra] = nbVols;
3324       }
3325       else {
3326         aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3327         aVec[SMDSEntity_Tetra] = nbVols;
3328       }
3329     }
3330     SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3331     aResMap[sm].swap(aVec);
3332   }
3333
3334   return true;
3335 }
3336
3337 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3338                                         const int *       algoProgressTic,
3339                                         const double *    algoProgress) const
3340 {
3341   ((int&) _progressTic ) = *algoProgressTic + 1;
3342
3343   if ( !_occgeom ) return 0;
3344
3345   double progress = -1;
3346   if ( !_isVolume )
3347   {
3348     if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3349     {
3350       ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3351     }
3352     else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3353     {
3354       int doneShapeIndex = -1;
3355       while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3356               _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3357         doneShapeIndex++;
3358       if ( doneShapeIndex+1 != _curShapeIndex )
3359       {
3360         ((int&) _curShapeIndex) = doneShapeIndex+1;
3361         double    doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3362         double         doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3363         ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
3364         // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3365         //      << " " << doneTime / _totalTime / _progressTic << endl;
3366       }
3367     }
3368   }
3369   else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3370   {
3371     int curShapeIndex = _curShapeIndex;
3372     if ( _ngMesh->GetNE() > 0 )
3373     {
3374       netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3375       curShapeIndex = el.GetIndex();
3376     }
3377     if ( curShapeIndex != _curShapeIndex )
3378     {
3379       ((int&) _curShapeIndex) = curShapeIndex;
3380       double    doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3381       double         doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3382       ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
3383       // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3384       //      << " " << doneTime / _totalTime / _progressTic << endl;
3385     }
3386   }
3387
3388   if ( _ticTime > 0 )
3389     progress  = Max( *algoProgressTic * _ticTime, *algoProgress );
3390
3391   if ( progress > 0 )
3392   {
3393     if ( _isVolume &&
3394          netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3395          progress > voluMeshingTime )
3396     {
3397       progress = voluMeshingTime;
3398       ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3399     }
3400     ((int&) *algoProgressTic )++;
3401     ((double&) *algoProgress) = progress;
3402   }
3403   //cout << progress << " "  << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3404
3405   return Min( progress, 0.99 );
3406 }
3407
3408 //================================================================================
3409 /*!
3410  * \brief Read mesh entities preventing successful computation from "test.out" file
3411  */
3412 //================================================================================
3413
3414 SMESH_ComputeErrorPtr
3415 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3416 {
3417   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3418     (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3419   SMESH_File file("test.out");
3420   vector<int> two(2);
3421   vector<int> three1(3), three2(3);
3422   const char* badEdgeStr = " multiple times in surface mesh";
3423   const int   badEdgeStrLen = strlen( badEdgeStr );
3424   const int   nbNodes = nodeVec.size();
3425
3426   while( !file.eof() )
3427   {
3428     if ( strncmp( file, "Edge ", 5 ) == 0 &&
3429          file.getInts( two ) &&
3430          strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3431          two[0] < nbNodes  &&  two[1] < nbNodes )
3432     {
3433       err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3434       file += badEdgeStrLen;
3435     }
3436     else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3437     {
3438 // Intersecting: 
3439 // openelement 18 with open element 126
3440 // 41  36  38  
3441 // 69  70  72
3442       file.getLine();
3443       const char* pos = file;
3444       bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3445       ok = ok && file.getInts( two );
3446       ok = ok && file.getInts( three1 );
3447       ok = ok && file.getInts( three2 );
3448       for ( int i = 0; ok && i < 3; ++i )
3449         ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3450       for ( int i = 0; ok && i < 3; ++i ) 
3451         ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3452       if ( ok )
3453       {
3454         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3455                                                             nodeVec[ three1[1]],
3456                                                             nodeVec[ three1[2]]));
3457         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3458                                                             nodeVec[ three2[1]],
3459                                                             nodeVec[ three2[2]]));
3460         err->myComment = "Intersecting triangles";
3461       }
3462       else
3463       {
3464         file.setPos( pos );
3465       }
3466     }
3467     else
3468     {
3469       ++file;
3470     }
3471   }
3472
3473 #ifdef _DEBUG_
3474   size_t nbBadElems = err->myBadElements.size();
3475   if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3476 #endif
3477
3478   return err;
3479 }
3480
3481 //================================================================================
3482 /*!
3483  * \brief Write a python script creating an equivalent SALOME mesh.
3484  * This is useful to see what mesh is passed as input for the next step of mesh
3485  * generation (of mesh of higher dimension)
3486  */
3487 //================================================================================
3488
3489 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3490 {
3491   const char*  pyFile = "/tmp/ngMesh.py";
3492   ofstream outfile( pyFile, ios::out );
3493   if ( !outfile ) return;
3494
3495   outfile << "import SMESH" << endl
3496           << "from salome.smesh import smeshBuilder" << endl
3497           << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3498           << "mesh = smesh.Mesh()" << endl << endl;
3499
3500   using namespace netgen;
3501   PointIndex pi;
3502   for (pi = PointIndex::BASE; 
3503        pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3504   {
3505     outfile << "mesh.AddNode( ";
3506     outfile << (*ngMesh)[pi](0) << ", ";
3507     outfile << (*ngMesh)[pi](1) << ", ";
3508     outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3509   }
3510
3511   int nbDom = ngMesh->GetNDomains();
3512   for ( int i = 0; i < nbDom; ++i )
3513     outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3514
3515   SurfaceElementIndex sei;
3516   for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3517   {
3518     outfile << "mesh.AddFace([ ";
3519     Element2d sel = (*ngMesh)[sei];
3520     for (int j = 0; j < sel.GetNP(); j++)
3521       outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3522     if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3523     outfile << endl;
3524
3525     if ((*ngMesh)[sei].GetIndex())
3526     {
3527       if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3528         outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3529       if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3530         outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3531     }
3532   }
3533
3534   for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3535   {
3536     Element el = (*ngMesh)[ei];
3537     outfile << "mesh.AddVolume([ ";
3538     for (int j = 0; j < el.GetNP(); j++)
3539       outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3540     outfile << endl;
3541   }
3542
3543   for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3544   {
3545     const Segment & seg = ngMesh->LineSegment (i);
3546     outfile << "mesh.AddEdge([ "
3547             << seg[0] << ", "
3548             << seg[1] << " ])" << endl;
3549   }
3550   cout << "Write " << pyFile << endl;
3551 }
3552
3553 //================================================================================
3554 /*!
3555  * \brief Constructor of NETGENPlugin_ngMeshInfo
3556  */
3557 //================================================================================
3558
3559 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3560   _copyOfLocalH(0)
3561 {
3562   if ( ngMesh )
3563   {
3564     _nbNodes    = ngMesh->GetNP();
3565     _nbSegments = ngMesh->GetNSeg();
3566     _nbFaces    = ngMesh->GetNSE();
3567     _nbVolumes  = ngMesh->GetNE();
3568   }
3569   else
3570   {
3571     _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3572   }
3573 }
3574
3575 //================================================================================
3576 /*!
3577  * \brief Copy LocalH member from one netgen mesh to another
3578  */
3579 //================================================================================
3580
3581 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3582                                               netgen::Mesh* toMesh )
3583 {
3584   if ( !fromMesh->LocalHFunctionGenerated() ) return;
3585   if ( !toMesh->LocalHFunctionGenerated() )
3586 #ifdef NETGEN_V5
3587     toMesh->CalcLocalH(netgen::mparam.grading);
3588 #else
3589     toMesh->CalcLocalH();
3590 #endif
3591
3592   const size_t size = sizeof( netgen::LocalH );
3593   _copyOfLocalH = new char[ size ];
3594   memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3595   memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3596 }
3597
3598 //================================================================================
3599 /*!
3600  * \brief Restore LocalH member of a netgen mesh
3601  */
3602 //================================================================================
3603
3604 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3605 {
3606   if ( _copyOfLocalH )
3607   {
3608     const size_t size = sizeof( netgen::LocalH );
3609     memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3610     delete [] _copyOfLocalH;
3611     _copyOfLocalH = 0;
3612   }
3613 }
3614
3615 //================================================================================
3616 /*!
3617  * \brief Find "internal" sub-shapes
3618  */
3619 //================================================================================
3620
3621 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh&         mesh,
3622                                                 const TopoDS_Shape& shape,
3623                                                 bool                is3D )
3624   : _mesh( mesh ), _is3D( is3D )
3625 {
3626   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3627
3628   TopExp_Explorer f,e;
3629   for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3630   {
3631     int faceID = meshDS->ShapeToIndex( f.Current() );
3632
3633     // find not computed internal edges
3634
3635     for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3636       if ( e.Current().Orientation() == TopAbs_INTERNAL )
3637       {
3638         SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3639         if ( eSM->IsEmpty() )
3640         {
3641           _e2face.insert( make_pair( eSM->GetId(), faceID ));
3642           for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3643             _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3644         }
3645       }
3646
3647     // find internal vertices in a face
3648     set<int> intVV; // issue 0020850 where same vertex is twice in a face
3649     for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3650       if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3651       {
3652         int vID = meshDS->ShapeToIndex( fSub.Value() );
3653         if ( intVV.insert( vID ).second )
3654           _f2v[ faceID ].push_back( vID );
3655       }
3656
3657     if ( is3D )
3658     {
3659       // find internal faces and their subshapes where nodes are to be doubled
3660       //  to make a crack with non-sewed borders
3661
3662       if ( f.Current().Orientation() == TopAbs_INTERNAL )
3663       {
3664         _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3665
3666         // egdes
3667         list< TopoDS_Shape > edges;
3668         for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3669           if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3670           {
3671             _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3672             edges.push_back( e.Current() );
3673             // find border faces
3674             PShapeIteratorPtr fIt =
3675               SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3676             while ( const TopoDS_Shape* pFace = fIt->next() )
3677               if ( !pFace->IsSame( f.Current() ))
3678                 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3679           }
3680         // vertices
3681         // we consider vertex internal if it is shared by more than one internal edge
3682         list< TopoDS_Shape >::iterator edge = edges.begin();
3683         for ( ; edge != edges.end(); ++edge )
3684           for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3685           {
3686             set<int> internalEdges;
3687             PShapeIteratorPtr eIt =
3688               SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3689             while ( const TopoDS_Shape* pEdge = eIt->next() )
3690             {
3691               int edgeID = meshDS->ShapeToIndex( *pEdge );
3692               if ( isInternalShape( edgeID ))
3693                 internalEdges.insert( edgeID );
3694             }
3695             if ( internalEdges.size() > 1 )
3696               _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3697           }
3698       }
3699     }
3700   } // loop on geom faces
3701
3702   // find vertices internal in solids
3703   if ( is3D )
3704   {
3705     for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3706     {
3707       int soID = meshDS->ShapeToIndex( so.Current() );
3708       for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3709         if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3710           _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3711     }
3712   }
3713 }
3714
3715 //================================================================================
3716 /*!
3717  * \brief Find mesh faces on non-internal geom faces sharing internal edge
3718  * some nodes of which are to be doubled to make the second border of the "crack"
3719  */
3720 //================================================================================
3721
3722 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3723 {
3724   if ( _intShapes.empty() ) return;
3725
3726   SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3727   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3728
3729   // loop on internal geom edges
3730   set<int>::const_iterator intShapeId = _intShapes.begin();
3731   for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3732   {
3733     const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3734     if ( s.ShapeType() != TopAbs_EDGE ) continue;
3735
3736     // get internal and non-internal geom faces sharing the internal edge <s>
3737     int intFace = 0;
3738     set<int>::iterator bordFace = _borderFaces.end();
3739     PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3740     while ( const TopoDS_Shape* pFace = faces->next() )
3741     {
3742       int faceID = meshDS->ShapeToIndex( *pFace );
3743       if ( isInternalShape( faceID ))
3744         intFace = faceID;
3745       else
3746         bordFace = _borderFaces.insert( faceID ).first;
3747     }
3748     if ( bordFace == _borderFaces.end() || !intFace ) continue;
3749
3750     // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3751     set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3752     list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3753     int nbSuspectFaces = 0;
3754     SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3755     if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3756     SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3757     while ( smIt->more() )
3758     {
3759       SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3760       if ( !sm ) continue;
3761       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3762       while ( nIt->more() )
3763       {
3764         const SMDS_MeshNode* nOnEdge = nIt->next();
3765         SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3766         while ( fIt->more() )
3767         {
3768           const SMDS_MeshElement* f = fIt->next();
3769           const int nbNodes = f->NbCornerNodes();
3770           if ( intFaceSM->Contains( f ))
3771           {
3772             for ( int i = 0; i < nbNodes; ++i )
3773               links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3774           }
3775           else
3776           {
3777             int nbDblNodes = 0;
3778             for ( int i = 0; i < nbNodes; ++i )
3779               nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3780             if ( nbDblNodes )
3781               suspectFaces[ nbDblNodes < 2 ].push_back( f );
3782             nbSuspectFaces++;
3783           }
3784         }
3785       }
3786     }
3787     // suspectFaces[0] having link with same orientation as mesh faces on
3788     // the internal geom face are <borderElems>. suspectFaces[1] have
3789     // only one node on edge <s>, we decide on them later (at the 2nd loop)
3790     // by links of <borderElems> found at the 1st and 2nd loops
3791     set< SMESH_OrientedLink > borderLinks;
3792     for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3793     {
3794       list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3795       for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3796       {
3797         const SMDS_MeshElement* f = *fIt;
3798         bool isBorder = false, linkFound = false, borderLinkFound = false;
3799         list< SMESH_OrientedLink > faceLinks;
3800         int nbNodes = f->NbCornerNodes();
3801         for ( int i = 0; i < nbNodes; ++i )
3802         {
3803           SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3804           faceLinks.push_back( link );
3805           if ( !linkFound )
3806           {
3807             set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3808             if ( foundLink != links.end() )
3809             {
3810               linkFound= true;
3811               isBorder = ( foundLink->_reversed == link._reversed );
3812               if ( !isBorder && !isPostponed ) break;
3813               faceLinks.pop_back();
3814             }
3815             else if ( isPostponed && !borderLinkFound )
3816             {
3817               foundLink = borderLinks.find( link );
3818               if ( foundLink != borderLinks.end() )
3819               {
3820                 borderLinkFound = true;
3821                 isBorder = ( foundLink->_reversed != link._reversed );
3822               }
3823             }
3824           }
3825         }
3826         if ( isBorder )
3827         {
3828           borderElems.insert( f );
3829           borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3830         }
3831         else if ( !linkFound && !borderLinkFound )
3832         {
3833           suspectFaces[1].push_back( f );
3834           if ( nbF > 2 * nbSuspectFaces )
3835             break; // dead loop protection
3836         }
3837       }
3838     }
3839   }
3840 }
3841
3842 //================================================================================
3843 /*!
3844  * \brief put internal shapes in maps and fill in submeshes to precompute
3845  */
3846 //================================================================================
3847
3848 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3849                                                TopTools_IndexedMapOfShape& emap,
3850                                                TopTools_IndexedMapOfShape& vmap,
3851                                                list< SMESH_subMesh* > smToPrecompute[])
3852 {
3853   if ( !hasInternalEdges() ) return;
3854   map<int,int>::const_iterator ev_face = _e2face.begin();
3855   for ( ; ev_face != _e2face.end(); ++ev_face )
3856   {
3857     const TopoDS_Shape& ev   = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3858     const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3859
3860     ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3861     fmap.Add( face );
3862     //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3863
3864     smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3865   }
3866 }
3867
3868 //================================================================================
3869 /*!
3870  * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3871  */
3872 //================================================================================
3873
3874 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3875                                                TopTools_IndexedMapOfShape& emap,
3876                                                list< SMESH_subMesh* >&     intFaceSM,
3877                                                list< SMESH_subMesh* >&     boundarySM)
3878 {
3879   if ( !hasInternalFaces() ) return;
3880
3881   // <fmap> and <emap> are for not yet meshed shapes
3882   // <intFaceSM> is for submeshes of faces
3883   // <boundarySM> is for meshed edges and vertices
3884
3885   intFaceSM.clear();
3886   boundarySM.clear();
3887
3888   set<int> shapeIDs ( _intShapes );
3889   if ( !_borderFaces.empty() )
3890     shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3891
3892   set<int>::const_iterator intS = shapeIDs.begin();
3893   for ( ; intS != shapeIDs.end(); ++intS )
3894   {
3895     SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3896
3897     if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3898
3899     intFaceSM.push_back( sm );
3900
3901     // add submeshes of not computed internal faces
3902     if ( !sm->IsEmpty() ) continue;
3903
3904     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3905     while ( smIt->more() )
3906     {
3907       sm = smIt->next();
3908       const TopoDS_Shape& s = sm->GetSubShape();
3909
3910       if ( sm->IsEmpty() )
3911       {
3912         // not yet meshed
3913         switch ( s.ShapeType() ) {
3914         case TopAbs_FACE: fmap.Add ( s ); break;
3915         case TopAbs_EDGE: emap.Add ( s ); break;
3916         default:;
3917         }
3918       }
3919       else
3920       {
3921         if ( s.ShapeType() != TopAbs_FACE )
3922           boundarySM.push_back( sm );
3923       }
3924     }
3925   }
3926 }
3927
3928 //================================================================================
3929 /*!
3930  * \brief Return true if given shape is to be precomputed in order to be correctly
3931  * added to netgen mesh
3932  */
3933 //================================================================================
3934
3935 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3936 {
3937   int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3938   switch ( s.ShapeType() ) {
3939   case TopAbs_FACE  : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3940   case TopAbs_EDGE  : return isInternalEdge( shapeID );
3941   case TopAbs_VERTEX: break;
3942   default:;
3943   }
3944   return false;
3945 }
3946
3947 //================================================================================
3948 /*!
3949  * \brief Return SMESH
3950  */
3951 //================================================================================
3952
3953 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3954 {
3955   return const_cast<SMESH_Mesh&>( _mesh );
3956 }
3957
3958 //================================================================================
3959 /*!
3960  * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
3961  */
3962 //================================================================================
3963
3964 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
3965 {
3966   static int theCouner = 0;
3967   return theCouner;
3968 }
3969
3970 //================================================================================
3971 /*!
3972  * \brief Initialize netgen library
3973  */
3974 //================================================================================
3975
3976 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3977 {
3978   if ( instanceCounter() == 0 )
3979     Ng_Init();
3980
3981   ++instanceCounter();
3982
3983   _isComputeOk      = false;
3984   _coutBuffer       = NULL;
3985   _ngcout           = NULL;
3986   _ngcerr           = NULL;
3987   if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
3988   {
3989     // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3990     _outputFileName = getOutputFileName();
3991     _ngcout         = netgen::mycout;
3992     _ngcerr         = netgen::myerr;
3993     netgen::mycout  = new ofstream ( _outputFileName.c_str() );
3994     netgen::myerr   = netgen::mycout;
3995     _coutBuffer     = std::cout.rdbuf();
3996 #ifdef _DEBUG_
3997     cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3998 #else
3999     std::cout.rdbuf( netgen::mycout->rdbuf() );
4000 #endif
4001   }
4002
4003   _ngMesh = Ng_NewMesh();
4004 }
4005
4006 //================================================================================
4007 /*!
4008  * \brief Finish using netgen library
4009  */
4010 //================================================================================
4011
4012 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4013 {
4014   --instanceCounter();
4015
4016   Ng_DeleteMesh( _ngMesh );
4017   Ng_Exit();
4018   RemoveTmpFiles();
4019   if ( _coutBuffer )
4020     std::cout.rdbuf( _coutBuffer );
4021 #ifdef _DEBUG_
4022   if( _isComputeOk )
4023 #endif
4024     removeOutputFile();
4025 }
4026
4027 //================================================================================
4028 /*!
4029  * \brief Set netgen mesh to delete at destruction
4030  */
4031 //================================================================================
4032
4033 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4034 {
4035   if ( _ngMesh )
4036     Ng_DeleteMesh( _ngMesh );
4037   _ngMesh = mesh;
4038 }
4039
4040 //================================================================================
4041 /*!
4042  * \brief Return a unique file name
4043  */
4044 //================================================================================
4045
4046 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4047 {
4048   std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4049
4050   TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
4051   aGenericName += "NETGEN_";
4052 #ifndef WIN32
4053   aGenericName += getpid();
4054 #else
4055   aGenericName += _getpid();
4056 #endif
4057   aGenericName += "_";
4058   aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4059   aGenericName += ".out";
4060
4061   return aGenericName.ToCString();
4062 }
4063
4064 //================================================================================
4065 /*!
4066  * \brief Remove "test.out" and "problemfaces" files in current directory
4067  */
4068 //================================================================================
4069
4070 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4071 {
4072   bool rm =  SMESH_File("test.out").remove() ;
4073 #ifndef WIN32
4074   if ( rm && netgen::testout && instanceCounter() == 0 )
4075   {
4076     delete netgen::testout;
4077     netgen::testout = 0;
4078   }
4079 #endif
4080   SMESH_File("problemfaces").remove();
4081   SMESH_File("occmesh.rep").remove();
4082 }
4083
4084 //================================================================================
4085 /*!
4086  * \brief Remove file with netgen output
4087  */
4088 //================================================================================
4089
4090 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4091 {
4092   if ( !_outputFileName.empty() )
4093   {
4094     if ( _ngcout )
4095     {
4096       delete netgen::mycout;
4097       netgen::mycout = _ngcout;
4098       netgen::myerr  = _ngcerr;
4099       _ngcout        = 0;
4100     }
4101     string    tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4102     string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4103     SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
4104     aFiles->length(1);
4105     aFiles[0] = aFileName.c_str();
4106
4107     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
4108   }
4109 }