Salome HOME
0021559: EDF 2175 SMESH: Hexa/Tetra mixed meshes
[modules/smesh.git] / src / SMESH / SMESH_Gen.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 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 //  File   : SMESH_Gen.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28
29 //#define CHRONODEF
30
31 #include "SMESH_Gen.hxx"
32
33 #include "SMDS_Mesh.hxx"
34 #include "SMDS_MeshElement.hxx"
35 #include "SMDS_MeshNode.hxx"
36 #include "SMESHDS_Document.hxx"
37 #include "SMESH_HypoFilter.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40
41 #include "utilities.h"
42 #include "OpUtil.hxx"
43 #include "Utils_ExceptHandlers.hxx"
44
45 #include <TopoDS_Iterator.hxx>
46 #include <LDOMParser.hxx>
47
48 #include "memoire.h"
49
50 using namespace std;
51
52 //=============================================================================
53 /*!
54  *  Constructor
55  */
56 //=============================================================================
57
58 SMESH_Gen::SMESH_Gen()
59 {
60         MESSAGE("SMESH_Gen::SMESH_Gen");
61         _localId = 0;
62         _hypId = 0;
63         _segmentation = _nbSegments = 10;
64         SMDS_Mesh::_meshList.clear();
65         MESSAGE(SMDS_Mesh::_meshList.size());
66         _counters = new counters(100);
67 #ifdef WITH_SMESH_CANCEL_COMPUTE
68         _compute_canceled = false;
69         _sm_current = NULL;
70 #endif
71 }
72
73 //=============================================================================
74 /*!
75  * Destructor
76  */
77 //=============================================================================
78
79 SMESH_Gen::~SMESH_Gen()
80 {
81   MESSAGE("SMESH_Gen::~SMESH_Gen");
82 }
83
84 //=============================================================================
85 /*!
86  * Creates a mesh in a study.
87  * if (theIsEmbeddedMode) { mesh modification commands are not logged }
88  */
89 //=============================================================================
90
91 SMESH_Mesh* SMESH_Gen::CreateMesh(int theStudyId, bool theIsEmbeddedMode)
92   throw(SALOME_Exception)
93 {
94   Unexpect aCatch(SalomeException);
95   MESSAGE("SMESH_Gen::CreateMesh");
96
97   // Get studyContext, create it if it does'nt exist, with a SMESHDS_Document
98   StudyContextStruct *aStudyContext = GetStudyContext(theStudyId);
99
100   // create a new SMESH_mesh object
101   SMESH_Mesh *aMesh = new SMESH_Mesh(_localId++,
102                                      theStudyId,
103                                      this,
104                                      theIsEmbeddedMode,
105                                      aStudyContext->myDocument);
106   aStudyContext->mapMesh[_localId-1] = aMesh;
107
108   return aMesh;
109 }
110
111 //=============================================================================
112 /*!
113  * Compute a mesh
114  */
115 //=============================================================================
116
117 bool SMESH_Gen::Compute(SMESH_Mesh &          aMesh,
118                         const TopoDS_Shape &  aShape,
119                         const bool            anUpward,
120                         const ::MeshDimension aDim,
121                         TSetOfInt*            aShapesId)
122 {
123   MESSAGE("SMESH_Gen::Compute");
124   MEMOSTAT;
125
126   bool ret = true;
127
128   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
129
130   const bool includeSelf = true;
131   const bool complexShapeFirst = true;
132   const int  globalAlgoDim = 100;
133
134   SMESH_subMeshIteratorPtr smIt;
135
136   if ( anUpward ) // is called from below code here
137   {
138     // -----------------------------------------------
139     // mesh all the sub-shapes starting from vertices
140     // -----------------------------------------------
141     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
142     while ( smIt->more() )
143     {
144       SMESH_subMesh* smToCompute = smIt->next();
145
146       // do not mesh vertices of a pseudo shape
147       const TopAbs_ShapeEnum aShType = smToCompute->GetSubShape().ShapeType();
148       if ( !aMesh.HasShapeToMesh() && aShType == TopAbs_VERTEX )
149         continue;
150
151       // check for preview dimension limitations
152       if ( aShapesId && GetShapeDim( aShType ) > (int)aDim )
153       {
154         // clear compute state to not show previous compute errors
155         //  if preview invoked less dimension less than previous
156         smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
157         continue;
158       }
159
160       if (smToCompute->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
161       {
162 #ifdef WITH_SMESH_CANCEL_COMPUTE
163         if (_compute_canceled)
164           return false;
165         _sm_current = smToCompute;
166 #endif
167         smToCompute->ComputeStateEngine( SMESH_subMesh::COMPUTE );
168 #ifdef WITH_SMESH_CANCEL_COMPUTE
169         _sm_current = NULL;
170 #endif
171       }
172
173       // we check all the submeshes here and detect if any of them failed to compute
174       if (smToCompute->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE)
175         ret = false;
176       else if ( aShapesId )
177         aShapesId->insert( smToCompute->GetId() );
178     }
179     //aMesh.GetMeshDS()->Modified();
180     return ret;
181   }
182   else
183   {
184     // -----------------------------------------------------------------
185     // apply algos that DO NOT require Discreteized boundaries and DO NOT
186     // support submeshes, starting from the most complex shapes
187     // and collect submeshes with algos that DO support submeshes
188     // -----------------------------------------------------------------
189     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
190
191     // map to sort sm with same dim algos according to dim of
192     // the shape the algo assigned to (issue 0021217)
193     multimap< int, SMESH_subMesh* > shDim2sm;
194     multimap< int, SMESH_subMesh* >::reverse_iterator shDim2smIt;
195     TopoDS_Shape algoShape;
196     int prevShapeDim = -1;
197
198     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
199     while ( smIt->more() )
200     {
201       SMESH_subMesh* smToCompute = smIt->next();
202       if ( smToCompute->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE )
203         continue;
204
205       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
206       int aShapeDim = GetShapeDim( aSubShape );
207       if ( aShapeDim < 1 ) break;
208       
209       // check for preview dimension limitations
210       if ( aShapesId && aShapeDim > (int)aDim )
211         continue;
212
213       SMESH_Algo* algo = GetAlgo( aMesh, aSubShape, &algoShape );
214       if ( algo && !algo->NeedDiscreteBoundary() )
215       {
216         if ( algo->SupportSubmeshes() )
217         {
218           // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
219           // so that more local algos to go first
220           if ( prevShapeDim != aShapeDim )
221           {
222             prevShapeDim = aShapeDim;
223             for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
224               if ( shDim2smIt->first == globalAlgoDim )
225                 smWithAlgoSupportingSubmeshes.push_back( shDim2smIt->second );
226               else
227                 smWithAlgoSupportingSubmeshes.push_front( shDim2smIt->second );
228             shDim2sm.clear();
229           }
230           // add smToCompute to shDim2sm map
231           if ( algoShape.IsSame( aMesh.GetShapeToMesh() ))
232           {
233             aShapeDim = globalAlgoDim; // to compute last
234           }
235           else
236           {
237             aShapeDim = GetShapeDim( algoShape );
238             if ( algoShape.ShapeType() == TopAbs_COMPOUND )
239             {
240               TopoDS_Iterator it( algoShape );
241               aShapeDim += GetShapeDim( it.Value() );
242             }
243           }
244           shDim2sm.insert( make_pair( aShapeDim, smToCompute ));
245         }
246         else
247         {
248 #ifdef WITH_SMESH_CANCEL_COMPUTE
249           if (_compute_canceled)
250             return false;
251           _sm_current = smToCompute;
252 #endif
253           smToCompute->ComputeStateEngine( SMESH_subMesh::COMPUTE );
254 #ifdef WITH_SMESH_CANCEL_COMPUTE
255           _sm_current = NULL;
256 #endif
257           if ( aShapesId )
258             aShapesId->insert( smToCompute->GetId() );
259         }
260       }
261     }
262     // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
263     for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
264       if ( shDim2smIt->first == globalAlgoDim )
265         smWithAlgoSupportingSubmeshes.push_back( shDim2smIt->second );
266       else
267         smWithAlgoSupportingSubmeshes.push_front( shDim2smIt->second );
268
269     // ------------------------------------------------------------
270     // sort list of submeshes according to mesh order
271     // ------------------------------------------------------------
272     aMesh.SortByMeshOrder( smWithAlgoSupportingSubmeshes );
273
274     // ------------------------------------------------------------
275     // compute submeshes under shapes with algos that DO NOT require
276     // Discreteized boundaries and DO support submeshes
277     // ------------------------------------------------------------
278     list< SMESH_subMesh* >::iterator subIt, subEnd;
279     subIt  = smWithAlgoSupportingSubmeshes.begin();
280     subEnd = smWithAlgoSupportingSubmeshes.end();
281     // start from lower shapes
282     for ( ; subIt != subEnd; ++subIt )
283     {
284       sm = *subIt;
285
286       // get a shape the algo is assigned to
287       if ( !GetAlgo( aMesh, sm->GetSubShape(), & algoShape ))
288         continue; // strange...
289
290       // look for more local algos
291       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
292       while ( smIt->more() )
293       {
294         SMESH_subMesh* smToCompute = smIt->next();
295
296         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
297         const int aShapeDim = GetShapeDim( aSubShape );
298         //if ( aSubShape.ShapeType() == TopAbs_VERTEX ) continue;
299         if ( aShapeDim < 1 ) continue;
300
301         // check for preview dimension limitations
302         if ( aShapesId && GetShapeDim( aSubShape.ShapeType() ) > (int)aDim )
303           continue;
304         
305         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
306         filter
307           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
308           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
309
310         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( aSubShape, filter, true )) {
311           SMESH_Hypothesis::Hypothesis_Status status;
312           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
313             // mesh a lower smToCompute starting from vertices
314             Compute( aMesh, aSubShape, /*anUpward=*/true, aDim, aShapesId );
315         }
316       }
317     }
318     // ----------------------------------------------------------
319     // apply the algos that do not require Discreteized boundaries
320     // ----------------------------------------------------------
321     for ( subIt = smWithAlgoSupportingSubmeshes.begin(); subIt != subEnd; ++subIt )
322     {
323       sm = *subIt;
324       if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
325       {
326         const TopAbs_ShapeEnum aShType = sm->GetSubShape().ShapeType();
327         // check for preview dimension limitations
328         if ( aShapesId && GetShapeDim( aShType ) > (int)aDim )
329           continue;
330
331 #ifdef WITH_SMESH_CANCEL_COMPUTE
332         if (_compute_canceled)
333           return false;
334         _sm_current = sm;
335 #endif
336         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
337 #ifdef WITH_SMESH_CANCEL_COMPUTE
338         _sm_current = NULL;
339 #endif
340         if ( aShapesId )
341           aShapesId->insert( sm->GetId() );
342       }
343     }
344     // -----------------------------------------------
345     // mesh the rest sub-shapes starting from vertices
346     // -----------------------------------------------
347     ret = Compute( aMesh, aShape, /*anUpward=*/true, aDim, aShapesId );
348   }
349
350   MESSAGE( "VSR - SMESH_Gen::Compute() finished, OK = " << ret);
351   MEMOSTAT;
352
353   SMESHDS_Mesh *myMesh = aMesh.GetMeshDS();
354   myMesh->adjustStructure();
355   MESSAGE("*** compactMesh after compute");
356   myMesh->compactMesh();
357   //myMesh->adjustStructure();
358   list<int> listind = myMesh->SubMeshIndices();
359   list<int>::iterator it = listind.begin();
360   int total = 0;
361   for(; it != listind.end(); ++it)
362     {
363       ::SMESHDS_SubMesh *subMesh = myMesh->MeshElements(*it);
364       total +=  subMesh->getSize();
365     }
366   MESSAGE("total elements and nodes in submesh sets:" << total);
367   MESSAGE("Number of node objects " << SMDS_MeshNode::nbNodes);
368   MESSAGE("Number of cell objects " << SMDS_MeshCell::nbCells);
369   //myMesh->dumpGrid();
370   //aMesh.GetMeshDS()->Modified();
371
372   // fix quadratic mesh by bending iternal links near concave boundary
373   if ( aShape.IsSame( aMesh.GetShapeToMesh() ) &&
374        !aShapesId ) // not preview
375   {
376     SMESH_MesherHelper aHelper( aMesh );
377     if ( aHelper.IsQuadraticMesh() != SMESH_MesherHelper::LINEAR )
378       aHelper.FixQuadraticElements();
379   }
380   return ret;
381 }
382
383
384 #ifdef WITH_SMESH_CANCEL_COMPUTE
385 //=============================================================================
386 /*!
387  * Prepare Compute a mesh
388  */
389 //=============================================================================
390 void SMESH_Gen::PrepareCompute(SMESH_Mesh &          aMesh,
391                                const TopoDS_Shape &  aShape)
392 {
393   _compute_canceled = false;
394   _sm_current = NULL;
395 }
396 //=============================================================================
397 /*!
398  * Cancel Compute a mesh
399  */
400 //=============================================================================
401 void SMESH_Gen::CancelCompute(SMESH_Mesh &          aMesh,
402                               const TopoDS_Shape &  aShape)
403 {
404   _compute_canceled = true;
405   if(_sm_current)
406     {
407       _sm_current->ComputeStateEngine( SMESH_subMesh::COMPUTE_CANCELED );
408     }
409 }
410 #endif
411
412 //=============================================================================
413 /*!
414  * Evaluate a mesh
415  */
416 //=============================================================================
417
418 bool SMESH_Gen::Evaluate(SMESH_Mesh &          aMesh,
419                          const TopoDS_Shape &  aShape,
420                          MapShapeNbElems&      aResMap,
421                          const bool            anUpward,
422                          TSetOfInt*            aShapesId)
423 {
424   MESSAGE("SMESH_Gen::Evaluate");
425
426   bool ret = true;
427
428   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
429
430   const bool includeSelf = true;
431   const bool complexShapeFirst = true;
432   SMESH_subMeshIteratorPtr smIt;
433
434   if ( anUpward ) { // is called from below code here
435     // -----------------------------------------------
436     // mesh all the sub-shapes starting from vertices
437     // -----------------------------------------------
438     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
439     while ( smIt->more() ) {
440       SMESH_subMesh* smToCompute = smIt->next();
441
442       // do not mesh vertices of a pseudo shape
443       const TopAbs_ShapeEnum aShType = smToCompute->GetSubShape().ShapeType();
444       //if ( !aMesh.HasShapeToMesh() && aShType == TopAbs_VERTEX )
445       //  continue;
446       if ( !aMesh.HasShapeToMesh() ) {
447         if( aShType == TopAbs_VERTEX || aShType == TopAbs_WIRE ||
448             aShType == TopAbs_SHELL )
449           continue;
450       }
451
452       smToCompute->Evaluate(aResMap);
453       if( aShapesId )
454         aShapesId->insert( smToCompute->GetId() );
455     }
456     return ret;
457   }
458   else {
459     // -----------------------------------------------------------------
460     // apply algos that DO NOT require Discreteized boundaries and DO NOT
461     // support submeshes, starting from the most complex shapes
462     // and collect submeshes with algos that DO support submeshes
463     // -----------------------------------------------------------------
464     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
465     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
466     while ( smIt->more() ) {
467       SMESH_subMesh* smToCompute = smIt->next();
468       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
469       const int aShapeDim = GetShapeDim( aSubShape );
470       if ( aShapeDim < 1 ) break;
471       
472       SMESH_Algo* algo = GetAlgo( aMesh, aSubShape );
473       if ( algo && !algo->NeedDiscreteBoundary() ) {
474         if ( algo->SupportSubmeshes() ) {
475           smWithAlgoSupportingSubmeshes.push_front( smToCompute );
476         }
477         else {
478           smToCompute->Evaluate(aResMap);
479           if ( aShapesId )
480             aShapesId->insert( smToCompute->GetId() );
481         }
482       }
483     }
484
485     // ------------------------------------------------------------
486     // sort list of meshes according to mesh order
487     // ------------------------------------------------------------
488     aMesh.SortByMeshOrder( smWithAlgoSupportingSubmeshes );
489
490     // ------------------------------------------------------------
491     // compute submeshes under shapes with algos that DO NOT require
492     // Discreteized boundaries and DO support submeshes
493     // ------------------------------------------------------------
494     list< SMESH_subMesh* >::iterator subIt, subEnd;
495     subIt  = smWithAlgoSupportingSubmeshes.begin();
496     subEnd = smWithAlgoSupportingSubmeshes.end();
497     // start from lower shapes
498     for ( ; subIt != subEnd; ++subIt ) {
499       sm = *subIt;
500
501       // get a shape the algo is assigned to
502       TopoDS_Shape algoShape;
503       if ( !GetAlgo( aMesh, sm->GetSubShape(), & algoShape ))
504         continue; // strange...
505
506       // look for more local algos
507       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
508       while ( smIt->more() ) {
509         SMESH_subMesh* smToCompute = smIt->next();
510
511         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
512         const int aShapeDim = GetShapeDim( aSubShape );
513         if ( aShapeDim < 1 ) continue;
514
515         //const TopAbs_ShapeEnum aShType = smToCompute->GetSubShape().ShapeType();
516
517         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
518         filter
519           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
520           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
521
522         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( aSubShape, filter, true )) {
523           SMESH_Hypothesis::Hypothesis_Status status;
524           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
525             // mesh a lower smToCompute starting from vertices
526             Evaluate( aMesh, aSubShape, aResMap, /*anUpward=*/true, aShapesId );
527         }
528       }
529     }
530     // ----------------------------------------------------------
531     // apply the algos that do not require Discreteized boundaries
532     // ----------------------------------------------------------
533     for ( subIt = smWithAlgoSupportingSubmeshes.begin(); subIt != subEnd; ++subIt )
534     {
535       sm = *subIt;
536       sm->Evaluate(aResMap);
537       if ( aShapesId )
538         aShapesId->insert( sm->GetId() );
539     }
540
541     // -----------------------------------------------
542     // mesh the rest sub-shapes starting from vertices
543     // -----------------------------------------------
544     ret = Evaluate( aMesh, aShape, aResMap, /*anUpward=*/true, aShapesId );
545   }
546
547   MESSAGE( "VSR - SMESH_Gen::Evaluate() finished, OK = " << ret);
548   return ret;
549 }
550
551
552 //=======================================================================
553 //function : checkConformIgnoredAlgos
554 //purpose  :
555 //=======================================================================
556
557 static bool checkConformIgnoredAlgos(SMESH_Mesh&               aMesh,
558                                      SMESH_subMesh*            aSubMesh,
559                                      const SMESH_Algo*         aGlobIgnoAlgo,
560                                      const SMESH_Algo*         aLocIgnoAlgo,
561                                      bool &                    checkConform,
562                                      set<SMESH_subMesh*>&      aCheckedMap,
563                                      list< SMESH_Gen::TAlgoStateError > & theErrors)
564 {
565   ASSERT( aSubMesh );
566   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
567     return true;
568
569
570   bool ret = true;
571
572   const list<const SMESHDS_Hypothesis*>& listHyp =
573     aMesh.GetMeshDS()->GetHypothesis( aSubMesh->GetSubShape() );
574   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
575   for ( ; it != listHyp.end(); it++)
576   {
577     const SMESHDS_Hypothesis * aHyp = *it;
578     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
579       continue;
580
581     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
582     ASSERT ( algo );
583
584     if ( aLocIgnoAlgo ) // algo is hidden by a local algo of upper dim
585     {
586       INFOS( "Local <" << algo->GetName() << "> is hidden by local <"
587             << aLocIgnoAlgo->GetName() << ">");
588     }
589     else
590     {
591       bool isGlobal = (aMesh.IsMainShape( aSubMesh->GetSubShape() ));
592       int dim = algo->GetDim();
593       int aMaxGlobIgnoDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->GetDim() : -1 );
594
595       if ( dim < aMaxGlobIgnoDim )
596       {
597         // algo is hidden by a global algo
598         INFOS( ( isGlobal ? "Global" : "Local" )
599               << " <" << algo->GetName() << "> is hidden by global <"
600               << aGlobIgnoAlgo->GetName() << ">");
601       }
602       else if ( !algo->NeedDiscreteBoundary() && !isGlobal)
603       {
604         // local algo is not hidden and hides algos on sub-shapes
605         if (checkConform && !aSubMesh->IsConform( algo ))
606         {
607           ret = false;
608           checkConform = false; // no more check conformity
609           INFOS( "ERROR: Local <" << algo->GetName() <<
610                 "> would produce not conform mesh: "
611                 "<Not Conform Mesh Allowed> hypotesis is missing");
612           theErrors.push_back( SMESH_Gen::TAlgoStateError() );
613           theErrors.back().Set( SMESH_Hypothesis::HYP_NOTCONFORM, algo, false );
614         }
615
616         // sub-algos will be hidden by a local <algo>
617         SMESH_subMeshIteratorPtr revItSub =
618           aSubMesh->getDependsOnIterator( /*includeSelf=*/false, /*complexShapeFirst=*/true);
619         bool checkConform2 = false;
620         while ( revItSub->more() )
621         {
622           SMESH_subMesh* sm = revItSub->next();
623           checkConformIgnoredAlgos (aMesh, sm, aGlobIgnoAlgo,
624                                     algo, checkConform2, aCheckedMap, theErrors);
625           aCheckedMap.insert( sm );
626         }
627       }
628     }
629   }
630
631   return ret;
632 }
633
634 //=======================================================================
635 //function : checkMissing
636 //purpose  : notify on missing hypothesis
637 //           Return false if algo or hipothesis is missing
638 //=======================================================================
639
640 static bool checkMissing(SMESH_Gen*                aGen,
641                          SMESH_Mesh&               aMesh,
642                          SMESH_subMesh*            aSubMesh,
643                          const int                 aTopAlgoDim,
644                          bool*                     globalChecked,
645                          const bool                checkNoAlgo,
646                          set<SMESH_subMesh*>&      aCheckedMap,
647                          list< SMESH_Gen::TAlgoStateError > & theErrors)
648 {
649   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
650     return true;
651
652   //MESSAGE("=====checkMissing");
653
654   int ret = true;
655   SMESH_Algo* algo = 0;
656
657   switch (aSubMesh->GetAlgoState())
658   {
659   case SMESH_subMesh::NO_ALGO: {
660     if (checkNoAlgo)
661     {
662       // should there be any algo?
663       int shapeDim = SMESH_Gen::GetShapeDim( aSubMesh->GetSubShape() );
664       if (aTopAlgoDim > shapeDim)
665       {
666         MESSAGE( "ERROR: " << shapeDim << "D algorithm is missing" );
667         ret = false;
668         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
669         theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, shapeDim, true );
670       }
671     }
672     return ret;
673   }
674   case SMESH_subMesh::MISSING_HYP: {
675     // notify if an algo missing hyp is attached to aSubMesh
676     algo = aGen->GetAlgo( aMesh, aSubMesh->GetSubShape() );
677     ASSERT( algo );
678     bool IsGlobalHypothesis = aGen->IsGlobalHypothesis( algo, aMesh );
679     if (!IsGlobalHypothesis || !globalChecked[ algo->GetDim() ])
680     {
681       TAlgoStateErrorName errName = SMESH_Hypothesis::HYP_MISSING;
682       SMESH_Hypothesis::Hypothesis_Status status;
683       algo->CheckHypothesis( aMesh, aSubMesh->GetSubShape(), status );
684       if ( status == SMESH_Hypothesis::HYP_BAD_PARAMETER ) {
685         MESSAGE( "ERROR: hypothesis of " << (IsGlobalHypothesis ? "Global " : "Local ")
686                  << "<" << algo->GetName() << "> has a bad parameter value");
687         errName = status;
688       } else if ( status == SMESH_Hypothesis::HYP_BAD_GEOMETRY ) {
689         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
690                  << "<" << algo->GetName() << "> assigned to mismatching geometry");
691         errName = status;
692       } else {
693         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
694                  << "<" << algo->GetName() << "> misses some hypothesis");
695       }
696       if (IsGlobalHypothesis)
697         globalChecked[ algo->GetDim() ] = true;
698       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
699       theErrors.back().Set( errName, algo, IsGlobalHypothesis );
700     }
701     ret = false;
702     break;
703   }
704   case SMESH_subMesh::HYP_OK:
705     algo = aGen->GetAlgo( aMesh, aSubMesh->GetSubShape() );
706     ret = true;
707     break;
708   default: ASSERT(0);
709   }
710
711   // do not check under algo that hides sub-algos or
712   // re-start checking NO_ALGO state
713   ASSERT (algo);
714   bool isTopLocalAlgo =
715     ( aTopAlgoDim <= algo->GetDim() && !aGen->IsGlobalHypothesis( algo, aMesh ));
716   if (!algo->NeedDiscreteBoundary() || isTopLocalAlgo)
717   {
718     bool checkNoAlgo2 = ( algo->NeedDiscreteBoundary() );
719     SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
720                                                                      /*complexShapeFirst=*/false);
721     while ( itsub->more() )
722     {
723       // sub-meshes should not be checked further more
724       SMESH_subMesh* sm = itsub->next();
725       aCheckedMap.insert( sm );
726
727       if (isTopLocalAlgo)
728       {
729         //check algo on sub-meshes
730         int aTopAlgoDim2 = algo->GetDim();
731         if (!checkMissing (aGen, aMesh, sm, aTopAlgoDim2,
732                            globalChecked, checkNoAlgo2, aCheckedMap, theErrors))
733         {
734           ret = false;
735           if (sm->GetAlgoState() == SMESH_subMesh::NO_ALGO )
736             checkNoAlgo2 = false;
737         }
738       }
739     }
740   }
741   return ret;
742 }
743
744 //=======================================================================
745 //function : CheckAlgoState
746 //purpose  : notify on bad state of attached algos, return false
747 //           if Compute() would fail because of some algo bad state
748 //=======================================================================
749
750 bool SMESH_Gen::CheckAlgoState(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
751 {
752   list< TAlgoStateError > errors;
753   return GetAlgoState( aMesh, aShape, errors );
754 }
755
756 //=======================================================================
757 //function : GetAlgoState
758 //purpose  : notify on bad state of attached algos, return false
759 //           if Compute() would fail because of some algo bad state
760 //           theErrors list contains problems description
761 //=======================================================================
762
763 bool SMESH_Gen::GetAlgoState(SMESH_Mesh&               theMesh,
764                              const TopoDS_Shape&       theShape,
765                              list< TAlgoStateError > & theErrors)
766 {
767   //MESSAGE("SMESH_Gen::CheckAlgoState");
768
769   bool ret = true;
770   bool hasAlgo = false;
771
772   SMESH_subMesh* sm = theMesh.GetSubMesh(theShape);
773   const SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
774   TopoDS_Shape mainShape = meshDS->ShapeToMesh();
775
776   // -----------------
777   // get global algos
778   // -----------------
779
780   const SMESH_Algo* aGlobAlgoArr[] = {0,0,0,0};
781
782   const list<const SMESHDS_Hypothesis*>& listHyp = meshDS->GetHypothesis( mainShape );
783   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
784   for ( ; it != listHyp.end(); it++)
785   {
786     const SMESHDS_Hypothesis * aHyp = *it;
787     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
788       continue;
789
790     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
791     ASSERT ( algo );
792
793     int dim = algo->GetDim();
794     aGlobAlgoArr[ dim ] = algo;
795
796     hasAlgo = true;
797   }
798
799   // --------------------------------------------------------
800   // info on algos that will be ignored because of ones that
801   // don't NeedDiscreteBoundary() attached to super-shapes,
802   // check that a conform mesh will be produced
803   // --------------------------------------------------------
804
805
806   // find a global algo possibly hiding sub-algos
807   int dim;
808   const SMESH_Algo* aGlobIgnoAlgo = 0;
809   for (dim = 3; dim > 0; dim--)
810   {
811     if (aGlobAlgoArr[ dim ] &&
812         !aGlobAlgoArr[ dim ]->NeedDiscreteBoundary())
813     {
814       aGlobIgnoAlgo = aGlobAlgoArr[ dim ];
815       break;
816     }
817   }
818
819   set<SMESH_subMesh*> aCheckedSubs;
820   bool checkConform = ( !theMesh.IsNotConformAllowed() );
821
822   // loop on theShape and its sub-shapes
823   SMESH_subMeshIteratorPtr revItSub = sm->getDependsOnIterator( /*includeSelf=*/true,
824                                                                 /*complexShapeFirst=*/true);
825   while ( revItSub->more() )
826   {
827     SMESH_subMesh* smToCheck = revItSub->next();
828     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
829       break;
830
831     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
832       if (!checkConformIgnoredAlgos (theMesh, smToCheck, aGlobIgnoAlgo,
833                                      0, checkConform, aCheckedSubs, theErrors))
834         ret = false;
835
836     if ( smToCheck->GetAlgoState() != SMESH_subMesh::NO_ALGO )
837       hasAlgo = true;
838   }
839
840   // ----------------------------------------------------------------
841   // info on missing hypothesis and find out if all needed algos are
842   // well defined
843   // ----------------------------------------------------------------
844
845   //MESSAGE( "---info on missing hypothesis and find out if all needed algos are");
846
847   // find max dim of global algo
848   int aTopAlgoDim = 0;
849   for (dim = 3; dim > 0; dim--)
850   {
851     if (aGlobAlgoArr[ dim ])
852     {
853       aTopAlgoDim = dim;
854       break;
855     }
856   }
857   bool checkNoAlgo = theMesh.HasShapeToMesh() ? bool( aTopAlgoDim ) : false;
858   bool globalChecked[] = { false, false, false, false };
859
860   // loop on theShape and its sub-shapes
861   aCheckedSubs.clear();
862   revItSub = sm->getDependsOnIterator( /*includeSelf=*/true, /*complexShapeFirst=*/true);
863   while ( revItSub->more() )
864   {
865     SMESH_subMesh* smToCheck = revItSub->next();
866     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
867       break;
868
869     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
870       if (!checkMissing (this, theMesh, smToCheck, aTopAlgoDim,
871                          globalChecked, checkNoAlgo, aCheckedSubs, theErrors))
872       {
873         ret = false;
874         if (smToCheck->GetAlgoState() == SMESH_subMesh::NO_ALGO )
875           checkNoAlgo = false;
876       }
877   }
878
879   if ( !hasAlgo ) {
880     ret = false;
881     INFOS( "None algorithm attached" );
882     theErrors.push_back( TAlgoStateError() );
883     theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, 1, true );
884   }
885
886   return ret;
887 }
888
889 //=======================================================================
890 //function : IsGlobalHypothesis
891 //purpose  : check if theAlgo is attached to the main shape
892 //=======================================================================
893
894 bool SMESH_Gen::IsGlobalHypothesis(const SMESH_Hypothesis* theHyp, SMESH_Mesh& aMesh)
895 {
896   SMESH_HypoFilter filter( SMESH_HypoFilter::Is( theHyp ));
897   return aMesh.GetHypothesis( aMesh.GetMeshDS()->ShapeToMesh(), filter, false );
898 }
899
900 //================================================================================
901 /*!
902  * \brief Return paths to xml files of plugins
903  */
904 //================================================================================
905
906 std::vector< std::string > SMESH_Gen::GetPluginXMLPaths()
907 {
908   // Get paths to xml files of plugins
909   vector< string > xmlPaths;
910   string sep;
911   if ( const char* meshersList = getenv("SMESH_MeshersList") )
912   {
913     string meshers = meshersList, plugin;
914     string::size_type from = 0, pos;
915     while ( from < meshers.size() )
916     {
917       // cut off plugin name
918       pos = meshers.find( ':', from );
919       if ( pos != string::npos )
920         plugin = meshers.substr( from, pos-from );
921       else
922         plugin = meshers.substr( from ), pos = meshers.size();
923       from = pos + 1;
924
925       // get PLUGIN_ROOT_DIR path
926       string rootDirVar, pluginSubDir = plugin;
927       if ( plugin == "StdMeshers" )
928         rootDirVar = "SMESH", pluginSubDir = "smesh";
929       else
930         for ( pos = 0; pos < plugin.size(); ++pos )
931           rootDirVar += toupper( plugin[pos] );
932       rootDirVar += "_ROOT_DIR";
933
934       const char* rootDir = getenv( rootDirVar.c_str() );
935       if ( !rootDir || strlen(rootDir) == 0 )
936       {
937         rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
938         rootDir = getenv( rootDirVar.c_str() );
939         if ( !rootDir || strlen(rootDir) == 0 ) continue;
940       }
941
942       // get a separator from rootDir
943       for ( pos = strlen( rootDir )-1; pos >= 0 && sep.empty(); --pos )
944         if ( rootDir[pos] == '/' || rootDir[pos] == '\\' )
945         {
946           sep = rootDir[pos];
947           break;
948         }
949 #ifdef WNT
950       if (sep.empty() ) sep = "\\";
951 #else
952       if (sep.empty() ) sep = "/";
953 #endif
954
955       // get a path to resource file
956       string xmlPath = rootDir;
957       if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
958         xmlPath += sep;
959       xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
960       for ( pos = 0; pos < pluginSubDir.size(); ++pos )
961         xmlPath += tolower( pluginSubDir[pos] );
962       xmlPath += sep + plugin + ".xml";
963       bool fileOK;
964 #ifdef WNT
965       fileOK = (GetFileAttributes(xmlPath.c_str()) != INVALID_FILE_ATTRIBUTES);
966 #else
967       fileOK = (access(xmlPath.c_str(), F_OK) == 0);
968 #endif
969       if ( fileOK )
970         xmlPaths.push_back( xmlPath );
971     }
972   }
973
974   return xmlPaths;
975 }
976
977 //=======================================================================
978 namespace // Access to type of input and output of an algorithm
979 //=======================================================================
980 {
981   struct AlgoData
982   {
983     int                       _dim;
984     set<SMDSAbs_GeometryType> _inElemTypes; // acceptable types of input mesh element
985     set<SMDSAbs_GeometryType> _outElemTypes; // produced types of mesh elements
986
987     bool IsCompatible( const AlgoData& algo2 ) const
988     {
989       if ( _dim > algo2._dim ) return algo2.IsCompatible( *this );
990       // algo2 is of highter dimension
991       if ( _outElemTypes.empty() || algo2._inElemTypes.empty() )
992         return false;
993       bool compatible = true;
994       set<SMDSAbs_GeometryType>::const_iterator myOutType = _outElemTypes.begin();
995       for ( ; myOutType != _outElemTypes.end() && compatible; ++myOutType )
996         compatible = algo2._inElemTypes.count( *myOutType );
997       return compatible;
998     }
999   };
1000
1001   //================================================================================
1002   /*!
1003    * \brief Return AlgoData of the algorithm
1004    */
1005   //================================================================================
1006
1007   const AlgoData& getAlgoData( const SMESH_Algo* algo )
1008   {
1009     static map< string, AlgoData > theDataByName;
1010     if ( theDataByName.empty() )
1011     {
1012       // Read Plugin.xml files
1013       vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
1014       LDOMParser xmlParser;
1015       for ( size_t i = 0; i < xmlPaths.size(); ++i )
1016       {
1017         bool error = xmlParser.parse( xmlPaths[i].c_str() );
1018         if ( error )
1019         {
1020           TCollection_AsciiString data;
1021           INFOS( xmlParser.GetError(data) );
1022           continue;
1023         }
1024         // <algorithm type="Regular_1D"
1025         //            ...
1026         //            input="EDGE"
1027         //            output="QUAD,TRIA">
1028         //
1029         LDOM_Document xmlDoc = xmlParser.getDocument();
1030         LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
1031         for ( int i = 0; i < algoNodeList.getLength(); ++i )
1032         {
1033           LDOM_Node     algoNode           = algoNodeList.item( i );
1034           LDOM_Element& algoElem           = (LDOM_Element&) algoNode;
1035           TCollection_AsciiString algoType = algoElem.getAttribute("type");
1036           TCollection_AsciiString input    = algoElem.getAttribute("input");
1037           TCollection_AsciiString output   = algoElem.getAttribute("output");
1038           TCollection_AsciiString dim      = algoElem.getAttribute("dim");
1039           AlgoData & data                  = theDataByName[ algoType.ToCString() ];
1040           data._dim = dim.IntegerValue();
1041           for ( int isInput = 0; isInput < 2; ++isInput )
1042           {
1043             TCollection_AsciiString&   typeStr = isInput ? input : output;
1044             set<SMDSAbs_GeometryType>& typeSet = isInput ? data._inElemTypes : data._outElemTypes;
1045             int beg = 1, end;
1046             while ( beg <= typeStr.Length() )
1047             {
1048               while ( beg < typeStr.Length() && !isalpha( typeStr.Value( beg ) ))
1049                 ++beg;
1050               end = beg;
1051               while ( end < typeStr.Length() && isalpha( typeStr.Value( end + 1 ) ))
1052                 ++end;
1053               if ( end > beg )
1054               {
1055                 TCollection_AsciiString typeName = typeStr.SubString( beg, end );
1056                 if      ( typeName == "EDGE" ) typeSet.insert( SMDSGeom_EDGE );
1057                 else if ( typeName == "TRIA" ) typeSet.insert( SMDSGeom_TRIANGLE );
1058                 else if ( typeName == "QUAD" ) typeSet.insert( SMDSGeom_QUADRANGLE );
1059               }
1060               beg = end + 1;
1061             }
1062           }
1063         }
1064       }
1065     }
1066     return theDataByName[ algo->GetName() ];
1067   }
1068 }
1069
1070 //=============================================================================
1071 /*!
1072  * Finds algo to mesh a shape. Optionally returns a shape the found algo is bound to
1073  */
1074 //=============================================================================
1075
1076 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_Mesh &         aMesh,
1077                                const TopoDS_Shape & aShape,
1078                                TopoDS_Shape*        assignedTo)
1079 {
1080   SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
1081   filter.And( filter.IsApplicableTo( aShape ));
1082
1083   TopoDS_Shape assignedToShape;
1084   SMESH_Algo* algo =
1085     (SMESH_Algo*) aMesh.GetHypothesis( aShape, filter, true, &assignedToShape );
1086
1087   if ( algo &&
1088        aShape.ShapeType() == TopAbs_FACE &&
1089        !aShape.IsSame( assignedToShape ) &&
1090        SMESH_MesherHelper::NbAncestors( aShape, aMesh, TopAbs_SOLID ) > 1 )
1091   {
1092     // Issue 0021559. If there is another 2D algo with different types of output
1093     // elements that can be used to mesh aShape, and 3D algos on adjacent SOLIDs
1094     // have different types of input elements, we choose a most appropriate 2D algo.
1095
1096     // try to find a concurrent 2D algo
1097     filter.AndNot( filter.Is( algo ));
1098     TopoDS_Shape assignedToShape2;
1099     SMESH_Algo* algo2 =
1100       (SMESH_Algo*) aMesh.GetHypothesis( aShape, filter, true, &assignedToShape2 );
1101     if ( algo2 &&
1102          assignedToShape2.ShapeType() == assignedToShape.ShapeType() &&
1103          aMesh.IsOrderOK( aMesh.GetSubMesh( assignedToShape2 ),
1104                           aMesh.GetSubMesh( assignedToShape  )))
1105     {
1106       // get algos on the adjacent SOLIDs
1107       filter.Init( filter.IsAlgo() ).And( filter.HasDim( 3 ));
1108       vector< SMESH_Algo* > algos3D;
1109       PShapeIteratorPtr solidIt = SMESH_MesherHelper::GetAncestors( aShape, aMesh,
1110                                                                     TopAbs_SOLID );
1111       while ( const TopoDS_Shape* solid = solidIt->next() )
1112         if ( SMESH_Algo* algo3D = (SMESH_Algo*) aMesh.GetHypothesis( *solid, filter, true ))
1113         {
1114           algos3D.push_back( algo3D );
1115           filter.AndNot( filter.Is( algo3D ));
1116         }
1117       // check compatibility of algos
1118       if ( algos3D.size() > 1 )
1119       {
1120         const AlgoData& algoData    = getAlgoData( algo );
1121         const AlgoData& algoData2   = getAlgoData( algo2 );
1122         const AlgoData& algoData3d0 = getAlgoData( algos3D[0] );
1123         const AlgoData& algoData3d1 = getAlgoData( algos3D[1] );
1124         if (( algoData2.IsCompatible( algoData3d0 ) &&
1125               algoData2.IsCompatible( algoData3d1 ))
1126             &&
1127             !(algoData.IsCompatible( algoData3d0 ) &&
1128               algoData.IsCompatible( algoData3d1 )))
1129           algo = algo2;
1130       }
1131     }
1132   }
1133
1134   if ( assignedTo && algo )
1135     * assignedTo = assignedToShape;
1136
1137   return algo;
1138 }
1139
1140 //=============================================================================
1141 /*!
1142  * Returns StudyContextStruct for a study
1143  */
1144 //=============================================================================
1145
1146 StudyContextStruct *SMESH_Gen::GetStudyContext(int studyId)
1147 {
1148   // Get studyContext, create it if it does'nt exist, with a SMESHDS_Document
1149
1150   if (_mapStudyContext.find(studyId) == _mapStudyContext.end())
1151   {
1152     _mapStudyContext[studyId] = new StudyContextStruct;
1153     _mapStudyContext[studyId]->myDocument = new SMESHDS_Document(studyId);
1154   }
1155   StudyContextStruct *myStudyContext = _mapStudyContext[studyId];
1156   return myStudyContext;
1157 }
1158
1159 //================================================================================
1160 /*!
1161  * \brief Return shape dimension by TopAbs_ShapeEnum
1162  */
1163 //================================================================================
1164
1165 int SMESH_Gen::GetShapeDim(const TopAbs_ShapeEnum & aShapeType)
1166 {
1167   static vector<int> dim;
1168   if ( dim.empty() )
1169   {
1170     dim.resize( TopAbs_SHAPE, -1 );
1171     dim[ TopAbs_COMPOUND ]  = MeshDim_3D;
1172     dim[ TopAbs_COMPSOLID ] = MeshDim_3D;
1173     dim[ TopAbs_SOLID ]     = MeshDim_3D;
1174     dim[ TopAbs_SHELL ]     = MeshDim_2D;
1175     dim[ TopAbs_FACE  ]     = MeshDim_2D;
1176     dim[ TopAbs_WIRE ]      = MeshDim_1D;
1177     dim[ TopAbs_EDGE ]      = MeshDim_1D;
1178     dim[ TopAbs_VERTEX ]    = MeshDim_0D;
1179   }
1180   return dim[ aShapeType ];
1181 }
1182
1183 //=============================================================================
1184 /*!
1185  * Genarate a new id unique withing this Gen
1186  */
1187 //=============================================================================
1188
1189 int SMESH_Gen::GetANewId()
1190 {
1191   return _hypId++;
1192 }