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