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