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