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