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