Salome HOME
Adding comments
[modules/smesh.git] / src / SMESH / SMESH_Gen.cxx
1 // Copyright (C) 2007-2022  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 "SMESH_DriverMesh.hxx"
34 #include "SMDS_Mesh.hxx"
35 #include "SMDS_MeshElement.hxx"
36 #include "SMDS_MeshNode.hxx"
37 #include "SMESHDS_Document.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_subMesh.hxx"
42
43 #include <utilities.h>
44 #include <Utils_ExceptHandlers.hxx>
45
46 #include <TopExp_Explorer.hxx>
47 #include <TopoDS.hxx>
48 #include <TopoDS_Iterator.hxx>
49
50 #include "memoire.h"
51 #include <functional>
52
53 #ifdef WIN32
54   #include <windows.h>
55 #endif
56
57 #include <Basics_Utils.hxx>
58
59 using namespace std;
60 #include <boost/filesystem.hpp>
61 #include <boost/asio.hpp>
62 namespace fs = boost::filesystem;
63
64 // Environment variable separator
65 #ifdef WIN32
66   #define env_sep ';'
67 #else
68   #define env_sep ':'
69 #endif
70
71 namespace
72 {
73   // a structure used to nullify SMESH_Gen field of SMESH_Hypothesis,
74   // which is needed for SMESH_Hypothesis not deleted before ~SMESH_Gen()
75   struct _Hyp : public SMESH_Hypothesis
76   {
77     void NullifyGen()
78     {
79       _gen = 0;
80     }
81   };
82
83   //================================================================================
84   /*!
85    * \brief Fill a map of shapes with all sub-shape of a sub-mesh
86    */
87   //================================================================================
88
89   TopTools_IndexedMapOfShape * fillAllowed( SMESH_subMesh*               sm,
90                                             const bool                   toFill,
91                                             TopTools_IndexedMapOfShape * allowedSub )
92   {
93     if ( !toFill || !allowedSub )
94     {
95       return nullptr;
96     }
97     if ( allowedSub->IsEmpty() )
98     {
99       allowedSub->ReSize( sm->DependsOn().size() + 1 );
100       allowedSub->Add( sm->GetSubShape() );
101       for ( const auto & key_sm : sm->DependsOn() )
102         allowedSub->Add( key_sm.second->GetSubShape() );
103     }
104     return allowedSub;
105   }
106 }
107
108 //=============================================================================
109 /*!
110  *  Constructor
111  */
112 //=============================================================================
113
114 SMESH_Gen::SMESH_Gen()
115 {
116   _studyContext = new StudyContextStruct;
117   _studyContext->myDocument = new SMESHDS_Document();
118   _localId = 0;
119   _hypId   = 0;
120   _segmentation = _nbSegments = 10;
121   _compute_canceled = false;
122 }
123
124 //=============================================================================
125 /*!
126  * Destructor
127  */
128 //=============================================================================
129
130 SMESH_Gen::~SMESH_Gen()
131 {
132   std::map < int, SMESH_Hypothesis * >::iterator i_hyp = _studyContext->mapHypothesis.begin();
133   for ( ; i_hyp != _studyContext->mapHypothesis.end(); ++i_hyp )
134   {
135     if ( _Hyp* h = static_cast< _Hyp*>( i_hyp->second ))
136       h->NullifyGen();
137   }
138   delete _studyContext->myDocument;
139   delete _studyContext;
140 }
141
142 //=============================================================================
143 /*!
144  * Creates a mesh in a study.
145  * if (theIsEmbeddedMode) { mesh modification commands are not logged }
146  */
147 //=============================================================================
148
149 SMESH_Mesh* SMESH_Gen::CreateMesh(bool theIsEmbeddedMode)
150 {
151   Unexpect aCatch(SalomeException);
152
153   // create a new SMESH_mesh object
154   SMESH_Mesh *aMesh = new SMESH_Mesh(_localId++,
155                                      this,
156                                      theIsEmbeddedMode,
157                                      _studyContext->myDocument);
158   _studyContext->mapMesh[_localId-1] = aMesh;
159
160   return aMesh;
161 }
162
163
164 //=============================================================================
165 /*!
166  * Algo to run the computation of all the submeshes of a mesh in sequentila
167  */
168 //=============================================================================
169
170 bool SMESH_Gen::sequentialComputeSubMeshes(
171           SMESH_Mesh & aMesh,
172           const TopoDS_Shape & aShape,
173           const ::MeshDimension       aDim,
174           TSetOfInt*                  aShapesId /*=0*/,
175           TopTools_IndexedMapOfShape* allowedSubShapes,
176           SMESH_subMesh::compute_event &computeEvent,
177           const bool includeSelf,
178           const bool complexShapeFirst,
179           const bool   aShapeOnly)
180 {
181   MESSAGE("Compute submeshes sequentialy");
182
183   bool ret = true;
184
185   SMESH_subMeshIteratorPtr smIt;
186   SMESH_subMesh *shapeSM = aMesh.GetSubMesh(aShape);
187
188   smIt = shapeSM->getDependsOnIterator(includeSelf, !complexShapeFirst);
189   while ( smIt->more() )
190   {
191     SMESH_subMesh* smToCompute = smIt->next();
192
193     // do not mesh vertices of a pseudo shape
194     const TopoDS_Shape&        shape = smToCompute->GetSubShape();
195     const TopAbs_ShapeEnum shapeType = shape.ShapeType();
196     if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
197       continue;
198
199     // check for preview dimension limitations
200     if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
201     {
202       // clear compute state not to show previous compute errors
203       //  if preview invoked less dimension less than previous
204       smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
205       continue;
206     }
207
208     if (smToCompute->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
209     {
210       if (_compute_canceled)
211         return false;
212       smToCompute->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
213       setCurrentSubMesh( smToCompute );
214       smToCompute->ComputeStateEngine( computeEvent );
215       setCurrentSubMesh( nullptr );
216       smToCompute->SetAllowedSubShapes( nullptr );
217     }
218
219     // we check all the sub-meshes here and detect if any of them failed to compute
220     if (smToCompute->GetComputeState() == SMESH_subMesh::FAILED_TO_COMPUTE &&
221         ( shapeType != TopAbs_EDGE || !SMESH_Algo::isDegenerated( TopoDS::Edge( shape ))))
222       ret = false;
223     else if ( aShapesId )
224       aShapesId->insert( smToCompute->GetId() );
225   }
226   //aMesh.GetMeshDS()->Modified();
227   return ret;
228
229 };
230
231 //=============================================================================
232 /*
233  * compute of a submesh
234  * This function is passed to the thread pool
235  */
236 //=============================================================================
237 const std::function<void(SMESH_subMesh*,
238                          SMESH_subMesh::compute_event,
239                          SMESH_subMesh*,
240                          bool,
241                          TopTools_IndexedMapOfShape *,
242                          TSetOfInt*)>
243      compute_function([&] (SMESH_subMesh* sm,
244                           SMESH_subMesh::compute_event event,
245                           SMESH_subMesh *shapeSM,
246                           bool aShapeOnly,
247                           TopTools_IndexedMapOfShape *allowedSubShapes,
248                           TSetOfInt*                  aShapesId) -> void
249 {
250   if (sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE)
251   {
252     sm->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
253     //setCurrentSubMesh( sm );
254     sm->ComputeStateEngine(event);
255     //setCurrentSubMesh( nullptr );
256     sm->SetAllowedSubShapes( nullptr );
257   }
258
259   if ( aShapesId )
260     aShapesId->insert( sm->GetId() );
261
262 });
263
264 //=============================================================================
265 /*!
266  * Algo to run the computation of all the submeshes of a mesh in parallel
267  */
268 //=============================================================================
269
270 bool SMESH_Gen::parallelComputeSubMeshes(
271           SMESH_Mesh & aMesh,
272           const TopoDS_Shape & aShape,
273           const ::MeshDimension       aDim,
274           TSetOfInt*                  aShapesId /*=0*/,
275           TopTools_IndexedMapOfShape* allowedSubShapes,
276           SMESH_subMesh::compute_event &computeEvent,
277           const bool includeSelf,
278           const bool complexShapeFirst,
279           const bool   aShapeOnly)
280 {
281
282   bool ret = true;
283
284   SMESH_subMeshIteratorPtr smIt;
285   SMESH_subMesh *shapeSM = aMesh.GetSubMesh(aShape);
286
287   // Pool of thread for computation
288   // TODO: move when parallelMesh created
289   aMesh.InitPoolThreads();
290
291   TopAbs_ShapeEnum previousShapeType = TopAbs_VERTEX;
292   int nbThreads = aMesh.GetNbThreads();
293   MESSAGE("Compute submeshes with threads: " << nbThreads);
294
295
296   smIt = shapeSM->getDependsOnIterator(includeSelf, !complexShapeFirst);
297   while ( smIt->more() )
298   {
299     SMESH_subMesh* smToCompute = smIt->next();
300
301     // do not mesh vertices of a pseudo shape
302     const TopoDS_Shape&        shape = smToCompute->GetSubShape();
303     const TopAbs_ShapeEnum shapeType = shape.ShapeType();
304     // Not doing in parallel 1D and 2D meshes
305     if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
306       continue;
307     if(shapeType==TopAbs_FACE||shapeType==TopAbs_EDGE)
308       aMesh.SetNbThreads(0);
309     else
310       aMesh.SetNbThreads(nbThreads);
311
312
313     if (shapeType != previousShapeType) {
314       // Waiting for all threads for the previous type to end
315       aMesh.wait();
316
317       std::string file_name;
318       switch(previousShapeType){
319         case TopAbs_FACE:
320           file_name = "Mesh2D.med";
321           break;
322         case TopAbs_EDGE:
323           file_name = "Mesh1D.med";
324           break;
325         case TopAbs_VERTEX:
326           file_name = "Mesh0D.med";
327           break;
328         case TopAbs_SOLID:
329         default:
330           file_name = "";
331           break;
332       }
333       if(file_name != "")
334       {
335         fs::path mesh_file = fs::path(aMesh.tmp_folder) / fs::path(file_name);
336         exportMesh(mesh_file.string(), aMesh, "MESH");
337
338       }
339       //Resetting threaded pool info
340       previousShapeType = shapeType;
341     }
342
343     // check for preview dimension limitations
344     if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
345     {
346       // clear compute state not to show previous compute errors
347       //  if preview invoked less dimension less than previous
348       smToCompute->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
349       continue;
350     }
351     boost::asio::post(*(aMesh._pool), std::bind(compute_function, smToCompute, computeEvent,
352                       shapeSM, aShapeOnly, allowedSubShapes,
353                       aShapesId));
354   }
355
356   // Waiting for the thread for Solids to finish
357   aMesh.wait();
358
359   aMesh.GetMeshDS()->Modified();
360
361   return ret;
362 };
363
364
365 //=============================================================================
366 /*
367  * Compute a mesh
368  */
369 //=============================================================================
370
371 bool SMESH_Gen::Compute(SMESH_Mesh &                aMesh,
372                         const TopoDS_Shape &        aShape,
373                         const int                   aFlags /*= COMPACT_MESH*/,
374                         const ::MeshDimension       aDim /*=::MeshDim_3D*/,
375                         TSetOfInt*                  aShapesId /*=0*/,
376                         TopTools_IndexedMapOfShape* anAllowedSubShapes/*=0*/)
377 {
378   MEMOSTAT;
379
380   const bool   aShapeOnly = aFlags & SHAPE_ONLY;
381   const bool     anUpward = aFlags & UPWARD;
382   const bool aCompactMesh = aFlags & COMPACT_MESH;
383
384   bool ret = true;
385
386   SMESH_subMesh *sm, *shapeSM = aMesh.GetSubMesh(aShape);
387
388   const bool includeSelf = true;
389   const bool complexShapeFirst = true;
390   const int  globalAlgoDim = 100;
391
392   SMESH_subMeshIteratorPtr smIt;
393
394   // Fix of Issue 22150. Due to !BLSURF->OnlyUnaryInput(), BLSURF computes edges
395   // that must be computed by Projection 1D-2D while the Projection asks to compute
396   // one face only.
397   SMESH_subMesh::compute_event computeEvent =
398     aShapeOnly ? SMESH_subMesh::COMPUTE_SUBMESH : SMESH_subMesh::COMPUTE;
399   if ( !aMesh.HasShapeToMesh() )
400     computeEvent = SMESH_subMesh::COMPUTE_NOGEOM; // if several algos and no geometry
401
402   TopTools_IndexedMapOfShape *allowedSubShapes = anAllowedSubShapes, allowedSub;
403   if ( aShapeOnly && !allowedSubShapes )
404     allowedSubShapes = &allowedSub;
405
406   if ( anUpward ) // is called from the below code in this method
407   {
408     // ===============================================
409     // Mesh all the sub-shapes starting from vertices
410     // ===============================================
411     if (aMesh.IsParallel())
412       ret = parallelComputeSubMeshes(
413               aMesh, aShape, aDim,
414               aShapesId, allowedSubShapes,
415               computeEvent,
416               includeSelf,
417               complexShapeFirst,
418               aShapeOnly);
419     else
420       ret = sequentialComputeSubMeshes(
421               aMesh, aShape, aDim,
422               aShapesId, allowedSubShapes,
423               computeEvent,
424               includeSelf,
425               complexShapeFirst,
426               aShapeOnly);
427
428     return ret;
429   }
430   else
431   {
432     // ================================================================
433     // Apply algos that do NOT require discretized boundaries
434     // ("all-dimensional") and do NOT support sub-meshes, starting from
435     // the most complex shapes and collect sub-meshes with algos that
436     // DO support sub-meshes
437     // ================================================================
438     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes[4]; // for each dim
439
440     // map to sort sm with same dim algos according to dim of
441     // the shape the algo assigned to (issue 0021217).
442     // Other issues influenced the algo applying order:
443     // 21406, 21556, 21893, 20206
444     multimap< int, SMESH_subMesh* > shDim2sm;
445     multimap< int, SMESH_subMesh* >::reverse_iterator shDim2smIt;
446     TopoDS_Shape algoShape;
447     int prevShapeDim = -1, aShapeDim;
448
449     smIt = shapeSM->getDependsOnIterator(includeSelf, complexShapeFirst);
450     while ( smIt->more() )
451     {
452       SMESH_subMesh* smToCompute = smIt->next();
453       if ( smToCompute->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE )
454         continue;
455
456       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
457       aShapeDim = GetShapeDim( aSubShape );
458       if ( aShapeDim < 1 ) break;
459
460       // check for preview dimension limitations
461       if ( aShapesId && aShapeDim > (int)aDim )
462         continue;
463
464       SMESH_Algo* algo = GetAlgo( smToCompute, &algoShape );
465       if ( algo && !algo->NeedDiscreteBoundary() )
466       {
467         if ( algo->SupportSubmeshes() )
468         {
469           // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
470           // so that more local algos to go first
471           if ( prevShapeDim != aShapeDim )
472           {
473             prevShapeDim = aShapeDim;
474             for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
475               if ( shDim2smIt->first == globalAlgoDim )
476                 smWithAlgoSupportingSubmeshes[ aShapeDim ].push_back( shDim2smIt->second );
477               else
478                 smWithAlgoSupportingSubmeshes[ aShapeDim ].push_front( shDim2smIt->second );
479             shDim2sm.clear();
480           }
481           // add smToCompute to shDim2sm map
482           if ( algoShape.IsSame( aMesh.GetShapeToMesh() ))
483           {
484             aShapeDim = globalAlgoDim; // to compute last
485           }
486           else
487           {
488             aShapeDim = GetShapeDim( algoShape );
489             if ( algoShape.ShapeType() == TopAbs_COMPOUND )
490             {
491               TopoDS_Iterator it( algoShape );
492               aShapeDim += GetShapeDim( it.Value() );
493             }
494           }
495           shDim2sm.insert( make_pair( aShapeDim, smToCompute ));
496         }
497         else // Compute w/o support of sub-meshes
498         {
499           if (_compute_canceled)
500             return false;
501           smToCompute->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
502           setCurrentSubMesh( smToCompute );
503           smToCompute->ComputeStateEngine( computeEvent );
504           setCurrentSubMesh( nullptr );
505           smToCompute->SetAllowedSubShapes( nullptr );
506           if ( aShapesId )
507             aShapesId->insert( smToCompute->GetId() );
508         }
509       }
510     }
511     // reload sub-meshes from shDim2sm into smWithAlgoSupportingSubmeshes
512     for ( shDim2smIt = shDim2sm.rbegin(); shDim2smIt != shDim2sm.rend(); ++shDim2smIt )
513       if ( shDim2smIt->first == globalAlgoDim )
514         smWithAlgoSupportingSubmeshes[3].push_back( shDim2smIt->second );
515       else
516         smWithAlgoSupportingSubmeshes[0].push_front( shDim2smIt->second );
517
518     // ======================================================
519     // Apply all-dimensional algorithms supporing sub-meshes
520     // ======================================================
521
522     std::vector< SMESH_subMesh* > smVec;
523     for ( aShapeDim = 0; aShapeDim < 4; ++aShapeDim )
524       smVec.insert( smVec.end(),
525                     smWithAlgoSupportingSubmeshes[aShapeDim].begin(),
526                     smWithAlgoSupportingSubmeshes[aShapeDim].end() );
527
528     // gather sub-shapes with local uni-dimensional algos (bos #29143)
529     // ----------------------------------------------------------------
530     TopTools_MapOfShape uniDimAlgoShapes;
531     if ( !smVec.empty() )
532     {
533       ShapeToHypothesis::Iterator s2hyps( aMesh.GetMeshDS()->GetHypotheses() );
534       for ( ; s2hyps.More(); s2hyps.Next() )
535       {
536         const TopoDS_Shape& s = s2hyps.Key();
537         if ( s.IsSame( aMesh.GetShapeToMesh() ))
538           continue;
539         for ( auto & hyp : s2hyps.Value() )
540         {
541           if ( const SMESH_Algo* algo = dynamic_cast< const SMESH_Algo*>( hyp ))
542             if ( algo->NeedDiscreteBoundary() )
543             {
544               TopAbs_ShapeEnum sType;
545               switch ( algo->GetDim() ) {
546               case 3:  sType = TopAbs_SOLID; break;
547               case 2:  sType = TopAbs_FACE; break;
548               default: sType = TopAbs_EDGE; break;
549               }
550               for ( TopExp_Explorer ex( s2hyps.Key(), sType ); ex.More(); ex.Next() )
551                 uniDimAlgoShapes.Add( ex.Current() );
552             }
553         }
554       }
555     }
556
557     {
558       // ------------------------------------------------
559       // sort list of sub-meshes according to mesh order
560       // ------------------------------------------------
561       aMesh.SortByMeshOrder( smVec );
562
563       // ------------------------------------------------------------
564       // compute sub-meshes with local uni-dimensional algos under
565       // sub-meshes with all-dimensional algos
566       // ------------------------------------------------------------
567       // start from lower shapes
568       for ( size_t i = 0; i < smVec.size(); ++i )
569       {
570         sm = smVec[i];
571         if ( sm->GetComputeState() != SMESH_subMesh::READY_TO_COMPUTE)
572           continue;
573
574         const TopAbs_ShapeEnum shapeType = sm->GetSubShape().ShapeType();
575
576         if ( !uniDimAlgoShapes.IsEmpty() )
577         {
578           // get a shape the algo is assigned to
579           if ( !GetAlgo( sm, & algoShape ))
580             continue; // strange...
581
582           // look for more local algos
583           if ( SMESH_subMesh* algoSM = aMesh.GetSubMesh( algoShape ))
584             smIt = algoSM->getDependsOnIterator(!includeSelf, !complexShapeFirst);
585           else
586             smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
587
588           while ( smIt->more() )
589           {
590             SMESH_subMesh* smToCompute = smIt->next();
591
592             const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
593             const           int aShapeDim = GetShapeDim( aSubShape );
594             if ( aShapeDim < 1 || aSubShape.ShapeType() <= shapeType )
595               continue;
596             if ( !uniDimAlgoShapes.Contains( aSubShape ))
597               continue; // [bos #29143] aMesh.GetHypothesis() is too long
598
599             // check for preview dimension limitations
600             if ( aShapesId && GetShapeDim( aSubShape.ShapeType() ) > (int)aDim )
601               continue;
602
603             SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
604             filter
605               .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
606               .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
607
608             if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( smToCompute, filter, true))
609             {
610               if ( ! subAlgo->NeedDiscreteBoundary() ) continue;
611               TopTools_IndexedMapOfShape* localAllowed = allowedSubShapes;
612               if ( localAllowed && localAllowed->IsEmpty() )
613                 localAllowed = 0; // prevent fillAllowed() with  aSubShape
614
615               SMESH_Hypothesis::Hypothesis_Status status;
616               if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
617                 // mesh a lower smToCompute starting from vertices
618                 Compute( aMesh, aSubShape, aFlags | SHAPE_ONLY_UPWARD, aDim, aShapesId, localAllowed );
619             }
620           }
621         }
622         // --------------------------------
623         // apply the all-dimensional algo
624         // --------------------------------
625         {
626           if (_compute_canceled)
627             return false;
628           // check for preview dimension limitations
629           if ( aShapesId && GetShapeDim( shapeType ) > (int)aDim )
630             continue;
631           sm->SetAllowedSubShapes( fillAllowed( shapeSM, aShapeOnly, allowedSubShapes ));
632           setCurrentSubMesh( sm );
633           sm->ComputeStateEngine( computeEvent );
634
635           setCurrentSubMesh( NULL );
636           sm->SetAllowedSubShapes( nullptr );
637           if ( aShapesId )
638             aShapesId->insert( sm->GetId() );
639         }
640       }
641     }
642
643     // -----------------------------------------------
644     // mesh the rest sub-shapes starting from vertices
645     // -----------------------------------------------
646     ret = Compute( aMesh, aShape, aFlags | UPWARD, aDim, aShapesId, allowedSubShapes );
647
648   }
649
650   MEMOSTAT;
651
652   // fix quadratic mesh by bending iternal links near concave boundary
653   if ( aCompactMesh && // a final compute
654        aShape.IsSame( aMesh.GetShapeToMesh() ) &&
655        !aShapesId && // not preview
656        ret ) // everything is OK
657   {
658     SMESH_MesherHelper aHelper( aMesh );
659     if ( aHelper.IsQuadraticMesh() != SMESH_MesherHelper::LINEAR )
660     {
661       aHelper.FixQuadraticElements( shapeSM->GetComputeError() );
662     }
663   }
664
665   if ( aCompactMesh )
666   {
667     aMesh.GetMeshDS()->Modified();
668     aMesh.GetMeshDS()->CompactMesh();
669   }
670   return ret;
671 }
672
673 //=============================================================================
674 /*!
675  * Prepare Compute a mesh
676  */
677 //=============================================================================
678 void SMESH_Gen::PrepareCompute(SMESH_Mesh &          /*aMesh*/,
679                                const TopoDS_Shape &  /*aShape*/)
680 {
681   _compute_canceled = false;
682   resetCurrentSubMesh();
683 }
684
685 //=============================================================================
686 /*!
687  * Cancel Compute a mesh
688  */
689 //=============================================================================
690 void SMESH_Gen::CancelCompute(SMESH_Mesh &          /*aMesh*/,
691                               const TopoDS_Shape &  /*aShape*/)
692 {
693   _compute_canceled = true;
694   if ( const SMESH_subMesh* sm = GetCurrentSubMesh() )
695   {
696     const_cast< SMESH_subMesh* >( sm )->ComputeStateEngine( SMESH_subMesh::COMPUTE_CANCELED );
697   }
698   resetCurrentSubMesh();
699 }
700
701 //================================================================================
702 /*!
703  * \brief Returns a sub-mesh being currently computed
704  */
705 //================================================================================
706
707 const SMESH_subMesh* SMESH_Gen::GetCurrentSubMesh() const
708 {
709   return _sm_current.empty() ? 0 : _sm_current.back();
710 }
711
712 //================================================================================
713 /*!
714  * \brief Sets a sub-mesh being currently computed.
715  *
716  * An algorithm can call Compute() for a sub-shape, hence we keep a stack of sub-meshes
717  */
718 //================================================================================
719
720 void SMESH_Gen::setCurrentSubMesh(SMESH_subMesh* sm)
721 {
722   if ( sm )
723     _sm_current.push_back( sm );
724
725   else if ( !_sm_current.empty() )
726     _sm_current.pop_back();
727 }
728
729 void SMESH_Gen::resetCurrentSubMesh()
730 {
731   _sm_current.clear();
732 }
733
734 //=============================================================================
735 /*!
736  * Evaluate a mesh
737  */
738 //=============================================================================
739
740 bool SMESH_Gen::Evaluate(SMESH_Mesh &          aMesh,
741                          const TopoDS_Shape &  aShape,
742                          MapShapeNbElems&      aResMap,
743                          const bool            anUpward,
744                          TSetOfInt*            aShapesId)
745 {
746   bool ret = true;
747
748   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
749
750   const bool includeSelf = true;
751   const bool complexShapeFirst = true;
752   SMESH_subMeshIteratorPtr smIt;
753
754   if ( anUpward ) { // is called from below code here
755     // -----------------------------------------------
756     // mesh all the sub-shapes starting from vertices
757     // -----------------------------------------------
758     smIt = sm->getDependsOnIterator(includeSelf, !complexShapeFirst);
759     while ( smIt->more() ) {
760       SMESH_subMesh* smToCompute = smIt->next();
761
762       // do not mesh vertices of a pseudo shape
763       const TopAbs_ShapeEnum shapeType = smToCompute->GetSubShape().ShapeType();
764       //if ( !aMesh.HasShapeToMesh() && shapeType == TopAbs_VERTEX )
765       //  continue;
766       if ( !aMesh.HasShapeToMesh() ) {
767         if( shapeType == TopAbs_VERTEX || shapeType == TopAbs_WIRE ||
768             shapeType == TopAbs_SHELL )
769           continue;
770       }
771
772       smToCompute->Evaluate(aResMap);
773       if( aShapesId )
774         aShapesId->insert( smToCompute->GetId() );
775     }
776     return ret;
777   }
778   else {
779     // -----------------------------------------------------------------
780     // apply algos that DO NOT require Discreteized boundaries and DO NOT
781     // support sub-meshes, starting from the most complex shapes
782     // and collect sub-meshes with algos that DO support sub-meshes
783     // -----------------------------------------------------------------
784     list< SMESH_subMesh* > smWithAlgoSupportingSubmeshes;
785     smIt = sm->getDependsOnIterator(includeSelf, complexShapeFirst);
786     while ( smIt->more() ) {
787       SMESH_subMesh* smToCompute = smIt->next();
788       const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
789       const int aShapeDim = GetShapeDim( aSubShape );
790       if ( aShapeDim < 1 ) break;
791
792       SMESH_Algo* algo = GetAlgo( smToCompute );
793       if ( algo && !algo->NeedDiscreteBoundary() ) {
794         if ( algo->SupportSubmeshes() ) {
795           smWithAlgoSupportingSubmeshes.push_front( smToCompute );
796         }
797         else {
798           smToCompute->Evaluate(aResMap);
799           if ( aShapesId )
800             aShapesId->insert( smToCompute->GetId() );
801         }
802       }
803     }
804
805     // ------------------------------------------------------------
806     // sort list of meshes according to mesh order
807     // ------------------------------------------------------------
808     std::vector< SMESH_subMesh* > smVec( smWithAlgoSupportingSubmeshes.begin(),
809                                          smWithAlgoSupportingSubmeshes.end() );
810     aMesh.SortByMeshOrder( smVec );
811
812     // ------------------------------------------------------------
813     // compute sub-meshes under shapes with algos that DO NOT require
814     // Discreteized boundaries and DO support sub-meshes
815     // ------------------------------------------------------------
816     // start from lower shapes
817     for ( size_t i = 0; i < smVec.size(); ++i )
818     {
819       sm = smVec[i];
820
821       // get a shape the algo is assigned to
822       TopoDS_Shape algoShape;
823       if ( !GetAlgo( sm, & algoShape ))
824         continue; // strange...
825
826       // look for more local algos
827       smIt = sm->getDependsOnIterator(!includeSelf, !complexShapeFirst);
828       while ( smIt->more() ) {
829         SMESH_subMesh* smToCompute = smIt->next();
830
831         const TopoDS_Shape& aSubShape = smToCompute->GetSubShape();
832         const int aShapeDim = GetShapeDim( aSubShape );
833         if ( aShapeDim < 1 ) continue;
834
835         SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
836         filter
837           .And( SMESH_HypoFilter::IsApplicableTo( aSubShape ))
838           .And( SMESH_HypoFilter::IsMoreLocalThan( algoShape, aMesh ));
839
840         if ( SMESH_Algo* subAlgo = (SMESH_Algo*) aMesh.GetHypothesis( smToCompute, filter, true ))
841         {
842           if ( ! subAlgo->NeedDiscreteBoundary() ) continue;
843           SMESH_Hypothesis::Hypothesis_Status status;
844           if ( subAlgo->CheckHypothesis( aMesh, aSubShape, status ))
845             // mesh a lower smToCompute starting from vertices
846             Evaluate( aMesh, aSubShape, aResMap, /*anUpward=*/true, aShapesId );
847         }
848       }
849     }
850     // ----------------------------------------------------------
851     // apply the algos that do not require Discreteized boundaries
852     // ----------------------------------------------------------
853     for ( size_t i = 0; i < smVec.size(); ++i )
854     {
855       sm = smVec[i];
856       sm->Evaluate(aResMap);
857       if ( aShapesId )
858         aShapesId->insert( sm->GetId() );
859     }
860
861     // -----------------------------------------------
862     // mesh the rest sub-shapes starting from vertices
863     // -----------------------------------------------
864     ret = Evaluate( aMesh, aShape, aResMap, /*anUpward=*/true, aShapesId );
865   }
866
867   return ret;
868 }
869
870
871 //=======================================================================
872 //function : checkConformIgnoredAlgos
873 //purpose  :
874 //=======================================================================
875
876 static bool checkConformIgnoredAlgos(SMESH_Mesh&               aMesh,
877                                      SMESH_subMesh*            aSubMesh,
878                                      const SMESH_Algo*         aGlobIgnoAlgo,
879                                      const SMESH_Algo*         aLocIgnoAlgo,
880                                      bool &                    checkConform,
881                                      set<SMESH_subMesh*>&      aCheckedMap,
882                                      list< SMESH_Gen::TAlgoStateError > & theErrors)
883 {
884   ASSERT( aSubMesh );
885   if ( aSubMesh->GetSubShape().ShapeType() == TopAbs_VERTEX)
886     return true;
887
888
889   bool ret = true;
890
891   const list<const SMESHDS_Hypothesis*>& listHyp =
892     aMesh.GetMeshDS()->GetHypothesis( aSubMesh->GetSubShape() );
893   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
894   for ( ; it != listHyp.end(); it++)
895   {
896     const SMESHDS_Hypothesis * aHyp = *it;
897     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
898       continue;
899
900     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
901     ASSERT ( algo );
902
903     if ( aLocIgnoAlgo ) // algo is hidden by a local algo of upper dim
904     {
905       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
906       theErrors.back().Set( SMESH_Hypothesis::HYP_HIDDEN_ALGO, algo, false );
907       INFOS( "Local <" << algo->GetName() << "> is hidden by local <"
908             << aLocIgnoAlgo->GetName() << ">");
909     }
910     else
911     {
912       bool       isGlobal = (aMesh.IsMainShape( aSubMesh->GetSubShape() ));
913       int             dim = algo->GetDim();
914       int aMaxGlobIgnoDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->GetDim() : -1 );
915       bool    isNeededDim = ( aGlobIgnoAlgo ? aGlobIgnoAlgo->NeedLowerHyps( dim ) : false );
916
917       if (( dim < aMaxGlobIgnoDim && !isNeededDim ) &&
918           ( isGlobal || !aGlobIgnoAlgo->SupportSubmeshes() ))
919       {
920         // algo is hidden by a global algo
921         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
922         theErrors.back().Set( SMESH_Hypothesis::HYP_HIDDEN_ALGO, algo, true );
923         INFOS( ( isGlobal ? "Global" : "Local" )
924               << " <" << algo->GetName() << "> is hidden by global <"
925               << aGlobIgnoAlgo->GetName() << ">");
926       }
927       else if ( !algo->NeedDiscreteBoundary() && !isGlobal)
928       {
929         // local algo is not hidden and hides algos on sub-shapes
930         if (checkConform && !aSubMesh->IsConform( algo ))
931         {
932           ret = false;
933           checkConform = false; // no more check conformity
934           INFOS( "ERROR: Local <" << algo->GetName() <<
935                 "> would produce not conform mesh: "
936                 "<Not Conform Mesh Allowed> hypothesis is missing");
937           theErrors.push_back( SMESH_Gen::TAlgoStateError() );
938           theErrors.back().Set( SMESH_Hypothesis::HYP_NOTCONFORM, algo, false );
939         }
940
941         // sub-algos will be hidden by a local <algo> if <algo> does not support sub-meshes
942         if ( algo->SupportSubmeshes() )
943           algo = 0;
944         SMESH_subMeshIteratorPtr revItSub =
945           aSubMesh->getDependsOnIterator( /*includeSelf=*/false, /*complexShapeFirst=*/true);
946         bool checkConform2 = false;
947         while ( revItSub->more() )
948         {
949           SMESH_subMesh* sm = revItSub->next();
950           checkConformIgnoredAlgos (aMesh, sm, aGlobIgnoAlgo,
951                                     algo, checkConform2, aCheckedMap, theErrors);
952           aCheckedMap.insert( sm );
953         }
954       }
955     }
956   }
957
958   return ret;
959 }
960
961 //=======================================================================
962 //function : checkMissing
963 //purpose  : notify on missing hypothesis
964 //           Return false if algo or hipothesis is missing
965 //=======================================================================
966
967 static bool checkMissing(SMESH_Gen*                aGen,
968                          SMESH_Mesh&               aMesh,
969                          SMESH_subMesh*            aSubMesh,
970                          const int                 aTopAlgoDim,
971                          bool*                     globalChecked,
972                          const bool                checkNoAlgo,
973                          set<SMESH_subMesh*>&      aCheckedMap,
974                          list< SMESH_Gen::TAlgoStateError > & theErrors)
975 {
976   switch ( aSubMesh->GetSubShape().ShapeType() )
977   {
978   case TopAbs_EDGE:
979   case TopAbs_FACE:
980   case TopAbs_SOLID: break; // check this sub-mesh, it can be meshed
981   default:
982     return true; // not meshable sub-mesh
983   }
984   if ( aCheckedMap.count( aSubMesh ))
985     return true;
986
987   int ret = true;
988   SMESH_Algo* algo = 0;
989
990   switch (aSubMesh->GetAlgoState())
991   {
992   case SMESH_subMesh::NO_ALGO: {
993     if (checkNoAlgo)
994     {
995       // should there be any algo?
996       int shapeDim = SMESH_Gen::GetShapeDim( aSubMesh->GetSubShape() );
997       if (aTopAlgoDim > shapeDim)
998       {
999         MESSAGE( "ERROR: " << shapeDim << "D algorithm is missing" );
1000         ret = false;
1001         theErrors.push_back( SMESH_Gen::TAlgoStateError() );
1002         theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, shapeDim, true );
1003       }
1004     }
1005     return ret;
1006   }
1007   case SMESH_subMesh::MISSING_HYP: {
1008     // notify if an algo missing hyp is attached to aSubMesh
1009     algo = aSubMesh->GetAlgo();
1010     ASSERT( algo );
1011     bool IsGlobalHypothesis = aGen->IsGlobalHypothesis( algo, aMesh );
1012     if (!IsGlobalHypothesis || !globalChecked[ algo->GetDim() ])
1013     {
1014       TAlgoStateErrorName errName = SMESH_Hypothesis::HYP_MISSING;
1015       SMESH_Hypothesis::Hypothesis_Status status;
1016       algo->CheckHypothesis( aMesh, aSubMesh->GetSubShape(), status );
1017       if ( status == SMESH_Hypothesis::HYP_BAD_PARAMETER ) {
1018         MESSAGE( "ERROR: hypothesis of " << (IsGlobalHypothesis ? "Global " : "Local ")
1019                  << "<" << algo->GetName() << "> has a bad parameter value");
1020         errName = status;
1021       } else if ( status == SMESH_Hypothesis::HYP_BAD_GEOMETRY ) {
1022         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
1023                  << "<" << algo->GetName() << "> assigned to mismatching geometry");
1024         errName = status;
1025       } else {
1026         MESSAGE( "ERROR: " << (IsGlobalHypothesis ? "Global " : "Local ")
1027                  << "<" << algo->GetName() << "> misses some hypothesis");
1028       }
1029       if (IsGlobalHypothesis)
1030         globalChecked[ algo->GetDim() ] = true;
1031       theErrors.push_back( SMESH_Gen::TAlgoStateError() );
1032       theErrors.back().Set( errName, algo, IsGlobalHypothesis );
1033     }
1034     ret = false;
1035     break;
1036   }
1037   case SMESH_subMesh::HYP_OK:
1038     algo = aSubMesh->GetAlgo();
1039     ret = true;
1040     if (!algo->NeedDiscreteBoundary())
1041     {
1042       SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
1043                                                                        /*complexShapeFirst=*/false);
1044       while ( itsub->more() )
1045         aCheckedMap.insert( itsub->next() );
1046     }
1047     break;
1048   default: ASSERT(0);
1049   }
1050
1051   // do not check under algo that hides sub-algos or
1052   // re-start checking NO_ALGO state
1053   ASSERT (algo);
1054   bool isTopLocalAlgo =
1055     ( aTopAlgoDim <= algo->GetDim() && !aGen->IsGlobalHypothesis( algo, aMesh ));
1056   if (!algo->NeedDiscreteBoundary() || isTopLocalAlgo)
1057   {
1058     bool checkNoAlgo2 = ( algo->NeedDiscreteBoundary() );
1059     SMESH_subMeshIteratorPtr itsub = aSubMesh->getDependsOnIterator( /*includeSelf=*/false,
1060                                                                      /*complexShapeFirst=*/true);
1061     while ( itsub->more() )
1062     {
1063       // sub-meshes should not be checked further more
1064       SMESH_subMesh* sm = itsub->next();
1065
1066       if (isTopLocalAlgo)
1067       {
1068         //check algo on sub-meshes
1069         int aTopAlgoDim2 = algo->GetDim();
1070         if (!checkMissing (aGen, aMesh, sm, aTopAlgoDim2,
1071                            globalChecked, checkNoAlgo2, aCheckedMap, theErrors))
1072         {
1073           ret = false;
1074           if (sm->GetAlgoState() == SMESH_subMesh::NO_ALGO )
1075             checkNoAlgo2 = false;
1076         }
1077       }
1078       aCheckedMap.insert( sm );
1079     }
1080   }
1081   return ret;
1082 }
1083
1084 //=======================================================================
1085 //function : CheckAlgoState
1086 //purpose  : notify on bad state of attached algos, return false
1087 //           if Compute() would fail because of some algo bad state
1088 //=======================================================================
1089
1090 bool SMESH_Gen::CheckAlgoState(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
1091 {
1092   list< TAlgoStateError > errors;
1093   return GetAlgoState( aMesh, aShape, errors );
1094 }
1095
1096 //=======================================================================
1097 //function : GetAlgoState
1098 //purpose  : notify on bad state of attached algos, return false
1099 //           if Compute() would fail because of some algo bad state
1100 //           theErrors list contains problems description
1101 //=======================================================================
1102
1103 bool SMESH_Gen::GetAlgoState(SMESH_Mesh&               theMesh,
1104                              const TopoDS_Shape&       theShape,
1105                              list< TAlgoStateError > & theErrors)
1106 {
1107   bool ret = true;
1108   bool hasAlgo = false;
1109
1110   SMESH_subMesh*          sm = theMesh.GetSubMesh(theShape);
1111   const SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1112   TopoDS_Shape     mainShape = meshDS->ShapeToMesh();
1113
1114   // -----------------
1115   // get global algos
1116   // -----------------
1117
1118   const SMESH_Algo* aGlobAlgoArr[] = {0,0,0,0};
1119
1120   const list<const SMESHDS_Hypothesis*>& listHyp = meshDS->GetHypothesis( mainShape );
1121   list<const SMESHDS_Hypothesis*>::const_iterator it=listHyp.begin();
1122   for ( ; it != listHyp.end(); it++)
1123   {
1124     const SMESHDS_Hypothesis * aHyp = *it;
1125     if (aHyp->GetType() == SMESHDS_Hypothesis::PARAM_ALGO)
1126       continue;
1127
1128     const SMESH_Algo* algo = dynamic_cast<const SMESH_Algo*> (aHyp);
1129     ASSERT ( algo );
1130
1131     int dim = algo->GetDim();
1132     aGlobAlgoArr[ dim ] = algo;
1133
1134     hasAlgo = true;
1135   }
1136
1137   // --------------------------------------------------------
1138   // info on algos that will be ignored because of ones that
1139   // don't NeedDiscreteBoundary() attached to super-shapes,
1140   // check that a conform mesh will be produced
1141   // --------------------------------------------------------
1142
1143
1144   // find a global algo possibly hiding sub-algos
1145   int dim;
1146   const SMESH_Algo* aGlobIgnoAlgo = 0;
1147   for (dim = 3; dim > 0; dim--)
1148   {
1149     if (aGlobAlgoArr[ dim ] &&
1150         !aGlobAlgoArr[ dim ]->NeedDiscreteBoundary() /*&&
1151         !aGlobAlgoArr[ dim ]->SupportSubmeshes()*/ )
1152     {
1153       aGlobIgnoAlgo = aGlobAlgoArr[ dim ];
1154       break;
1155     }
1156   }
1157
1158   set<SMESH_subMesh*> aCheckedSubs;
1159   bool checkConform = ( !theMesh.IsNotConformAllowed() );
1160
1161   // loop on theShape and its sub-shapes
1162   SMESH_subMeshIteratorPtr revItSub = sm->getDependsOnIterator( /*includeSelf=*/true,
1163                                                                 /*complexShapeFirst=*/true);
1164   while ( revItSub->more() )
1165   {
1166     SMESH_subMesh* smToCheck = revItSub->next();
1167     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
1168       break;
1169
1170     if ( aCheckedSubs.insert( smToCheck ).second ) // not yet checked
1171       if (!checkConformIgnoredAlgos (theMesh, smToCheck, aGlobIgnoAlgo,
1172                                      0, checkConform, aCheckedSubs, theErrors))
1173         ret = false;
1174
1175     if ( smToCheck->GetAlgoState() != SMESH_subMesh::NO_ALGO )
1176       hasAlgo = true;
1177   }
1178
1179   // ----------------------------------------------------------------
1180   // info on missing hypothesis and find out if all needed algos are
1181   // well defined
1182   // ----------------------------------------------------------------
1183
1184   // find max dim of global algo
1185   int aTopAlgoDim = 0;
1186   for (dim = 3; dim > 0; dim--)
1187   {
1188     if (aGlobAlgoArr[ dim ])
1189     {
1190       aTopAlgoDim = dim;
1191       break;
1192     }
1193   }
1194   bool checkNoAlgo = theMesh.HasShapeToMesh() ? bool( aTopAlgoDim ) : false;
1195   bool globalChecked[] = { false, false, false, false };
1196
1197   // loop on theShape and its sub-shapes
1198   aCheckedSubs.clear();
1199   revItSub = sm->getDependsOnIterator( /*includeSelf=*/true, /*complexShapeFirst=*/true);
1200   while ( revItSub->more() )
1201   {
1202     SMESH_subMesh* smToCheck = revItSub->next();
1203     if ( smToCheck->GetSubShape().ShapeType() == TopAbs_VERTEX)
1204       break;
1205
1206     if (!checkMissing (this, theMesh, smToCheck, aTopAlgoDim,
1207                        globalChecked, checkNoAlgo, aCheckedSubs, theErrors))
1208     {
1209       ret = false;
1210       if (smToCheck->GetAlgoState() == SMESH_subMesh::NO_ALGO )
1211         checkNoAlgo = false;
1212     }
1213   }
1214
1215   if ( !hasAlgo ) {
1216     ret = false;
1217     theErrors.push_back( TAlgoStateError() );
1218     theErrors.back().Set( SMESH_Hypothesis::HYP_MISSING, theMesh.HasShapeToMesh() ? 1 : 3, true );
1219   }
1220
1221   return ret;
1222 }
1223
1224 //=======================================================================
1225 //function : IsGlobalHypothesis
1226 //purpose  : check if theAlgo is attached to the main shape
1227 //=======================================================================
1228
1229 bool SMESH_Gen::IsGlobalHypothesis(const SMESH_Hypothesis* theHyp, SMESH_Mesh& aMesh)
1230 {
1231   SMESH_HypoFilter filter( SMESH_HypoFilter::Is( theHyp ));
1232   return aMesh.GetHypothesis( aMesh.GetMeshDS()->ShapeToMesh(), filter, false );
1233 }
1234
1235 //================================================================================
1236 /*!
1237  * \brief Return paths to xml files of plugins
1238  */
1239 //================================================================================
1240
1241 std::vector< std::string > SMESH_Gen::GetPluginXMLPaths()
1242 {
1243   // Get paths to xml files of plugins
1244   vector< string > xmlPaths;
1245   string sep;
1246   if ( const char* meshersList = getenv("SMESH_MeshersList") )
1247   {
1248     string meshers = meshersList, plugin;
1249     string::size_type from = 0, pos;
1250     while ( from < meshers.size() )
1251     {
1252       // cut off plugin name
1253       pos = meshers.find( env_sep, from );
1254       if ( pos != string::npos )
1255         plugin = meshers.substr( from, pos-from );
1256       else
1257         plugin = meshers.substr( from ), pos = meshers.size();
1258       from = pos + 1;
1259
1260       // get PLUGIN_ROOT_DIR path
1261       string rootDirVar, pluginSubDir = plugin;
1262       if ( plugin == "StdMeshers" )
1263         rootDirVar = "SMESH", pluginSubDir = "smesh";
1264       else
1265         for ( pos = 0; pos < plugin.size(); ++pos )
1266           rootDirVar += toupper( plugin[pos] );
1267       rootDirVar += "_ROOT_DIR";
1268
1269       const char* rootDir = getenv( rootDirVar.c_str() );
1270       if ( !rootDir || strlen(rootDir) == 0 )
1271       {
1272         rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
1273         rootDir = getenv( rootDirVar.c_str() );
1274         if ( !rootDir || strlen(rootDir) == 0 ) continue;
1275       }
1276
1277       // get a separator from rootDir
1278       for ( int i = strlen( rootDir )-1; i >= 0 && sep.empty(); --i )
1279         if ( rootDir[i] == '/' || rootDir[i] == '\\' )
1280         {
1281           sep = rootDir[i];
1282           break;
1283         }
1284 #ifdef WIN32
1285       if (sep.empty() ) sep = "\\";
1286 #else
1287       if (sep.empty() ) sep = "/";
1288 #endif
1289
1290       // get a path to resource file
1291       string xmlPath = rootDir;
1292       if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
1293         xmlPath += sep;
1294       xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
1295       for ( pos = 0; pos < pluginSubDir.size(); ++pos )
1296         xmlPath += tolower( pluginSubDir[pos] );
1297       xmlPath += sep + plugin + ".xml";
1298       bool fileOK;
1299 #ifdef WIN32
1300 #  ifdef UNICODE
1301       const wchar_t* path = Kernel_Utils::decode_s(xmlPath);
1302       SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
1303 #  else
1304       const char* path = xmlPath.c_str();
1305 #  endif
1306       fileOK = (GetFileAttributes(path) != INVALID_FILE_ATTRIBUTES);
1307
1308 #else
1309       fileOK = (access(xmlPath.c_str(), F_OK) == 0);
1310 #endif
1311       if ( fileOK )
1312         xmlPaths.push_back( xmlPath );
1313     }
1314   }
1315
1316   return xmlPaths;
1317 }
1318
1319 //=============================================================================
1320 /*!
1321  * Finds algo to mesh a shape. Optionally returns a shape the found algo is bound to
1322  */
1323 //=============================================================================
1324
1325 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_Mesh &         aMesh,
1326                                const TopoDS_Shape & aShape,
1327                                TopoDS_Shape*        assignedTo)
1328 {
1329   return GetAlgo( aMesh.GetSubMesh( aShape ), assignedTo );
1330 }
1331
1332 //=============================================================================
1333 /*!
1334  * Finds algo to mesh a sub-mesh. Optionally returns a shape the found algo is bound to
1335  */
1336 //=============================================================================
1337
1338 SMESH_Algo *SMESH_Gen::GetAlgo(SMESH_subMesh * aSubMesh,
1339                                TopoDS_Shape*   assignedTo)
1340 {
1341   if ( !aSubMesh ) return 0;
1342
1343   const TopoDS_Shape & aShape = aSubMesh->GetSubShape();
1344   SMESH_Mesh&          aMesh  = *aSubMesh->GetFather();
1345
1346   SMESH_HypoFilter filter( SMESH_HypoFilter::IsAlgo() );
1347   if ( aMesh.HasShapeToMesh() )
1348     filter.And( filter.IsApplicableTo( aShape ));
1349
1350   typedef SMESH_Algo::Features AlgoData;
1351
1352   TopoDS_Shape assignedToShape;
1353   SMESH_Algo* algo =
1354     (SMESH_Algo*) aMesh.GetHypothesis( aSubMesh, filter, true, &assignedToShape );
1355
1356   if ( algo &&
1357        aShape.ShapeType() == TopAbs_FACE &&
1358        !aShape.IsSame( assignedToShape ) &&
1359        SMESH_MesherHelper::NbAncestors( aShape, aMesh, TopAbs_SOLID ) > 1 )
1360   {
1361     // Issue 0021559. If there is another 2D algo with different types of output
1362     // elements that can be used to mesh aShape, and 3D algos on adjacent SOLIDs
1363     // have different types of input elements, we choose a most appropriate 2D algo.
1364
1365     // try to find a concurrent 2D algo
1366     filter.AndNot( filter.Is( algo ));
1367     TopoDS_Shape assignedToShape2;
1368     SMESH_Algo* algo2 =
1369       (SMESH_Algo*) aMesh.GetHypothesis( aSubMesh, filter, true, &assignedToShape2 );
1370     if ( algo2 &&                                                  // algo found
1371          !assignedToShape2.IsSame( aMesh.GetShapeToMesh() ) &&     // algo is local
1372          ( SMESH_MesherHelper::GetGroupType( assignedToShape2 ) == // algo of the same level
1373            SMESH_MesherHelper::GetGroupType( assignedToShape )) &&
1374          aMesh.IsOrderOK( aMesh.GetSubMesh( assignedToShape2 ),    // no forced order
1375                           aMesh.GetSubMesh( assignedToShape  )))
1376     {
1377       // get algos on the adjacent SOLIDs
1378       filter.Init( filter.IsAlgo() ).And( filter.HasDim( 3 ));
1379       vector< SMESH_Algo* > algos3D;
1380       PShapeIteratorPtr solidIt = SMESH_MesherHelper::GetAncestors( aShape, aMesh,
1381                                                                     TopAbs_SOLID );
1382       while ( const TopoDS_Shape* solid = solidIt->next() )
1383         if ( SMESH_Algo* algo3D = (SMESH_Algo*) aMesh.GetHypothesis( *solid, filter, true ))
1384         {
1385           algos3D.push_back( algo3D );
1386           filter.AndNot( filter.HasName( algo3D->GetName() ));
1387         }
1388       // check compatibility of algos
1389       if ( algos3D.size() > 1 )
1390       {
1391         const AlgoData& algoData    = algo->SMESH_Algo::GetFeatures();
1392         const AlgoData& algoData2   = algo2->SMESH_Algo::GetFeatures();
1393         const AlgoData& algoData3d0 = algos3D[0]->SMESH_Algo::GetFeatures();
1394         const AlgoData& algoData3d1 = algos3D[1]->SMESH_Algo::GetFeatures();
1395         if (( algoData2.IsCompatible( algoData3d0 ) &&
1396               algoData2.IsCompatible( algoData3d1 ))
1397             &&
1398             !(algoData.IsCompatible( algoData3d0 ) &&
1399               algoData.IsCompatible( algoData3d1 )))
1400           algo = algo2;
1401       }
1402     }
1403   }
1404
1405   if ( assignedTo && algo )
1406     * assignedTo = assignedToShape;
1407
1408   return algo;
1409 }
1410
1411 //=============================================================================
1412 /*!
1413  * Returns StudyContextStruct for a study
1414  */
1415 //=============================================================================
1416
1417 StudyContextStruct *SMESH_Gen::GetStudyContext()
1418 {
1419   return _studyContext;
1420 }
1421
1422 //================================================================================
1423 /*!
1424  * \brief Return shape dimension by TopAbs_ShapeEnum
1425  */
1426 //================================================================================
1427
1428 int SMESH_Gen::GetShapeDim(const TopAbs_ShapeEnum & aShapeType)
1429 {
1430   static vector<int> dim;
1431   if ( dim.empty() )
1432   {
1433     dim.resize( TopAbs_SHAPE, -1 );
1434     dim[ TopAbs_COMPOUND ]  = MeshDim_3D;
1435     dim[ TopAbs_COMPSOLID ] = MeshDim_3D;
1436     dim[ TopAbs_SOLID ]     = MeshDim_3D;
1437     dim[ TopAbs_SHELL ]     = MeshDim_2D;
1438     dim[ TopAbs_FACE  ]     = MeshDim_2D;
1439     dim[ TopAbs_WIRE ]      = MeshDim_1D;
1440     dim[ TopAbs_EDGE ]      = MeshDim_1D;
1441     dim[ TopAbs_VERTEX ]    = MeshDim_0D;
1442   }
1443   return dim[ aShapeType ];
1444 }
1445
1446 //================================================================================
1447 /*!
1448  * \brief Return shape dimension by exploding compounds
1449  */
1450 //================================================================================
1451
1452 int SMESH_Gen::GetFlatShapeDim(const TopoDS_Shape &aShape)
1453 {
1454   int aShapeDim;
1455   if ( aShape.ShapeType() == TopAbs_COMPOUND ||
1456        aShape.ShapeType() == TopAbs_COMPSOLID )
1457   {
1458     TopoDS_Iterator it( aShape );
1459     aShapeDim = GetFlatShapeDim( it.Value() );
1460   }
1461   else
1462     aShapeDim = GetShapeDim( aShape );
1463   return aShapeDim;
1464 }
1465
1466 //=============================================================================
1467 /*!
1468  * Generate a new id unique within this Gen
1469  */
1470 //=============================================================================
1471
1472 int SMESH_Gen::GetANewId()
1473 {
1474   return _hypId++;
1475 }