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