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