]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
Join modifications from BR_Dev_For_4_0 tag V4_1_1.
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 // Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS, L3S, LJLL, MENSI
3 //
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
8 //
9 // This library is distributed in the hope that it will be useful
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20 // File      : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author    : Edward AGAPOV (OCC)
22 // Project   : SALOME
23
24
25 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
26
27 #include "NETGENPlugin_Mesher.hxx"
28
29 #include "SMDS_MeshElement.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMESHDS_Mesh.hxx"
32 #include "SMESH_Comment.hxx"
33 #include "SMESH_Gen.hxx"
34 #include "SMESH_Mesh.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "StdMeshers_FaceSide.hxx"
37 #include "StdMeshers_MaxElementArea.hxx"
38 #include "StdMeshers_LengthFromEdges.hxx"
39 #include "StdMeshers_QuadranglePreference.hxx"
40
41 #include <Standard_ErrorHandler.hxx>
42 #include <Standard_Failure.hxx>
43
44 #include "utilities.h"
45
46 #include <list>
47 #include <vector>
48
49 /*
50   Netgen include files
51 */
52 namespace nglib {
53 #include <nglib.h>
54 }
55 #define OCCGEOMETRY
56 #include <occgeom.hpp>
57 #include <meshing.hpp>
58 //#include <meshtype.hpp>
59 namespace netgen {
60   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
61   /*extern*/ MeshingParameters mparam;
62 }
63
64 using namespace std;
65 using namespace netgen;
66 using namespace nglib;
67
68 //=============================================================================
69 /*!
70  *  
71  */
72 //=============================================================================
73
74 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
75                                                          SMESH_Gen* gen)
76   : SMESH_2D_Algo(hypId, studyId, gen)
77 {
78   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
79   _name = "NETGEN_2D_ONLY";
80
81   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
82
83   _compatibleHypothesis.push_back("MaxElementArea");
84   _compatibleHypothesis.push_back("LengthFromEdges");
85   _compatibleHypothesis.push_back("QuadranglePreference");
86
87   _hypMaxElementArea = 0;
88   _hypLengthFromEdges = 0;
89   _hypQuadranglePreference = 0;
90 }
91
92 //=============================================================================
93 /*!
94  *  
95  */
96 //=============================================================================
97
98 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
99 {
100   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
101 }
102
103 //=============================================================================
104 /*!
105  *  
106  */
107 //=============================================================================
108
109 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
110                                                    const TopoDS_Shape& aShape,
111                                                    Hypothesis_Status&  aStatus)
112 {
113   _hypMaxElementArea = 0;
114   _hypLengthFromEdges = 0;
115   _hypQuadranglePreference = 0;
116
117   aStatus = HYP_MISSING;
118
119   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
120
121   if (hyps.empty()) return false;  // can't work with no hypothesis
122
123   list<const SMESHDS_Hypothesis*>::const_iterator ith;
124   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
125   {
126     const SMESHDS_Hypothesis* hyp = (*ith);
127
128     string hypName = hyp->GetName();
129
130     if      ( hypName == "MaxElementArea")
131       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
132     else if ( hypName == "LengthFromEdges" )
133       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
134     else if ( hypName == "QuadranglePreference" )
135       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
136     else {
137       aStatus = HYP_INCOMPATIBLE;
138       return false;
139     }
140   }
141
142   if ( _hypMaxElementArea && _hypLengthFromEdges ) {
143     aStatus = HYP_CONCURENT;
144     return false;
145   }
146
147   if ( _hypMaxElementArea || _hypLengthFromEdges )
148     aStatus = HYP_OK;
149
150   return aStatus == HYP_OK;
151 }
152
153 //================================================================================
154 /*!
155  * \brief Fill netgen mesh with segments
156   * \retval SMESH_ComputeErrorPtr - error description
157  */
158 //================================================================================
159
160 static TError AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
161                                 OCCGeometry&                     geom,
162                                 const TSideVector&               wires,
163                                 SMESH_MesherHelper&              helper,
164                                 vector< const SMDS_MeshNode* > & nodeVec)
165 {
166   // ----------------------------
167   // Check wires and count nodes
168   // ----------------------------
169   int nbNodes = 0;
170   for ( int iW = 0; iW < wires.size(); ++iW )
171   {
172     StdMeshers_FaceSidePtr wire = wires[ iW ];
173     if ( wire->MissVertexNode() )
174       return TError
175         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
176       
177     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
178     if ( uvPtVec.size() != wire->NbPoints() )
179       return TError
180         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,
181                                 SMESH_Comment("Unexpected nb of points on wire ") << iW
182                                 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints()));
183     nbNodes += wire->NbSegments();
184   }
185   nodeVec.reserve( nbNodes );
186
187   // -----------------
188   // Fill netgen mesh
189   // -----------------
190
191 //   netgen::Box<3> bb = geom.GetBoundingBox();
192 //   bb.Increase (bb.Diam()/10);
193 //   ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
194
195   const int faceID = 1, solidID = 0;
196   ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
197
198   for ( int iW = 0; iW < wires.size(); ++iW )
199   {
200     StdMeshers_FaceSidePtr wire = wires[ iW ];
201     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
202
203     int firstPointID = ngMesh.GetNP() + 1;
204     int edgeID = 1, posID = -2;
205     for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
206     {
207       // Add the first point of a segment
208       const SMDS_MeshNode * n = uvPtVec[ i ].node;
209       const int posShapeID = n->GetPosition()->GetShapeId();
210
211       // skip nodes on degenerated edges
212       if ( helper.IsDegenShape( posShapeID ) &&
213            helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
214         continue;
215
216       nodeVec.push_back( n );
217
218       MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
219       ngMesh.AddPoint ( mp, 1, EDGEPOINT );
220
221       // Add the segment
222       Segment seg;
223
224       seg.p1 = ngMesh.GetNP();          // ng node id
225       seg.p2 = seg.p1 + 1;              // ng node id
226       seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
227       seg.si = faceID;                  // = geom.fmap.FindIndex (face);
228
229       for ( int iEnd = 0; iEnd < 2; ++iEnd)
230       {
231         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
232
233         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
234         seg.epgeominfo[ iEnd ].u    = pnt.u;
235         seg.epgeominfo[ iEnd ].v    = pnt.v;
236
237         // find out edge id and node parameter on edge
238         bool onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
239         if ( onVertex || posShapeID != posID )
240         {
241           // get edge id
242           double normParam = pnt.normParam;
243           if ( onVertex )
244             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
245           const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
246           edgeID = geom.emap.FindIndex( edge );
247           posID  = posShapeID;
248           if ( onVertex ) // param on curve is different on each of two edges
249             seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
250         }
251         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
252       }
253
254       ngMesh.AddSegment (seg);
255
256 //       cout << "Segment: " << seg.edgenr << endl
257 //            << "\tp1: " << seg.p1 << endl
258 //            << "\tp2: " << seg.p2 << endl
259 //            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
260 //            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
261 //            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
262 //            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
263 //            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
264 //            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
265     }
266     Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
267     seg.p2 = firstPointID;
268   }
269
270   ngMesh.CalcSurfacesOfNode();  
271
272   return TError();
273 }
274
275 //=============================================================================
276 /*!
277  *Here we are going to use the NETGEN mesher
278  */
279 //=============================================================================
280
281 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
282                                           const TopoDS_Shape& aShape)
283 {
284   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
285
286   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
287   int faceID = meshDS->ShapeToIndex( aShape );
288
289   SMESH_MesherHelper helper(aMesh);
290   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
291   helper.SetElementsOnShape( true );
292   const bool ignoreMediumNodes = _quadraticMesh;
293   
294   // ------------------------
295   // get all edges of a face
296   // ------------------------
297   const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
298   TError problem;
299   TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
300   if ( problem && !problem->IsOK() )
301     return error( problem );
302   int nbWires = wires.size();
303   if ( nbWires == 0 )
304     return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
305   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
306     return error(COMPERR_BAD_INPUT_MESH,
307                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
308
309   // -------------------------
310   // Make input netgen mesh
311   // -------------------------
312
313   Ng_Init();
314   netgen::Mesh * ngMesh = new netgen::Mesh ();
315
316   netgen::OCCGeometry occgeo;
317   NETGENPlugin_Mesher::PrepareOCCgeometry( occgeo, F );
318
319   vector< const SMDS_MeshNode* > nodeVec;
320   problem = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
321   if ( problem && !problem->IsOK() ) {
322     delete ngMesh; Ng_Exit();
323     return error( problem );
324   }
325
326   // --------------------
327   // compute edge length
328   // --------------------
329
330   double edgeLength = 0;
331   if (_hypLengthFromEdges)
332   {
333     int nbSegments = 0;
334     for ( int iW = 0; iW < nbWires; ++iW )
335     {
336       edgeLength += wires[ iW ]->Length();
337       nbSegments += wires[ iW ]->NbSegments();
338     }
339     if ( nbSegments )
340       edgeLength /= nbSegments;
341   }
342   if ( _hypMaxElementArea )
343   {
344     double maxArea = _hypMaxElementArea->GetMaxArea();
345     edgeLength = sqrt(2. * maxArea/sqrt(3.0));
346   }
347   if ( edgeLength < DBL_MIN )
348     edgeLength = occgeo.GetBoundingBox().Diam();
349
350   //cout << " edgeLength = " << edgeLength << endl;
351
352   netgen::mparam.maxh = edgeLength;
353   netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
354   //ngMesh->SetGlobalH ( edgeLength );
355
356   // -------------------------
357   // Generate surface mesh
358   // -------------------------
359
360   char *optstr;
361   int startWith = MESHCONST_MESHSURFACE;
362   int endWith   = MESHCONST_OPTSURFACE;
363   int err = 1;
364
365   try {
366 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
367     OCC_CATCH_SIGNALS;
368 #endif
369     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
370   }
371   catch (Standard_Failure& ex) {
372     string comment = ex.DynamicType()->Name();
373     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
374       comment += ": ";
375       comment += ex.GetMessageString();
376     }
377     error(COMPERR_OCC_EXCEPTION, comment);
378   }
379   catch (NgException exc) {
380     error( SMESH_Comment("NgException: ") << exc.What() );
381   }
382   catch (...) {
383     error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
384   }
385
386   // ----------------------------------------------------
387   // Fill the SMESHDS with the generated nodes and faces
388   // ----------------------------------------------------
389
390   int nbNodes = ngMesh->GetNP();
391   int nbFaces = ngMesh->GetNSE();
392
393   int nbInputNodes = nodeVec.size();
394   nodeVec.resize( nbNodes, 0 );
395
396   // add nodes
397   for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
398   {
399     const MeshPoint& ngPoint = ngMesh->Point(i);
400     SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
401     nodeVec[ i-1 ] = node;
402   }
403
404   // create faces
405   bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
406   for ( int i = 1; i <= nbFaces ; ++i )
407   {
408     const Element2d& elem = ngMesh->SurfaceElement(i);
409     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
410     for (int j=1; j <= elem.GetNP(); ++j)
411     {
412       int pind = elem.PNum(j);
413       const SMDS_MeshNode* node = nodeVec.at(pind-1);
414       if ( reverse )
415         nodes[ nodes.size()-j ] = node;
416       else
417         nodes[ j-1 ] = node;
418       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
419       {
420         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
421         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
422       }
423     }
424     SMDS_MeshFace* face = 0;
425     if ( elem.GetType() == TRIG )
426       face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
427     else
428       face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
429   }
430
431   Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
432   Ng_Exit();
433
434   NETGENPlugin_Mesher::RemoveTmpFiles();
435
436   return !err;
437 }