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