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