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