Salome HOME
IPAL52860: Free Edges control mis-location and mis-visibility
[modules/smesh.git] / src / Controls / SMESH_Controls.cxx
1 // Copyright (C) 2007-2015  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 #include "SMESH_ControlsDef.hxx"
24
25 #include "SMDS_BallElement.hxx"
26 #include "SMDS_Iterator.hxx"
27 #include "SMDS_Mesh.hxx"
28 #include "SMDS_MeshElement.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_QuadraticEdge.hxx"
31 #include "SMDS_QuadraticFaceOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMESHDS_GroupBase.hxx"
34 #include "SMESHDS_Mesh.hxx"
35 #include "SMESH_OctreeNode.hxx"
36 #include "SMESH_MeshAlgos.hxx"
37
38 #include <Basics_Utils.hxx>
39
40 #include <BRepAdaptor_Surface.hxx>
41 #include <BRepClass_FaceClassifier.hxx>
42 #include <BRep_Tool.hxx>
43 #include <Geom_CylindricalSurface.hxx>
44 #include <Geom_Plane.hxx>
45 #include <Geom_Surface.hxx>
46 #include <Precision.hxx>
47 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
48 #include <TColStd_MapOfInteger.hxx>
49 #include <TColStd_SequenceOfAsciiString.hxx>
50 #include <TColgp_Array1OfXYZ.hxx>
51 #include <TopAbs.hxx>
52 #include <TopExp.hxx>
53 #include <TopoDS.hxx>
54 #include <TopoDS_Edge.hxx>
55 #include <TopoDS_Face.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <TopoDS_Shape.hxx>
58 #include <TopoDS_Vertex.hxx>
59 #include <gp_Ax3.hxx>
60 #include <gp_Cylinder.hxx>
61 #include <gp_Dir.hxx>
62 #include <gp_Pln.hxx>
63 #include <gp_Pnt.hxx>
64 #include <gp_Vec.hxx>
65 #include <gp_XYZ.hxx>
66
67 #include <vtkMeshQuality.h>
68
69 #include <set>
70 #include <limits>
71
72 /*
73                             AUXILIARY METHODS
74 */
75
76 namespace {
77
78   const double theEps = 1e-100;
79   const double theInf = 1e+100;
80
81   inline gp_XYZ gpXYZ(const SMDS_MeshNode* aNode )
82   {
83     return gp_XYZ(aNode->X(), aNode->Y(), aNode->Z() );
84   }
85
86   inline double getAngle( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 )
87   {
88     gp_Vec v1( P1 - P2 ), v2( P3 - P2 );
89
90     return v1.Magnitude() < gp::Resolution() ||
91       v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 );
92   }
93
94   inline double getArea( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 )
95   {
96     gp_Vec aVec1( P2 - P1 );
97     gp_Vec aVec2( P3 - P1 );
98     return ( aVec1 ^ aVec2 ).Magnitude() * 0.5;
99   }
100
101   inline double getArea( const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3 )
102   {
103     return getArea( P1.XYZ(), P2.XYZ(), P3.XYZ() );
104   }
105
106
107
108   inline double getDistance( const gp_XYZ& P1, const gp_XYZ& P2 )
109   {
110     double aDist = gp_Pnt( P1 ).Distance( gp_Pnt( P2 ) );
111     return aDist;
112   }
113
114   int getNbMultiConnection( const SMDS_Mesh* theMesh, const int theId )
115   {
116     if ( theMesh == 0 )
117       return 0;
118
119     const SMDS_MeshElement* anEdge = theMesh->FindElement( theId );
120     if ( anEdge == 0 || anEdge->GetType() != SMDSAbs_Edge/* || anEdge->NbNodes() != 2 */)
121       return 0;
122
123     // for each pair of nodes in anEdge (there are 2 pairs in a quadratic edge)
124     // count elements containing both nodes of the pair.
125     // Note that there may be such cases for a quadratic edge (a horizontal line):
126     //
127     //  Case 1          Case 2
128     //  |     |      |        |      |
129     //  |     |      |        |      |
130     //  +-----+------+  +-----+------+ 
131     //  |            |  |            |
132     //  |            |  |            |
133     // result sould be 2 in both cases
134     //
135     int aResult0 = 0, aResult1 = 0;
136      // last node, it is a medium one in a quadratic edge
137     const SMDS_MeshNode* aLastNode = anEdge->GetNode( anEdge->NbNodes() - 1 );
138     const SMDS_MeshNode*    aNode0 = anEdge->GetNode( 0 );
139     const SMDS_MeshNode*    aNode1 = anEdge->GetNode( 1 );
140     if ( aNode1 == aLastNode ) aNode1 = 0;
141
142     SMDS_ElemIteratorPtr anElemIter = aLastNode->GetInverseElementIterator();
143     while( anElemIter->more() ) {
144       const SMDS_MeshElement* anElem = anElemIter->next();
145       if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) {
146         SMDS_ElemIteratorPtr anIter = anElem->nodesIterator();
147         while ( anIter->more() ) {
148           if ( const SMDS_MeshElement* anElemNode = anIter->next() ) {
149             if ( anElemNode == aNode0 ) {
150               aResult0++;
151               if ( !aNode1 ) break; // not a quadratic edge
152             }
153             else if ( anElemNode == aNode1 )
154               aResult1++;
155           }
156         }
157       }
158     }
159     int aResult = std::max ( aResult0, aResult1 );
160
161     return aResult;
162   }
163
164   gp_XYZ getNormale( const SMDS_MeshFace* theFace, bool* ok=0 )
165   {
166     int aNbNode = theFace->NbNodes();
167
168     gp_XYZ q1 = gpXYZ( theFace->GetNode(1)) - gpXYZ( theFace->GetNode(0));
169     gp_XYZ q2 = gpXYZ( theFace->GetNode(2)) - gpXYZ( theFace->GetNode(0));
170     gp_XYZ n  = q1 ^ q2;
171     if ( aNbNode > 3 ) {
172       gp_XYZ q3 = gpXYZ( theFace->GetNode(3)) - gpXYZ( theFace->GetNode(0));
173       n += q2 ^ q3;
174     }
175     double len = n.Modulus();
176     bool zeroLen = ( len <= numeric_limits<double>::min());
177     if ( !zeroLen )
178       n /= len;
179
180     if (ok) *ok = !zeroLen;
181
182     return n;
183   }
184 }
185
186
187
188 using namespace SMESH::Controls;
189
190 /*
191  *                               FUNCTORS
192  */
193
194 //================================================================================
195 /*
196   Class       : NumericalFunctor
197   Description : Base class for numerical functors
198 */
199 //================================================================================
200
201 NumericalFunctor::NumericalFunctor():
202   myMesh(NULL)
203 {
204   myPrecision = -1;
205 }
206
207 void NumericalFunctor::SetMesh( const SMDS_Mesh* theMesh )
208 {
209   myMesh = theMesh;
210 }
211
212 bool NumericalFunctor::GetPoints(const int       theId,
213                                  TSequenceOfXYZ& theRes ) const
214 {
215   theRes.clear();
216
217   if ( myMesh == 0 )
218     return false;
219
220   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
221   if ( !anElem || anElem->GetType() != this->GetType() )
222     return false;
223
224   return GetPoints( anElem, theRes );
225 }
226
227 bool NumericalFunctor::GetPoints(const SMDS_MeshElement* anElem,
228                                  TSequenceOfXYZ&         theRes )
229 {
230   theRes.clear();
231
232   if ( anElem == 0 )
233     return false;
234
235   theRes.reserve( anElem->NbNodes() );
236   theRes.setElement( anElem );
237
238   // Get nodes of the element
239   SMDS_ElemIteratorPtr anIter;
240
241   if ( anElem->IsQuadratic() ) {
242     switch ( anElem->GetType() ) {
243     case SMDSAbs_Edge:
244       anIter = dynamic_cast<const SMDS_VtkEdge*>
245         (anElem)->interlacedNodesElemIterator();
246       break;
247     case SMDSAbs_Face:
248       anIter = dynamic_cast<const SMDS_VtkFace*>
249         (anElem)->interlacedNodesElemIterator();
250       break;
251     default:
252       anIter = anElem->nodesIterator();
253     }
254   }
255   else {
256     anIter = anElem->nodesIterator();
257   }
258
259   if ( anIter ) {
260     double xyz[3];
261     while( anIter->more() ) {
262       if ( const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( anIter->next() ))
263       {
264         aNode->GetXYZ( xyz );
265         theRes.push_back( gp_XYZ( xyz[0], xyz[1], xyz[2] ));
266       }
267     }
268   }
269
270   return true;
271 }
272
273 long  NumericalFunctor::GetPrecision() const
274 {
275   return myPrecision;
276 }
277
278 void  NumericalFunctor::SetPrecision( const long thePrecision )
279 {
280   myPrecision = thePrecision;
281   myPrecisionValue = pow( 10., (double)( myPrecision ) );
282 }
283
284 double NumericalFunctor::GetValue( long theId )
285 {
286   double aVal = 0;
287
288   myCurrElement = myMesh->FindElement( theId );
289
290   TSequenceOfXYZ P;
291   if ( GetPoints( theId, P )) // elem type is checked here
292     aVal = Round( GetValue( P ));
293
294   return aVal;
295 }
296
297 double NumericalFunctor::Round( const double & aVal )
298 {
299   return ( myPrecision >= 0 ) ? floor( aVal * myPrecisionValue + 0.5 ) / myPrecisionValue : aVal;
300 }
301
302 //================================================================================
303 /*!
304  * \brief Return histogram of functor values
305  *  \param nbIntervals - number of intervals
306  *  \param nbEvents - number of mesh elements having values within i-th interval
307  *  \param funValues - boundaries of intervals
308  *  \param elements - elements to check vulue of; empty list means "of all"
309  *  \param minmax - boundaries of diapason of values to divide into intervals
310  */
311 //================================================================================
312
313 void NumericalFunctor::GetHistogram(int                  nbIntervals,
314                                     std::vector<int>&    nbEvents,
315                                     std::vector<double>& funValues,
316                                     const vector<int>&   elements,
317                                     const double*        minmax,
318                                     const bool           isLogarithmic)
319 {
320   if ( nbIntervals < 1 ||
321        !myMesh ||
322        !myMesh->GetMeshInfo().NbElements( GetType() ))
323     return;
324   nbEvents.resize( nbIntervals, 0 );
325   funValues.resize( nbIntervals+1 );
326
327   // get all values sorted
328   std::multiset< double > values;
329   if ( elements.empty() )
330   {
331     SMDS_ElemIteratorPtr elemIt = myMesh->elementsIterator( GetType() );
332     while ( elemIt->more() )
333       values.insert( GetValue( elemIt->next()->GetID() ));
334   }
335   else
336   {
337     vector<int>::const_iterator id = elements.begin();
338     for ( ; id != elements.end(); ++id )
339       values.insert( GetValue( *id ));
340   }
341
342   if ( minmax )
343   {
344     funValues[0] = minmax[0];
345     funValues[nbIntervals] = minmax[1];
346   }
347   else
348   {
349     funValues[0] = *values.begin();
350     funValues[nbIntervals] = *values.rbegin();
351   }
352   // case nbIntervals == 1
353   if ( nbIntervals == 1 )
354   {
355     nbEvents[0] = values.size();
356     return;
357   }
358   // case of 1 value
359   if (funValues.front() == funValues.back())
360   {
361     nbEvents.resize( 1 );
362     nbEvents[0] = values.size();
363     funValues[1] = funValues.back();
364     funValues.resize( 2 );
365   }
366   // generic case
367   std::multiset< double >::iterator min = values.begin(), max;
368   for ( int i = 0; i < nbIntervals; ++i )
369   {
370     // find end value of i-th interval
371     double r = (i+1) / double(nbIntervals);
372     if (isLogarithmic && funValues.front() > 1e-07 && funValues.back() > 1e-07) {
373       double logmin = log10(funValues.front());
374       double lval = logmin + r * (log10(funValues.back()) - logmin);
375       funValues[i+1] = pow(10.0, lval);
376     }
377     else {
378       funValues[i+1] = funValues.front() * (1-r) + funValues.back() * r;
379     }
380
381     // count values in the i-th interval if there are any
382     if ( min != values.end() && *min <= funValues[i+1] )
383     {
384       // find the first value out of the interval
385       max = values.upper_bound( funValues[i+1] ); // max is greater than funValues[i+1], or end()
386       nbEvents[i] = std::distance( min, max );
387       min = max;
388     }
389   }
390   // add values larger than minmax[1]
391   nbEvents.back() += std::distance( min, values.end() );
392 }
393
394 //=======================================================================
395 /*
396   Class       : Volume
397   Description : Functor calculating volume of a 3D element
398 */
399 //================================================================================
400
401 double Volume::GetValue( long theElementId )
402 {
403   if ( theElementId && myMesh ) {
404     SMDS_VolumeTool aVolumeTool;
405     if ( aVolumeTool.Set( myMesh->FindElement( theElementId )))
406       return aVolumeTool.GetSize();
407   }
408   return 0;
409 }
410
411 double Volume::GetBadRate( double Value, int /*nbNodes*/ ) const
412 {
413   return Value;
414 }
415
416 SMDSAbs_ElementType Volume::GetType() const
417 {
418   return SMDSAbs_Volume;
419 }
420
421 //=======================================================================
422 /*
423   Class       : MaxElementLength2D
424   Description : Functor calculating maximum length of 2D element
425 */
426 //================================================================================
427
428 double MaxElementLength2D::GetValue( const TSequenceOfXYZ& P )
429 {
430   if(P.size() == 0)
431     return 0.;
432   double aVal = 0;
433   int len = P.size();
434   if( len == 3 ) { // triangles
435     double L1 = getDistance(P( 1 ),P( 2 ));
436     double L2 = getDistance(P( 2 ),P( 3 ));
437     double L3 = getDistance(P( 3 ),P( 1 ));
438     aVal = Max(L1,Max(L2,L3));
439   }
440   else if( len == 4 ) { // quadrangles
441     double L1 = getDistance(P( 1 ),P( 2 ));
442     double L2 = getDistance(P( 2 ),P( 3 ));
443     double L3 = getDistance(P( 3 ),P( 4 ));
444     double L4 = getDistance(P( 4 ),P( 1 ));
445     double D1 = getDistance(P( 1 ),P( 3 ));
446     double D2 = getDistance(P( 2 ),P( 4 ));
447     aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2));
448   }
449   else if( len == 6 ) { // quadratic triangles
450     double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
451     double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
452     double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 ));
453     aVal = Max(L1,Max(L2,L3));
454   }
455   else if( len == 8 || len == 9 ) { // quadratic quadrangles
456     double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
457     double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
458     double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 ));
459     double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 ));
460     double D1 = getDistance(P( 1 ),P( 5 ));
461     double D2 = getDistance(P( 3 ),P( 7 ));
462     aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2));
463   }
464   // Diagonals are undefined for concave polygons
465   // else if ( P.getElementEntity() == SMDSEntity_Quad_Polygon && P.size() > 2 ) // quad polygon
466   // {
467   //   // sides
468   //   aVal = getDistance( P( 1 ), P( P.size() )) + getDistance( P( P.size() ), P( P.size()-1 ));
469   //   for ( size_t i = 1; i < P.size()-1; i += 2 )
470   //   {
471   //     double L = getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 ));
472   //     aVal = Max( aVal, L );
473   //   }
474   //   // diagonals
475   //   for ( int i = P.size()-5; i > 0; i -= 2 )
476   //     for ( int j = i + 4; j < P.size() + i - 2; i += 2 )
477   //     {
478   //       double D = getDistance( P( i ), P( j ));
479   //       aVal = Max( aVal, D );
480   //     }
481   // }
482   // { // polygons
483     
484   // }
485
486   if( myPrecision >= 0 )
487   {
488     double prec = pow( 10., (double)myPrecision );
489     aVal = floor( aVal * prec + 0.5 ) / prec;
490   }
491   return aVal;
492 }
493
494 double MaxElementLength2D::GetValue( long theElementId )
495 {
496   TSequenceOfXYZ P;
497   return GetPoints( theElementId, P ) ? GetValue(P) : 0.0;
498 }
499
500 double MaxElementLength2D::GetBadRate( double Value, int /*nbNodes*/ ) const
501 {
502   return Value;
503 }
504
505 SMDSAbs_ElementType MaxElementLength2D::GetType() const
506 {
507   return SMDSAbs_Face;
508 }
509
510 //=======================================================================
511 /*
512   Class       : MaxElementLength3D
513   Description : Functor calculating maximum length of 3D element
514 */
515 //================================================================================
516
517 double MaxElementLength3D::GetValue( long theElementId )
518 {
519   TSequenceOfXYZ P;
520   if( GetPoints( theElementId, P ) ) {
521     double aVal = 0;
522     const SMDS_MeshElement* aElem = myMesh->FindElement( theElementId );
523     SMDSAbs_ElementType aType = aElem->GetType();
524     int len = P.size();
525     switch( aType ) {
526     case SMDSAbs_Volume:
527       if( len == 4 ) { // tetras
528         double L1 = getDistance(P( 1 ),P( 2 ));
529         double L2 = getDistance(P( 2 ),P( 3 ));
530         double L3 = getDistance(P( 3 ),P( 1 ));
531         double L4 = getDistance(P( 1 ),P( 4 ));
532         double L5 = getDistance(P( 2 ),P( 4 ));
533         double L6 = getDistance(P( 3 ),P( 4 ));
534         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
535         break;
536       }
537       else if( len == 5 ) { // pyramids
538         double L1 = getDistance(P( 1 ),P( 2 ));
539         double L2 = getDistance(P( 2 ),P( 3 ));
540         double L3 = getDistance(P( 3 ),P( 4 ));
541         double L4 = getDistance(P( 4 ),P( 1 ));
542         double L5 = getDistance(P( 1 ),P( 5 ));
543         double L6 = getDistance(P( 2 ),P( 5 ));
544         double L7 = getDistance(P( 3 ),P( 5 ));
545         double L8 = getDistance(P( 4 ),P( 5 ));
546         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
547         aVal = Max(aVal,Max(L7,L8));
548         break;
549       }
550       else if( len == 6 ) { // pentas
551         double L1 = getDistance(P( 1 ),P( 2 ));
552         double L2 = getDistance(P( 2 ),P( 3 ));
553         double L3 = getDistance(P( 3 ),P( 1 ));
554         double L4 = getDistance(P( 4 ),P( 5 ));
555         double L5 = getDistance(P( 5 ),P( 6 ));
556         double L6 = getDistance(P( 6 ),P( 4 ));
557         double L7 = getDistance(P( 1 ),P( 4 ));
558         double L8 = getDistance(P( 2 ),P( 5 ));
559         double L9 = getDistance(P( 3 ),P( 6 ));
560         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
561         aVal = Max(aVal,Max(Max(L7,L8),L9));
562         break;
563       }
564       else if( len == 8 ) { // hexas
565         double L1 = getDistance(P( 1 ),P( 2 ));
566         double L2 = getDistance(P( 2 ),P( 3 ));
567         double L3 = getDistance(P( 3 ),P( 4 ));
568         double L4 = getDistance(P( 4 ),P( 1 ));
569         double L5 = getDistance(P( 5 ),P( 6 ));
570         double L6 = getDistance(P( 6 ),P( 7 ));
571         double L7 = getDistance(P( 7 ),P( 8 ));
572         double L8 = getDistance(P( 8 ),P( 5 ));
573         double L9 = getDistance(P( 1 ),P( 5 ));
574         double L10= getDistance(P( 2 ),P( 6 ));
575         double L11= getDistance(P( 3 ),P( 7 ));
576         double L12= getDistance(P( 4 ),P( 8 ));
577         double D1 = getDistance(P( 1 ),P( 7 ));
578         double D2 = getDistance(P( 2 ),P( 8 ));
579         double D3 = getDistance(P( 3 ),P( 5 ));
580         double D4 = getDistance(P( 4 ),P( 6 ));
581         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
582         aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10)));
583         aVal = Max(aVal,Max(L11,L12));
584         aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4)));
585         break;
586       }
587       else if( len == 12 ) { // hexagonal prism
588         for ( int i1 = 1; i1 < 12; ++i1 )
589           for ( int i2 = i1+1; i1 <= 12; ++i1 )
590             aVal = Max( aVal, getDistance(P( i1 ),P( i2 )));
591         break;
592       }
593       else if( len == 10 ) { // quadratic tetras
594         double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 ));
595         double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 ));
596         double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 ));
597         double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
598         double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 ));
599         double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 ));
600         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
601         break;
602       }
603       else if( len == 13 ) { // quadratic pyramids
604         double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 ));
605         double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 ));
606         double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
607         double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
608         double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
609         double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 ));
610         double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 ));
611         double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 ));
612         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
613         aVal = Max(aVal,Max(L7,L8));
614         break;
615       }
616       else if( len == 15 ) { // quadratic pentas
617         double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 ));
618         double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 ));
619         double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
620         double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
621         double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 ));
622         double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 ));
623         double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 ));
624         double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 ));
625         double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 ));
626         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
627         aVal = Max(aVal,Max(Max(L7,L8),L9));
628         break;
629       }
630       else if( len == 20 || len == 27 ) { // quadratic hexas
631         double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 ));
632         double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 ));
633         double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 ));
634         double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 ));
635         double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 ));
636         double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 ));
637         double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 ));
638         double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 ));
639         double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 ));
640         double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 ));
641         double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 ));
642         double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 ));
643         double D1 = getDistance(P( 1 ),P( 7 ));
644         double D2 = getDistance(P( 2 ),P( 8 ));
645         double D3 = getDistance(P( 3 ),P( 5 ));
646         double D4 = getDistance(P( 4 ),P( 6 ));
647         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
648         aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10)));
649         aVal = Max(aVal,Max(L11,L12));
650         aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4)));
651         break;
652       }
653       else if( len > 1 && aElem->IsPoly() ) { // polys
654         // get the maximum distance between all pairs of nodes
655         for( int i = 1; i <= len; i++ ) {
656           for( int j = 1; j <= len; j++ ) {
657             if( j > i ) { // optimization of the loop
658               double D = getDistance( P(i), P(j) );
659               aVal = Max( aVal, D );
660             }
661           }
662         }
663       }
664     }
665
666     if( myPrecision >= 0 )
667     {
668       double prec = pow( 10., (double)myPrecision );
669       aVal = floor( aVal * prec + 0.5 ) / prec;
670     }
671     return aVal;
672   }
673   return 0.;
674 }
675
676 double MaxElementLength3D::GetBadRate( double Value, int /*nbNodes*/ ) const
677 {
678   return Value;
679 }
680
681 SMDSAbs_ElementType MaxElementLength3D::GetType() const
682 {
683   return SMDSAbs_Volume;
684 }
685
686 //=======================================================================
687 /*
688   Class       : MinimumAngle
689   Description : Functor for calculation of minimum angle
690 */
691 //================================================================================
692
693 double MinimumAngle::GetValue( const TSequenceOfXYZ& P )
694 {
695   double aMin;
696
697   if (P.size() <3)
698     return 0.;
699
700   aMin = getAngle(P( P.size() ), P( 1 ), P( 2 ));
701   aMin = Min(aMin,getAngle(P( P.size()-1 ), P( P.size() ), P( 1 )));
702
703   for ( int i = 2; i < P.size(); i++ )
704   {
705     double A0 = getAngle( P( i-1 ), P( i ), P( i+1 ) );
706     aMin = Min(aMin,A0);
707   }
708
709   return aMin * 180.0 / M_PI;
710 }
711
712 double MinimumAngle::GetBadRate( double Value, int nbNodes ) const
713 {
714   //const double aBestAngle = PI / nbNodes;
715   const double aBestAngle = 180.0 - ( 360.0 / double(nbNodes) );
716   return ( fabs( aBestAngle - Value ));
717 }
718
719 SMDSAbs_ElementType MinimumAngle::GetType() const
720 {
721   return SMDSAbs_Face;
722 }
723
724
725 //================================================================================
726 /*
727   Class       : AspectRatio
728   Description : Functor for calculating aspect ratio
729 */
730 //================================================================================
731
732 double AspectRatio::GetValue( long theId )
733 {
734   double aVal = 0;
735   myCurrElement = myMesh->FindElement( theId );
736   if ( myCurrElement && myCurrElement->GetVtkType() == VTK_QUAD )
737   {
738     // issue 21723
739     vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid();
740     if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() ))
741       aVal = Round( vtkMeshQuality::QuadAspectRatio( avtkCell ));
742   }
743   else
744   {
745     TSequenceOfXYZ P;
746     if ( GetPoints( myCurrElement, P ))
747       aVal = Round( GetValue( P ));
748   }
749   return aVal;
750 }
751
752 double AspectRatio::GetValue( const TSequenceOfXYZ& P )
753 {
754   // According to "Mesh quality control" by Nadir Bouhamau referring to
755   // Pascal Jean Frey and Paul-Louis George. Maillages, applications aux elements finis.
756   // Hermes Science publications, Paris 1999 ISBN 2-7462-0024-4
757   // PAL10872
758
759   int nbNodes = P.size();
760
761   if ( nbNodes < 3 )
762     return 0;
763
764   // Compute aspect ratio
765
766   if ( nbNodes == 3 ) {
767     // Compute lengths of the sides
768     std::vector< double > aLen (nbNodes);
769     for ( int i = 0; i < nbNodes - 1; i++ )
770       aLen[ i ] = getDistance( P( i + 1 ), P( i + 2 ) );
771     aLen[ nbNodes - 1 ] = getDistance( P( 1 ), P( nbNodes ) );
772     // Q = alfa * h * p / S, where
773     //
774     // alfa = sqrt( 3 ) / 6
775     // h - length of the longest edge
776     // p - half perimeter
777     // S - triangle surface
778     const double alfa = sqrt( 3. ) / 6.;
779     double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) );
780     double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.;
781     double anArea = getArea( P( 1 ), P( 2 ), P( 3 ) );
782     if ( anArea <= theEps  )
783       return theInf;
784     return alfa * maxLen * half_perimeter / anArea;
785   }
786   else if ( nbNodes == 6 ) { // quadratic triangles
787     // Compute lengths of the sides
788     std::vector< double > aLen (3);
789     aLen[0] = getDistance( P(1), P(3) );
790     aLen[1] = getDistance( P(3), P(5) );
791     aLen[2] = getDistance( P(5), P(1) );
792     // Q = alfa * h * p / S, where
793     //
794     // alfa = sqrt( 3 ) / 6
795     // h - length of the longest edge
796     // p - half perimeter
797     // S - triangle surface
798     const double alfa = sqrt( 3. ) / 6.;
799     double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) );
800     double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.;
801     double anArea = getArea( P(1), P(3), P(5) );
802     if ( anArea <= theEps )
803       return theInf;
804     return alfa * maxLen * half_perimeter / anArea;
805   }
806   else if( nbNodes == 4 ) { // quadrangle
807     // Compute lengths of the sides
808     std::vector< double > aLen (4);
809     aLen[0] = getDistance( P(1), P(2) );
810     aLen[1] = getDistance( P(2), P(3) );
811     aLen[2] = getDistance( P(3), P(4) );
812     aLen[3] = getDistance( P(4), P(1) );
813     // Compute lengths of the diagonals
814     std::vector< double > aDia (2);
815     aDia[0] = getDistance( P(1), P(3) );
816     aDia[1] = getDistance( P(2), P(4) );
817     // Compute areas of all triangles which can be built
818     // taking three nodes of the quadrangle
819     std::vector< double > anArea (4);
820     anArea[0] = getArea( P(1), P(2), P(3) );
821     anArea[1] = getArea( P(1), P(2), P(4) );
822     anArea[2] = getArea( P(1), P(3), P(4) );
823     anArea[3] = getArea( P(2), P(3), P(4) );
824     // Q = alpha * L * C1 / C2, where
825     //
826     // alpha = sqrt( 1/32 )
827     // L = max( L1, L2, L3, L4, D1, D2 )
828     // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 )
829     // C2 = min( S1, S2, S3, S4 )
830     // Li - lengths of the edges
831     // Di - lengths of the diagonals
832     // Si - areas of the triangles
833     const double alpha = sqrt( 1 / 32. );
834     double L = Max( aLen[ 0 ],
835                  Max( aLen[ 1 ],
836                    Max( aLen[ 2 ],
837                      Max( aLen[ 3 ],
838                        Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) );
839     double C1 = sqrt( ( aLen[0] * aLen[0] +
840                         aLen[1] * aLen[1] +
841                         aLen[2] * aLen[2] +
842                         aLen[3] * aLen[3] ) / 4. );
843     double C2 = Min( anArea[ 0 ],
844                   Min( anArea[ 1 ],
845                     Min( anArea[ 2 ], anArea[ 3 ] ) ) );
846     if ( C2 <= theEps )
847       return theInf;
848     return alpha * L * C1 / C2;
849   }
850   else if( nbNodes == 8 || nbNodes == 9 ) { // nbNodes==8 - quadratic quadrangle
851     // Compute lengths of the sides
852     std::vector< double > aLen (4);
853     aLen[0] = getDistance( P(1), P(3) );
854     aLen[1] = getDistance( P(3), P(5) );
855     aLen[2] = getDistance( P(5), P(7) );
856     aLen[3] = getDistance( P(7), P(1) );
857     // Compute lengths of the diagonals
858     std::vector< double > aDia (2);
859     aDia[0] = getDistance( P(1), P(5) );
860     aDia[1] = getDistance( P(3), P(7) );
861     // Compute areas of all triangles which can be built
862     // taking three nodes of the quadrangle
863     std::vector< double > anArea (4);
864     anArea[0] = getArea( P(1), P(3), P(5) );
865     anArea[1] = getArea( P(1), P(3), P(7) );
866     anArea[2] = getArea( P(1), P(5), P(7) );
867     anArea[3] = getArea( P(3), P(5), P(7) );
868     // Q = alpha * L * C1 / C2, where
869     //
870     // alpha = sqrt( 1/32 )
871     // L = max( L1, L2, L3, L4, D1, D2 )
872     // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 )
873     // C2 = min( S1, S2, S3, S4 )
874     // Li - lengths of the edges
875     // Di - lengths of the diagonals
876     // Si - areas of the triangles
877     const double alpha = sqrt( 1 / 32. );
878     double L = Max( aLen[ 0 ],
879                  Max( aLen[ 1 ],
880                    Max( aLen[ 2 ],
881                      Max( aLen[ 3 ],
882                        Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) );
883     double C1 = sqrt( ( aLen[0] * aLen[0] +
884                         aLen[1] * aLen[1] +
885                         aLen[2] * aLen[2] +
886                         aLen[3] * aLen[3] ) / 4. );
887     double C2 = Min( anArea[ 0 ],
888                   Min( anArea[ 1 ],
889                     Min( anArea[ 2 ], anArea[ 3 ] ) ) );
890     if ( C2 <= theEps )
891       return theInf;
892     return alpha * L * C1 / C2;
893   }
894   return 0;
895 }
896
897 double AspectRatio::GetBadRate( double Value, int /*nbNodes*/ ) const
898 {
899   // the aspect ratio is in the range [1.0,infinity]
900   // < 1.0 = very bad, zero area
901   // 1.0 = good
902   // infinity = bad
903   return ( Value < 0.9 ) ? 1000 : Value / 1000.;
904 }
905
906 SMDSAbs_ElementType AspectRatio::GetType() const
907 {
908   return SMDSAbs_Face;
909 }
910
911
912 //================================================================================
913 /*
914   Class       : AspectRatio3D
915   Description : Functor for calculating aspect ratio
916 */
917 //================================================================================
918
919 namespace{
920
921   inline double getHalfPerimeter(double theTria[3]){
922     return (theTria[0] + theTria[1] + theTria[2])/2.0;
923   }
924
925   inline double getArea(double theHalfPerim, double theTria[3]){
926     return sqrt(theHalfPerim*
927                 (theHalfPerim-theTria[0])*
928                 (theHalfPerim-theTria[1])*
929                 (theHalfPerim-theTria[2]));
930   }
931
932   inline double getVolume(double theLen[6]){
933     double a2 = theLen[0]*theLen[0];
934     double b2 = theLen[1]*theLen[1];
935     double c2 = theLen[2]*theLen[2];
936     double d2 = theLen[3]*theLen[3];
937     double e2 = theLen[4]*theLen[4];
938     double f2 = theLen[5]*theLen[5];
939     double P = 4.0*a2*b2*d2;
940     double Q = a2*(b2+d2-e2)-b2*(a2+d2-f2)-d2*(a2+b2-c2);
941     double R = (b2+d2-e2)*(a2+d2-f2)*(a2+d2-f2);
942     return sqrt(P-Q+R)/12.0;
943   }
944
945   inline double getVolume2(double theLen[6]){
946     double a2 = theLen[0]*theLen[0];
947     double b2 = theLen[1]*theLen[1];
948     double c2 = theLen[2]*theLen[2];
949     double d2 = theLen[3]*theLen[3];
950     double e2 = theLen[4]*theLen[4];
951     double f2 = theLen[5]*theLen[5];
952
953     double P = a2*e2*(b2+c2+d2+f2-a2-e2);
954     double Q = b2*f2*(a2+c2+d2+e2-b2-f2);
955     double R = c2*d2*(a2+b2+e2+f2-c2-d2);
956     double S = a2*b2*d2+b2*c2*e2+a2*c2*f2+d2*e2*f2;
957
958     return sqrt(P+Q+R-S)/12.0;
959   }
960
961   inline double getVolume(const TSequenceOfXYZ& P){
962     gp_Vec aVec1( P( 2 ) - P( 1 ) );
963     gp_Vec aVec2( P( 3 ) - P( 1 ) );
964     gp_Vec aVec3( P( 4 ) - P( 1 ) );
965     gp_Vec anAreaVec( aVec1 ^ aVec2 );
966     return fabs(aVec3 * anAreaVec) / 6.0;
967   }
968
969   inline double getMaxHeight(double theLen[6])
970   {
971     double aHeight = std::max(theLen[0],theLen[1]);
972     aHeight = std::max(aHeight,theLen[2]);
973     aHeight = std::max(aHeight,theLen[3]);
974     aHeight = std::max(aHeight,theLen[4]);
975     aHeight = std::max(aHeight,theLen[5]);
976     return aHeight;
977   }
978
979 }
980
981 double AspectRatio3D::GetValue( long theId )
982 {
983   double aVal = 0;
984   myCurrElement = myMesh->FindElement( theId );
985   if ( myCurrElement && myCurrElement->GetVtkType() == VTK_TETRA )
986   {
987     // Action from CoTech | ACTION 31.3:
988     // EURIWARE BO: Homogenize the formulas used to calculate the Controls in SMESH to fit with
989     // those of ParaView. The library used by ParaView for those calculations can be reused in SMESH.
990     vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid();
991     if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() ))
992       aVal = Round( vtkMeshQuality::TetAspectRatio( avtkCell ));
993   }
994   else
995   {
996     TSequenceOfXYZ P;
997     if ( GetPoints( myCurrElement, P ))
998       aVal = Round( GetValue( P ));
999   }
1000   return aVal;
1001 }
1002
1003 double AspectRatio3D::GetValue( const TSequenceOfXYZ& P )
1004 {
1005   double aQuality = 0.0;
1006   if(myCurrElement->IsPoly()) return aQuality;
1007
1008   int nbNodes = P.size();
1009
1010   if(myCurrElement->IsQuadratic()) {
1011     if(nbNodes==10) nbNodes=4; // quadratic tetrahedron
1012     else if(nbNodes==13) nbNodes=5; // quadratic pyramid
1013     else if(nbNodes==15) nbNodes=6; // quadratic pentahedron
1014     else if(nbNodes==20) nbNodes=8; // quadratic hexahedron
1015     else if(nbNodes==27) nbNodes=8; // quadratic hexahedron
1016     else return aQuality;
1017   }
1018
1019   switch(nbNodes) {
1020   case 4:{
1021     double aLen[6] = {
1022       getDistance(P( 1 ),P( 2 )), // a
1023       getDistance(P( 2 ),P( 3 )), // b
1024       getDistance(P( 3 ),P( 1 )), // c
1025       getDistance(P( 2 ),P( 4 )), // d
1026       getDistance(P( 3 ),P( 4 )), // e
1027       getDistance(P( 1 ),P( 4 ))  // f
1028     };
1029     double aTria[4][3] = {
1030       {aLen[0],aLen[1],aLen[2]}, // abc
1031       {aLen[0],aLen[3],aLen[5]}, // adf
1032       {aLen[1],aLen[3],aLen[4]}, // bde
1033       {aLen[2],aLen[4],aLen[5]}  // cef
1034     };
1035     double aSumArea = 0.0;
1036     double aHalfPerimeter = getHalfPerimeter(aTria[0]);
1037     double anArea = getArea(aHalfPerimeter,aTria[0]);
1038     aSumArea += anArea;
1039     aHalfPerimeter = getHalfPerimeter(aTria[1]);
1040     anArea = getArea(aHalfPerimeter,aTria[1]);
1041     aSumArea += anArea;
1042     aHalfPerimeter = getHalfPerimeter(aTria[2]);
1043     anArea = getArea(aHalfPerimeter,aTria[2]);
1044     aSumArea += anArea;
1045     aHalfPerimeter = getHalfPerimeter(aTria[3]);
1046     anArea = getArea(aHalfPerimeter,aTria[3]);
1047     aSumArea += anArea;
1048     double aVolume = getVolume(P);
1049     //double aVolume = getVolume(aLen);
1050     double aHeight = getMaxHeight(aLen);
1051     static double aCoeff = sqrt(2.0)/12.0;
1052     if ( aVolume > DBL_MIN )
1053       aQuality = aCoeff*aHeight*aSumArea/aVolume;
1054     break;
1055   }
1056   case 5:{
1057     {
1058       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 3 ),P( 5 )};
1059       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1060     }
1061     {
1062       gp_XYZ aXYZ[4] = {P( 1 ),P( 3 ),P( 4 ),P( 5 )};
1063       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1064     }
1065     {
1066       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 5 )};
1067       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1068     }
1069     {
1070       gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 4 ),P( 5 )};
1071       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1072     }
1073     break;
1074   }
1075   case 6:{
1076     {
1077       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 6 )};
1078       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1079     }
1080     {
1081       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 3 )};
1082       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1083     }
1084     {
1085       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 6 )};
1086       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1087     }
1088     {
1089       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )};
1090       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1091     }
1092     {
1093       gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 6 )};
1094       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1095     }
1096     {
1097       gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 3 )};
1098       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1099     }
1100     break;
1101   }
1102   case 8:{
1103     {
1104       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )};
1105       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1106     }
1107     {
1108       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 4 )};
1109       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1110     }
1111     {
1112       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 7 )};
1113       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1114     }
1115     {
1116       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 8 )};
1117       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1118     }
1119     {
1120       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 3 )};
1121       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1122     }
1123     {
1124       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 4 )};
1125       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1126     }
1127     {
1128       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 7 )};
1129       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1130     }
1131     {
1132       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 8 )};
1133       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1134     }
1135     {
1136       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 3 )};
1137       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1138     }
1139     {
1140       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 4 )};
1141       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1142     }
1143     {
1144       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 7 )};
1145       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1146     }
1147     {
1148       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 8 )};
1149       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1150     }
1151     {
1152       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 1 )};
1153       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1154     }
1155     {
1156       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 2 )};
1157       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1158     }
1159     {
1160       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 5 )};
1161       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1162     }
1163     {
1164       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 6 )};
1165       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1166     }
1167     {
1168       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 1 )};
1169       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1170     }
1171     {
1172       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 2 )};
1173       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1174     }
1175     {
1176       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 5 )};
1177       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1178     }
1179     {
1180       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 6 )};
1181       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1182     }
1183     {
1184       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 1 )};
1185       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1186     }
1187     {
1188       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )};
1189       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1190     }
1191     {
1192       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 5 )};
1193       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1194     }
1195     {
1196       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 6 )};
1197       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1198     }
1199     {
1200       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )};
1201       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1202     }
1203     {
1204       gp_XYZ aXYZ[4] = {P( 4 ),P( 5 ),P( 8 ),P( 2 )};
1205       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1206     }
1207     {
1208       gp_XYZ aXYZ[4] = {P( 1 ),P( 4 ),P( 5 ),P( 3 )};
1209       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1210     }
1211     {
1212       gp_XYZ aXYZ[4] = {P( 3 ),P( 6 ),P( 7 ),P( 1 )};
1213       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1214     }
1215     {
1216       gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 6 ),P( 4 )};
1217       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1218     }
1219     {
1220       gp_XYZ aXYZ[4] = {P( 5 ),P( 6 ),P( 8 ),P( 3 )};
1221       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1222     }
1223     {
1224       gp_XYZ aXYZ[4] = {P( 7 ),P( 8 ),P( 6 ),P( 1 )};
1225       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1226     }
1227     {
1228       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 7 )};
1229       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1230     }
1231     {
1232       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 2 ),P( 5 )};
1233       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1234     }
1235     break;
1236   }
1237   case 12:
1238     {
1239       gp_XYZ aXYZ[8] = {P( 1 ),P( 2 ),P( 4 ),P( 5 ),P( 7 ),P( 8 ),P( 10 ),P( 11 )};
1240       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality);
1241     }
1242     {
1243       gp_XYZ aXYZ[8] = {P( 2 ),P( 3 ),P( 5 ),P( 6 ),P( 8 ),P( 9 ),P( 11 ),P( 12 )};
1244       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality);
1245     }
1246     {
1247       gp_XYZ aXYZ[8] = {P( 3 ),P( 4 ),P( 6 ),P( 1 ),P( 9 ),P( 10 ),P( 12 ),P( 7 )};
1248       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality);
1249     }
1250     break;
1251   } // switch(nbNodes)
1252
1253   if ( nbNodes > 4 ) {
1254     // avaluate aspect ratio of quadranle faces
1255     AspectRatio aspect2D;
1256     SMDS_VolumeTool::VolumeType type = SMDS_VolumeTool::GetType( nbNodes );
1257     int nbFaces = SMDS_VolumeTool::NbFaces( type );
1258     TSequenceOfXYZ points(4);
1259     for ( int i = 0; i < nbFaces; ++i ) { // loop on faces of a volume
1260       if ( SMDS_VolumeTool::NbFaceNodes( type, i ) != 4 )
1261         continue;
1262       const int* pInd = SMDS_VolumeTool::GetFaceNodesIndices( type, i, true );
1263       for ( int p = 0; p < 4; ++p ) // loop on nodes of a quadranle face
1264         points( p + 1 ) = P( pInd[ p ] + 1 );
1265       aQuality = std::max( aQuality, aspect2D.GetValue( points ));
1266     }
1267   }
1268   return aQuality;
1269 }
1270
1271 double AspectRatio3D::GetBadRate( double Value, int /*nbNodes*/ ) const
1272 {
1273   // the aspect ratio is in the range [1.0,infinity]
1274   // 1.0 = good
1275   // infinity = bad
1276   return Value / 1000.;
1277 }
1278
1279 SMDSAbs_ElementType AspectRatio3D::GetType() const
1280 {
1281   return SMDSAbs_Volume;
1282 }
1283
1284
1285 //================================================================================
1286 /*
1287   Class       : Warping
1288   Description : Functor for calculating warping
1289 */
1290 //================================================================================
1291
1292 double Warping::GetValue( const TSequenceOfXYZ& P )
1293 {
1294   if ( P.size() != 4 )
1295     return 0;
1296
1297   gp_XYZ G = ( P( 1 ) + P( 2 ) + P( 3 ) + P( 4 ) ) / 4.;
1298
1299   double A1 = ComputeA( P( 1 ), P( 2 ), P( 3 ), G );
1300   double A2 = ComputeA( P( 2 ), P( 3 ), P( 4 ), G );
1301   double A3 = ComputeA( P( 3 ), P( 4 ), P( 1 ), G );
1302   double A4 = ComputeA( P( 4 ), P( 1 ), P( 2 ), G );
1303
1304   double val = Max( Max( A1, A2 ), Max( A3, A4 ) );
1305
1306   const double eps = 0.1; // val is in degrees
1307
1308   return val < eps ? 0. : val;
1309 }
1310
1311 double Warping::ComputeA( const gp_XYZ& thePnt1,
1312                           const gp_XYZ& thePnt2,
1313                           const gp_XYZ& thePnt3,
1314                           const gp_XYZ& theG ) const
1315 {
1316   double aLen1 = gp_Pnt( thePnt1 ).Distance( gp_Pnt( thePnt2 ) );
1317   double aLen2 = gp_Pnt( thePnt2 ).Distance( gp_Pnt( thePnt3 ) );
1318   double L = Min( aLen1, aLen2 ) * 0.5;
1319   if ( L < theEps )
1320     return theInf;
1321
1322   gp_XYZ GI = ( thePnt2 + thePnt1 ) / 2. - theG;
1323   gp_XYZ GJ = ( thePnt3 + thePnt2 ) / 2. - theG;
1324   gp_XYZ N  = GI.Crossed( GJ );
1325
1326   if ( N.Modulus() < gp::Resolution() )
1327     return M_PI / 2;
1328
1329   N.Normalize();
1330
1331   double H = ( thePnt2 - theG ).Dot( N );
1332   return asin( fabs( H / L ) ) * 180. / M_PI;
1333 }
1334
1335 double Warping::GetBadRate( double Value, int /*nbNodes*/ ) const
1336 {
1337   // the warp is in the range [0.0,PI/2]
1338   // 0.0 = good (no warp)
1339   // PI/2 = bad  (face pliee)
1340   return Value;
1341 }
1342
1343 SMDSAbs_ElementType Warping::GetType() const
1344 {
1345   return SMDSAbs_Face;
1346 }
1347
1348
1349 //================================================================================
1350 /*
1351   Class       : Taper
1352   Description : Functor for calculating taper
1353 */
1354 //================================================================================
1355
1356 double Taper::GetValue( const TSequenceOfXYZ& P )
1357 {
1358   if ( P.size() != 4 )
1359     return 0.;
1360
1361   // Compute taper
1362   double J1 = getArea( P( 4 ), P( 1 ), P( 2 ) );
1363   double J2 = getArea( P( 3 ), P( 1 ), P( 2 ) );
1364   double J3 = getArea( P( 2 ), P( 3 ), P( 4 ) );
1365   double J4 = getArea( P( 3 ), P( 4 ), P( 1 ) );
1366
1367   double JA = 0.25 * ( J1 + J2 + J3 + J4 );
1368   if ( JA <= theEps )
1369     return theInf;
1370
1371   double T1 = fabs( ( J1 - JA ) / JA );
1372   double T2 = fabs( ( J2 - JA ) / JA );
1373   double T3 = fabs( ( J3 - JA ) / JA );
1374   double T4 = fabs( ( J4 - JA ) / JA );
1375
1376   double val = Max( Max( T1, T2 ), Max( T3, T4 ) );
1377
1378   const double eps = 0.01;
1379
1380   return val < eps ? 0. : val;
1381 }
1382
1383 double Taper::GetBadRate( double Value, int /*nbNodes*/ ) const
1384 {
1385   // the taper is in the range [0.0,1.0]
1386   // 0.0 = good (no taper)
1387   // 1.0 = bad  (les cotes opposes sont allignes)
1388   return Value;
1389 }
1390
1391 SMDSAbs_ElementType Taper::GetType() const
1392 {
1393   return SMDSAbs_Face;
1394 }
1395
1396 //================================================================================
1397 /*
1398   Class       : Skew
1399   Description : Functor for calculating skew in degrees
1400 */
1401 //================================================================================
1402
1403 static inline double skewAngle( const gp_XYZ& p1, const gp_XYZ& p2, const gp_XYZ& p3 )
1404 {
1405   gp_XYZ p12 = ( p2 + p1 ) / 2.;
1406   gp_XYZ p23 = ( p3 + p2 ) / 2.;
1407   gp_XYZ p31 = ( p3 + p1 ) / 2.;
1408
1409   gp_Vec v1( p31 - p2 ), v2( p12 - p23 );
1410
1411   return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0. : v1.Angle( v2 );
1412 }
1413
1414 double Skew::GetValue( const TSequenceOfXYZ& P )
1415 {
1416   if ( P.size() != 3 && P.size() != 4 )
1417     return 0.;
1418
1419   // Compute skew
1420   const double PI2 = M_PI / 2.;
1421   if ( P.size() == 3 )
1422   {
1423     double A0 = fabs( PI2 - skewAngle( P( 3 ), P( 1 ), P( 2 ) ) );
1424     double A1 = fabs( PI2 - skewAngle( P( 1 ), P( 2 ), P( 3 ) ) );
1425     double A2 = fabs( PI2 - skewAngle( P( 2 ), P( 3 ), P( 1 ) ) );
1426
1427     return Max( A0, Max( A1, A2 ) ) * 180. / M_PI;
1428   }
1429   else
1430   {
1431     gp_XYZ p12 = ( P( 1 ) + P( 2 ) ) / 2.;
1432     gp_XYZ p23 = ( P( 2 ) + P( 3 ) ) / 2.;
1433     gp_XYZ p34 = ( P( 3 ) + P( 4 ) ) / 2.;
1434     gp_XYZ p41 = ( P( 4 ) + P( 1 ) ) / 2.;
1435
1436     gp_Vec v1( p34 - p12 ), v2( p23 - p41 );
1437     double A = v1.Magnitude() <= gp::Resolution() || v2.Magnitude() <= gp::Resolution()
1438       ? 0. : fabs( PI2 - v1.Angle( v2 ) );
1439
1440     double val = A * 180. / M_PI;
1441
1442     const double eps = 0.1; // val is in degrees
1443
1444     return val < eps ? 0. : val;
1445   }
1446 }
1447
1448 double Skew::GetBadRate( double Value, int /*nbNodes*/ ) const
1449 {
1450   // the skew is in the range [0.0,PI/2].
1451   // 0.0 = good
1452   // PI/2 = bad
1453   return Value;
1454 }
1455
1456 SMDSAbs_ElementType Skew::GetType() const
1457 {
1458   return SMDSAbs_Face;
1459 }
1460
1461
1462 //================================================================================
1463 /*
1464   Class       : Area
1465   Description : Functor for calculating area
1466 */
1467 //================================================================================
1468
1469 double Area::GetValue( const TSequenceOfXYZ& P )
1470 {
1471   double val = 0.0;
1472   if ( P.size() > 2 )
1473   {
1474     gp_Vec aVec1( P(2) - P(1) );
1475     gp_Vec aVec2( P(3) - P(1) );
1476     gp_Vec SumVec = aVec1 ^ aVec2;
1477
1478     for (int i=4; i<=P.size(); i++)
1479     {
1480       gp_Vec aVec1( P(i-1) - P(1) );
1481       gp_Vec aVec2( P(i) - P(1) );
1482       gp_Vec tmp = aVec1 ^ aVec2;
1483       SumVec.Add(tmp);
1484     }
1485     val = SumVec.Magnitude() * 0.5;
1486   }
1487   return val;
1488 }
1489
1490 double Area::GetBadRate( double Value, int /*nbNodes*/ ) const
1491 {
1492   // meaningless as it is not a quality control functor
1493   return Value;
1494 }
1495
1496 SMDSAbs_ElementType Area::GetType() const
1497 {
1498   return SMDSAbs_Face;
1499 }
1500
1501 //================================================================================
1502 /*
1503   Class       : Length
1504   Description : Functor for calculating length of edge
1505 */
1506 //================================================================================
1507
1508 double Length::GetValue( const TSequenceOfXYZ& P )
1509 {
1510   switch ( P.size() ) {
1511   case 2:  return getDistance( P( 1 ), P( 2 ) );
1512   case 3:  return getDistance( P( 1 ), P( 2 ) ) + getDistance( P( 2 ), P( 3 ) );
1513   default: return 0.;
1514   }
1515 }
1516
1517 double Length::GetBadRate( double Value, int /*nbNodes*/ ) const
1518 {
1519   // meaningless as it is not quality control functor
1520   return Value;
1521 }
1522
1523 SMDSAbs_ElementType Length::GetType() const
1524 {
1525   return SMDSAbs_Edge;
1526 }
1527
1528 //================================================================================
1529 /*
1530   Class       : Length2D
1531   Description : Functor for calculating minimal length of edge
1532 */
1533 //================================================================================
1534
1535 double Length2D::GetValue( long theElementId )
1536 {
1537   TSequenceOfXYZ P;
1538
1539   if ( GetPoints( theElementId, P ))
1540   {
1541     double aVal = 0;
1542     int len = P.size();
1543     SMDSAbs_EntityType aType = P.getElementEntity();
1544
1545     switch (aType) {
1546     case SMDSEntity_Edge:
1547       if (len == 2)
1548         aVal = getDistance( P( 1 ), P( 2 ) );
1549       break;
1550     case SMDSEntity_Quad_Edge:
1551       if (len == 3) // quadratic edge
1552         aVal = getDistance(P( 1 ),P( 3 )) + getDistance(P( 3 ),P( 2 ));
1553       break;
1554     case SMDSEntity_Triangle:
1555       if (len == 3){ // triangles
1556         double L1 = getDistance(P( 1 ),P( 2 ));
1557         double L2 = getDistance(P( 2 ),P( 3 ));
1558         double L3 = getDistance(P( 3 ),P( 1 ));
1559         aVal = Min(L1,Min(L2,L3));
1560       }
1561       break;
1562     case SMDSEntity_Quadrangle:
1563       if (len == 4){ // quadrangles
1564         double L1 = getDistance(P( 1 ),P( 2 ));
1565         double L2 = getDistance(P( 2 ),P( 3 ));
1566         double L3 = getDistance(P( 3 ),P( 4 ));
1567         double L4 = getDistance(P( 4 ),P( 1 ));
1568         aVal = Min(Min(L1,L2),Min(L3,L4));
1569       }
1570       break;
1571     case SMDSEntity_Quad_Triangle:
1572     case SMDSEntity_BiQuad_Triangle:
1573       if (len >= 6){ // quadratic triangles
1574         double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
1575         double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
1576         double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 ));
1577         aVal = Min(L1,Min(L2,L3));
1578       }
1579       break;
1580     case SMDSEntity_Quad_Quadrangle:
1581     case SMDSEntity_BiQuad_Quadrangle:
1582       if (len >= 8){ // quadratic quadrangles
1583         double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
1584         double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
1585         double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 ));
1586         double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 ));
1587         aVal = Min(Min(L1,L2),Min(L3,L4));
1588       }
1589       break;
1590     case SMDSEntity_Tetra:
1591       if (len == 4){ // tetrahedra
1592         double L1 = getDistance(P( 1 ),P( 2 ));
1593         double L2 = getDistance(P( 2 ),P( 3 ));
1594         double L3 = getDistance(P( 3 ),P( 1 ));
1595         double L4 = getDistance(P( 1 ),P( 4 ));
1596         double L5 = getDistance(P( 2 ),P( 4 ));
1597         double L6 = getDistance(P( 3 ),P( 4 ));
1598         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1599       }
1600       break;
1601     case SMDSEntity_Pyramid:
1602       if (len == 5){ // piramids
1603         double L1 = getDistance(P( 1 ),P( 2 ));
1604         double L2 = getDistance(P( 2 ),P( 3 ));
1605         double L3 = getDistance(P( 3 ),P( 4 ));
1606         double L4 = getDistance(P( 4 ),P( 1 ));
1607         double L5 = getDistance(P( 1 ),P( 5 ));
1608         double L6 = getDistance(P( 2 ),P( 5 ));
1609         double L7 = getDistance(P( 3 ),P( 5 ));
1610         double L8 = getDistance(P( 4 ),P( 5 ));
1611
1612         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1613         aVal = Min(aVal,Min(L7,L8));
1614       }
1615       break;
1616     case SMDSEntity_Penta:
1617       if (len == 6) { // pentaidres
1618         double L1 = getDistance(P( 1 ),P( 2 ));
1619         double L2 = getDistance(P( 2 ),P( 3 ));
1620         double L3 = getDistance(P( 3 ),P( 1 ));
1621         double L4 = getDistance(P( 4 ),P( 5 ));
1622         double L5 = getDistance(P( 5 ),P( 6 ));
1623         double L6 = getDistance(P( 6 ),P( 4 ));
1624         double L7 = getDistance(P( 1 ),P( 4 ));
1625         double L8 = getDistance(P( 2 ),P( 5 ));
1626         double L9 = getDistance(P( 3 ),P( 6 ));
1627
1628         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1629         aVal = Min(aVal,Min(Min(L7,L8),L9));
1630       }
1631       break;
1632     case SMDSEntity_Hexa:
1633       if (len == 8){ // hexahedron
1634         double L1 = getDistance(P( 1 ),P( 2 ));
1635         double L2 = getDistance(P( 2 ),P( 3 ));
1636         double L3 = getDistance(P( 3 ),P( 4 ));
1637         double L4 = getDistance(P( 4 ),P( 1 ));
1638         double L5 = getDistance(P( 5 ),P( 6 ));
1639         double L6 = getDistance(P( 6 ),P( 7 ));
1640         double L7 = getDistance(P( 7 ),P( 8 ));
1641         double L8 = getDistance(P( 8 ),P( 5 ));
1642         double L9 = getDistance(P( 1 ),P( 5 ));
1643         double L10= getDistance(P( 2 ),P( 6 ));
1644         double L11= getDistance(P( 3 ),P( 7 ));
1645         double L12= getDistance(P( 4 ),P( 8 ));
1646
1647         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1648         aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10)));
1649         aVal = Min(aVal,Min(L11,L12));
1650       }
1651       break;
1652     case SMDSEntity_Quad_Tetra:
1653       if (len == 10){ // quadratic tetraidrs
1654         double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 ));
1655         double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 ));
1656         double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 ));
1657         double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
1658         double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 ));
1659         double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 ));
1660         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1661       }
1662       break;
1663     case SMDSEntity_Quad_Pyramid:
1664       if (len == 13){ // quadratic piramids
1665         double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 ));
1666         double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 ));
1667         double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
1668         double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
1669         double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
1670         double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 ));
1671         double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 ));
1672         double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 ));
1673         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1674         aVal = Min(aVal,Min(L7,L8));
1675       }
1676       break;
1677     case SMDSEntity_Quad_Penta:
1678       if (len == 15){ // quadratic pentaidres
1679         double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 ));
1680         double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 ));
1681         double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
1682         double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
1683         double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 ));
1684         double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 ));
1685         double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 ));
1686         double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 ));
1687         double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 ));
1688         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1689         aVal = Min(aVal,Min(Min(L7,L8),L9));
1690       }
1691       break;
1692     case SMDSEntity_Quad_Hexa:
1693     case SMDSEntity_TriQuad_Hexa:
1694       if (len >= 20) { // quadratic hexaider
1695         double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 ));
1696         double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 ));
1697         double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 ));
1698         double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 ));
1699         double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 ));
1700         double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 ));
1701         double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 ));
1702         double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 ));
1703         double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 ));
1704         double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 ));
1705         double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 ));
1706         double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 ));
1707         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1708         aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10)));
1709         aVal = Min(aVal,Min(L11,L12));
1710       }
1711       break;
1712     case SMDSEntity_Polygon:
1713       if ( len > 1 ) {
1714         aVal = getDistance( P(1), P( P.size() ));
1715         for ( size_t i = 1; i < P.size(); ++i )
1716           aVal = Min( aVal, getDistance( P( i ), P( i+1 )));
1717       }
1718       break;
1719     case SMDSEntity_Quad_Polygon:
1720       if ( len > 2 ) {
1721         aVal = getDistance( P(1), P( P.size() )) + getDistance( P(P.size()), P( P.size()-1 ));
1722         for ( size_t i = 1; i < P.size()-1; i += 2 )
1723           aVal = Min( aVal, getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 )));
1724       }
1725       break;
1726     case SMDSEntity_Hexagonal_Prism:
1727       if (len == 12) { // hexagonal prism
1728         double L1 = getDistance(P( 1 ),P( 2 ));
1729         double L2 = getDistance(P( 2 ),P( 3 ));
1730         double L3 = getDistance(P( 3 ),P( 4 ));
1731         double L4 = getDistance(P( 4 ),P( 5 ));
1732         double L5 = getDistance(P( 5 ),P( 6 ));
1733         double L6 = getDistance(P( 6 ),P( 1 ));
1734
1735         double L7 = getDistance(P( 7 ), P( 8 ));
1736         double L8 = getDistance(P( 8 ), P( 9 ));
1737         double L9 = getDistance(P( 9 ), P( 10 ));
1738         double L10= getDistance(P( 10 ),P( 11 ));
1739         double L11= getDistance(P( 11 ),P( 12 ));
1740         double L12= getDistance(P( 12 ),P( 7 ));
1741
1742         double L13 = getDistance(P( 1 ),P( 7 ));
1743         double L14 = getDistance(P( 2 ),P( 8 ));
1744         double L15 = getDistance(P( 3 ),P( 9 ));
1745         double L16 = getDistance(P( 4 ),P( 10 ));
1746         double L17 = getDistance(P( 5 ),P( 11 ));
1747         double L18 = getDistance(P( 6 ),P( 12 ));
1748         aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1749         aVal = Min(aVal, Min(Min(Min(L7,L8),Min(L9,L10)),Min(L11,L12)));
1750         aVal = Min(aVal, Min(Min(Min(L13,L14),Min(L15,L16)),Min(L17,L18)));
1751       }
1752       break;
1753     case SMDSEntity_Polyhedra:
1754     {
1755     }
1756     break;
1757     default:
1758       return 0;
1759     }
1760
1761     if (aVal < 0 ) {
1762       return 0.;
1763     }
1764
1765     if ( myPrecision >= 0 )
1766     {
1767       double prec = pow( 10., (double)( myPrecision ) );
1768       aVal = floor( aVal * prec + 0.5 ) / prec;
1769     }
1770
1771     return aVal;
1772
1773   }
1774   return 0.;
1775 }
1776
1777 double Length2D::GetBadRate( double Value, int /*nbNodes*/ ) const
1778 {
1779   // meaningless as it is not a quality control functor
1780   return Value;
1781 }
1782
1783 SMDSAbs_ElementType Length2D::GetType() const
1784 {
1785   return SMDSAbs_Face;
1786 }
1787
1788 Length2D::Value::Value(double theLength,long thePntId1, long thePntId2):
1789   myLength(theLength)
1790 {
1791   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
1792   if(thePntId1 > thePntId2){
1793     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
1794   }
1795 }
1796
1797 bool Length2D::Value::operator<(const Length2D::Value& x) const
1798 {
1799   if(myPntId[0] < x.myPntId[0]) return true;
1800   if(myPntId[0] == x.myPntId[0])
1801     if(myPntId[1] < x.myPntId[1]) return true;
1802   return false;
1803 }
1804
1805 void Length2D::GetValues(TValues& theValues)
1806 {
1807   TValues aValues;
1808   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
1809   for(; anIter->more(); ){
1810     const SMDS_MeshFace* anElem = anIter->next();
1811
1812     if(anElem->IsQuadratic()) {
1813       const SMDS_VtkFace* F =
1814         dynamic_cast<const SMDS_VtkFace*>(anElem);
1815       // use special nodes iterator
1816       SMDS_ElemIteratorPtr anIter = F->interlacedNodesElemIterator();
1817       long aNodeId[4];
1818       gp_Pnt P[4];
1819
1820       double aLength;
1821       const SMDS_MeshElement* aNode;
1822       if(anIter->more()){
1823         aNode = anIter->next();
1824         const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
1825         P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
1826         aNodeId[0] = aNodeId[1] = aNode->GetID();
1827         aLength = 0;
1828       }
1829       for(; anIter->more(); ){
1830         const SMDS_MeshNode* N1 = static_cast<const SMDS_MeshNode*> (anIter->next());
1831         P[2] = gp_Pnt(N1->X(),N1->Y(),N1->Z());
1832         aNodeId[2] = N1->GetID();
1833         aLength = P[1].Distance(P[2]);
1834         if(!anIter->more()) break;
1835         const SMDS_MeshNode* N2 = static_cast<const SMDS_MeshNode*> (anIter->next());
1836         P[3] = gp_Pnt(N2->X(),N2->Y(),N2->Z());
1837         aNodeId[3] = N2->GetID();
1838         aLength += P[2].Distance(P[3]);
1839         Value aValue1(aLength,aNodeId[1],aNodeId[2]);
1840         Value aValue2(aLength,aNodeId[2],aNodeId[3]);
1841         P[1] = P[3];
1842         aNodeId[1] = aNodeId[3];
1843         theValues.insert(aValue1);
1844         theValues.insert(aValue2);
1845       }
1846       aLength += P[2].Distance(P[0]);
1847       Value aValue1(aLength,aNodeId[1],aNodeId[2]);
1848       Value aValue2(aLength,aNodeId[2],aNodeId[0]);
1849       theValues.insert(aValue1);
1850       theValues.insert(aValue2);
1851     }
1852     else {
1853       SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator();
1854       long aNodeId[2];
1855       gp_Pnt P[3];
1856
1857       double aLength;
1858       const SMDS_MeshElement* aNode;
1859       if(aNodesIter->more()){
1860         aNode = aNodesIter->next();
1861         const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
1862         P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
1863         aNodeId[0] = aNodeId[1] = aNode->GetID();
1864         aLength = 0;
1865       }
1866       for(; aNodesIter->more(); ){
1867         aNode = aNodesIter->next();
1868         const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
1869         long anId = aNode->GetID();
1870         
1871         P[2] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
1872         
1873         aLength = P[1].Distance(P[2]);
1874         
1875         Value aValue(aLength,aNodeId[1],anId);
1876         aNodeId[1] = anId;
1877         P[1] = P[2];
1878         theValues.insert(aValue);
1879       }
1880
1881       aLength = P[0].Distance(P[1]);
1882
1883       Value aValue(aLength,aNodeId[0],aNodeId[1]);
1884       theValues.insert(aValue);
1885     }
1886   }
1887 }
1888
1889 //================================================================================
1890 /*
1891   Class       : MultiConnection
1892   Description : Functor for calculating number of faces conneted to the edge
1893 */
1894 //================================================================================
1895
1896 double MultiConnection::GetValue( const TSequenceOfXYZ& P )
1897 {
1898   return 0;
1899 }
1900 double MultiConnection::GetValue( long theId )
1901 {
1902   return getNbMultiConnection( myMesh, theId );
1903 }
1904
1905 double MultiConnection::GetBadRate( double Value, int /*nbNodes*/ ) const
1906 {
1907   // meaningless as it is not quality control functor
1908   return Value;
1909 }
1910
1911 SMDSAbs_ElementType MultiConnection::GetType() const
1912 {
1913   return SMDSAbs_Edge;
1914 }
1915
1916 //================================================================================
1917 /*
1918   Class       : MultiConnection2D
1919   Description : Functor for calculating number of faces conneted to the edge
1920 */
1921 //================================================================================
1922
1923 double MultiConnection2D::GetValue( const TSequenceOfXYZ& P )
1924 {
1925   return 0;
1926 }
1927
1928 double MultiConnection2D::GetValue( long theElementId )
1929 {
1930   int aResult = 0;
1931
1932   const SMDS_MeshElement* aFaceElem = myMesh->FindElement(theElementId);
1933   SMDSAbs_ElementType aType = aFaceElem->GetType();
1934
1935   switch (aType) {
1936   case SMDSAbs_Face:
1937     {
1938       int i = 0, len = aFaceElem->NbNodes();
1939       SMDS_ElemIteratorPtr anIter = aFaceElem->nodesIterator();
1940       if (!anIter) break;
1941
1942       const SMDS_MeshNode *aNode, *aNode0;
1943       TColStd_MapOfInteger aMap, aMapPrev;
1944
1945       for (i = 0; i <= len; i++) {
1946         aMapPrev = aMap;
1947         aMap.Clear();
1948
1949         int aNb = 0;
1950         if (anIter->more()) {
1951           aNode = (SMDS_MeshNode*)anIter->next();
1952         } else {
1953           if (i == len)
1954             aNode = aNode0;
1955           else
1956             break;
1957         }
1958         if (!aNode) break;
1959         if (i == 0) aNode0 = aNode;
1960
1961         SMDS_ElemIteratorPtr anElemIter = aNode->GetInverseElementIterator();
1962         while (anElemIter->more()) {
1963           const SMDS_MeshElement* anElem = anElemIter->next();
1964           if (anElem != 0 && anElem->GetType() == SMDSAbs_Face) {
1965             int anId = anElem->GetID();
1966
1967             aMap.Add(anId);
1968             if (aMapPrev.Contains(anId)) {
1969               aNb++;
1970             }
1971           }
1972         }
1973         aResult = Max(aResult, aNb);
1974       }
1975     }
1976     break;
1977   default:
1978     aResult = 0;
1979   }
1980
1981   return aResult;
1982 }
1983
1984 double MultiConnection2D::GetBadRate( double Value, int /*nbNodes*/ ) const
1985 {
1986   // meaningless as it is not quality control functor
1987   return Value;
1988 }
1989
1990 SMDSAbs_ElementType MultiConnection2D::GetType() const
1991 {
1992   return SMDSAbs_Face;
1993 }
1994
1995 MultiConnection2D::Value::Value(long thePntId1, long thePntId2)
1996 {
1997   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
1998   if(thePntId1 > thePntId2){
1999     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
2000   }
2001 }
2002
2003 bool MultiConnection2D::Value::operator<(const MultiConnection2D::Value& x) const
2004 {
2005   if(myPntId[0] < x.myPntId[0]) return true;
2006   if(myPntId[0] == x.myPntId[0])
2007     if(myPntId[1] < x.myPntId[1]) return true;
2008   return false;
2009 }
2010
2011 void MultiConnection2D::GetValues(MValues& theValues)
2012 {
2013   if ( !myMesh ) return;
2014   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
2015   for(; anIter->more(); ){
2016     const SMDS_MeshFace* anElem = anIter->next();
2017     SMDS_ElemIteratorPtr aNodesIter;
2018     if ( anElem->IsQuadratic() )
2019       aNodesIter = dynamic_cast<const SMDS_VtkFace*>
2020         (anElem)->interlacedNodesElemIterator();
2021     else
2022       aNodesIter = anElem->nodesIterator();
2023     long aNodeId[3];
2024
2025     //int aNbConnects=0;
2026     const SMDS_MeshNode* aNode0;
2027     const SMDS_MeshNode* aNode1;
2028     const SMDS_MeshNode* aNode2;
2029     if(aNodesIter->more()){
2030       aNode0 = (SMDS_MeshNode*) aNodesIter->next();
2031       aNode1 = aNode0;
2032       const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode1;
2033       aNodeId[0] = aNodeId[1] = aNodes->GetID();
2034     }
2035     for(; aNodesIter->more(); ) {
2036       aNode2 = (SMDS_MeshNode*) aNodesIter->next();
2037       long anId = aNode2->GetID();
2038       aNodeId[2] = anId;
2039
2040       Value aValue(aNodeId[1],aNodeId[2]);
2041       MValues::iterator aItr = theValues.find(aValue);
2042       if (aItr != theValues.end()){
2043         aItr->second += 1;
2044         //aNbConnects = nb;
2045       }
2046       else {
2047         theValues[aValue] = 1;
2048         //aNbConnects = 1;
2049       }
2050       //cout << "NodeIds: "<<aNodeId[1]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl;
2051       aNodeId[1] = aNodeId[2];
2052       aNode1 = aNode2;
2053     }
2054     Value aValue(aNodeId[0],aNodeId[2]);
2055     MValues::iterator aItr = theValues.find(aValue);
2056     if (aItr != theValues.end()) {
2057       aItr->second += 1;
2058       //aNbConnects = nb;
2059     }
2060     else {
2061       theValues[aValue] = 1;
2062       //aNbConnects = 1;
2063     }
2064     //cout << "NodeIds: "<<aNodeId[0]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl;
2065   }
2066
2067 }
2068
2069 //================================================================================
2070 /*
2071   Class       : BallDiameter
2072   Description : Functor returning diameter of a ball element
2073 */
2074 //================================================================================
2075
2076 double BallDiameter::GetValue( long theId )
2077 {
2078   double diameter = 0;
2079
2080   if ( const SMDS_BallElement* ball =
2081        dynamic_cast<const SMDS_BallElement*>( myMesh->FindElement( theId )))
2082   {
2083     diameter = ball->GetDiameter();
2084   }
2085   return diameter;
2086 }
2087
2088 double BallDiameter::GetBadRate( double Value, int /*nbNodes*/ ) const
2089 {
2090   // meaningless as it is not a quality control functor
2091   return Value;
2092 }
2093
2094 SMDSAbs_ElementType BallDiameter::GetType() const
2095 {
2096   return SMDSAbs_Ball;
2097 }
2098
2099
2100 /*
2101                             PREDICATES
2102 */
2103
2104 //================================================================================
2105 /*
2106   Class       : BadOrientedVolume
2107   Description : Predicate bad oriented volumes
2108 */
2109 //================================================================================
2110
2111 BadOrientedVolume::BadOrientedVolume()
2112 {
2113   myMesh = 0;
2114 }
2115
2116 void BadOrientedVolume::SetMesh( const SMDS_Mesh* theMesh )
2117 {
2118   myMesh = theMesh;
2119 }
2120
2121 bool BadOrientedVolume::IsSatisfy( long theId )
2122 {
2123   if ( myMesh == 0 )
2124     return false;
2125
2126   SMDS_VolumeTool vTool( myMesh->FindElement( theId ));
2127   return !vTool.IsForward();
2128 }
2129
2130 SMDSAbs_ElementType BadOrientedVolume::GetType() const
2131 {
2132   return SMDSAbs_Volume;
2133 }
2134
2135 /*
2136   Class       : BareBorderVolume
2137 */
2138
2139 bool BareBorderVolume::IsSatisfy(long theElementId )
2140 {
2141   SMDS_VolumeTool  myTool;
2142   if ( myTool.Set( myMesh->FindElement(theElementId)))
2143   {
2144     for ( int iF = 0; iF < myTool.NbFaces(); ++iF )
2145       if ( myTool.IsFreeFace( iF ))
2146       {
2147         const SMDS_MeshNode** n = myTool.GetFaceNodes(iF);
2148         vector< const SMDS_MeshNode*> nodes( n, n+myTool.NbFaceNodes(iF));
2149         if ( !myMesh->FindElement( nodes, SMDSAbs_Face, /*Nomedium=*/false))
2150           return true;
2151       }
2152   }
2153   return false;
2154 }
2155
2156 //================================================================================
2157 /*
2158   Class       : BareBorderFace
2159 */
2160 //================================================================================
2161
2162 bool BareBorderFace::IsSatisfy(long theElementId )
2163 {
2164   bool ok = false;
2165   if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId))
2166   {
2167     if ( face->GetType() == SMDSAbs_Face )
2168     {
2169       int nbN = face->NbCornerNodes();
2170       for ( int i = 0; i < nbN && !ok; ++i )
2171       {
2172         // check if a link is shared by another face
2173         const SMDS_MeshNode* n1 = face->GetNode( i );
2174         const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN );
2175         SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face );
2176         bool isShared = false;
2177         while ( !isShared && fIt->more() )
2178         {
2179           const SMDS_MeshElement* f = fIt->next();
2180           isShared = ( f != face && f->GetNodeIndex(n2) != -1 );
2181         }
2182         if ( !isShared )
2183         {
2184           const int iQuad = face->IsQuadratic();
2185           myLinkNodes.resize( 2 + iQuad);
2186           myLinkNodes[0] = n1;
2187           myLinkNodes[1] = n2;
2188           if ( iQuad )
2189             myLinkNodes[2] = face->GetNode( i+nbN );
2190           ok = !myMesh->FindElement( myLinkNodes, SMDSAbs_Edge, /*noMedium=*/false);
2191         }
2192       }
2193     }
2194   }
2195   return ok;
2196 }
2197
2198 //================================================================================
2199 /*
2200   Class       : OverConstrainedVolume
2201 */
2202 //================================================================================
2203
2204 bool OverConstrainedVolume::IsSatisfy(long theElementId )
2205 {
2206   // An element is over-constrained if it has N-1 free borders where
2207   // N is the number of edges/faces for a 2D/3D element.
2208   SMDS_VolumeTool  myTool;
2209   if ( myTool.Set( myMesh->FindElement(theElementId)))
2210   {
2211     int nbSharedFaces = 0;
2212     for ( int iF = 0; iF < myTool.NbFaces(); ++iF )
2213       if ( !myTool.IsFreeFace( iF ) && ++nbSharedFaces > 1 )
2214         break;
2215     return ( nbSharedFaces == 1 );
2216   }
2217   return false;
2218 }
2219
2220 //================================================================================
2221 /*
2222   Class       : OverConstrainedFace
2223 */
2224 //================================================================================
2225
2226 bool OverConstrainedFace::IsSatisfy(long theElementId )
2227 {
2228   // An element is over-constrained if it has N-1 free borders where
2229   // N is the number of edges/faces for a 2D/3D element.
2230   if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId))
2231     if ( face->GetType() == SMDSAbs_Face )
2232     {
2233       int nbSharedBorders = 0;
2234       int nbN = face->NbCornerNodes();
2235       for ( int i = 0; i < nbN; ++i )
2236       {
2237         // check if a link is shared by another face
2238         const SMDS_MeshNode* n1 = face->GetNode( i );
2239         const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN );
2240         SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face );
2241         bool isShared = false;
2242         while ( !isShared && fIt->more() )
2243         {
2244           const SMDS_MeshElement* f = fIt->next();
2245           isShared = ( f != face && f->GetNodeIndex(n2) != -1 );
2246         }
2247         if ( isShared && ++nbSharedBorders > 1 )
2248           break;
2249       }
2250       return ( nbSharedBorders == 1 );
2251     }
2252   return false;
2253 }
2254
2255 //================================================================================
2256 /*
2257   Class       : CoincidentNodes
2258   Description : Predicate of Coincident nodes
2259 */
2260 //================================================================================
2261
2262 CoincidentNodes::CoincidentNodes()
2263 {
2264   myToler = 1e-5;
2265 }
2266
2267 bool CoincidentNodes::IsSatisfy( long theElementId )
2268 {
2269   return myCoincidentIDs.Contains( theElementId );
2270 }
2271
2272 SMDSAbs_ElementType CoincidentNodes::GetType() const
2273 {
2274   return SMDSAbs_Node;
2275 }
2276
2277 void CoincidentNodes::SetMesh( const SMDS_Mesh* theMesh )
2278 {
2279   myMeshModifTracer.SetMesh( theMesh );
2280   if ( myMeshModifTracer.IsMeshModified() )
2281   {
2282     TIDSortedNodeSet nodesToCheck;
2283     SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
2284     while ( nIt->more() )
2285       nodesToCheck.insert( nodesToCheck.end(), nIt->next() );
2286
2287     list< list< const SMDS_MeshNode*> > nodeGroups;
2288     SMESH_OctreeNode::FindCoincidentNodes ( nodesToCheck, &nodeGroups, myToler );
2289
2290     myCoincidentIDs.Clear();
2291     list< list< const SMDS_MeshNode*> >::iterator groupIt = nodeGroups.begin();
2292     for ( ; groupIt != nodeGroups.end(); ++groupIt )
2293     {
2294       list< const SMDS_MeshNode*>& coincNodes = *groupIt;
2295       list< const SMDS_MeshNode*>::iterator n = coincNodes.begin();
2296       for ( ; n != coincNodes.end(); ++n )
2297         myCoincidentIDs.Add( (*n)->GetID() );
2298     }
2299   }
2300 }
2301
2302 //================================================================================
2303 /*
2304   Class       : CoincidentElements
2305   Description : Predicate of Coincident Elements
2306   Note        : This class is suitable only for visualization of Coincident Elements
2307 */
2308 //================================================================================
2309
2310 CoincidentElements::CoincidentElements()
2311 {
2312   myMesh = 0;
2313 }
2314
2315 void CoincidentElements::SetMesh( const SMDS_Mesh* theMesh )
2316 {
2317   myMesh = theMesh;
2318 }
2319
2320 bool CoincidentElements::IsSatisfy( long theElementId )
2321 {
2322   if ( !myMesh ) return false;
2323
2324   if ( const SMDS_MeshElement* e = myMesh->FindElement( theElementId ))
2325   {
2326     if ( e->GetType() != GetType() ) return false;
2327     set< const SMDS_MeshNode* > elemNodes( e->begin_nodes(), e->end_nodes() );
2328     const int nbNodes = e->NbNodes();
2329     SMDS_ElemIteratorPtr invIt = (*elemNodes.begin())->GetInverseElementIterator( GetType() );
2330     while ( invIt->more() )
2331     {
2332       const SMDS_MeshElement* e2 = invIt->next();
2333       if ( e2 == e || e2->NbNodes() != nbNodes ) continue;
2334
2335       bool sameNodes = true;
2336       for ( size_t i = 0; i < elemNodes.size() && sameNodes; ++i )
2337         sameNodes = ( elemNodes.count( e2->GetNode( i )));
2338       if ( sameNodes )
2339         return true;
2340     }
2341   }
2342   return false;
2343 }
2344
2345 SMDSAbs_ElementType CoincidentElements1D::GetType() const
2346 {
2347   return SMDSAbs_Edge;
2348 }
2349 SMDSAbs_ElementType CoincidentElements2D::GetType() const
2350 {
2351   return SMDSAbs_Face;
2352 }
2353 SMDSAbs_ElementType CoincidentElements3D::GetType() const
2354 {
2355   return SMDSAbs_Volume;
2356 }
2357
2358
2359 //================================================================================
2360 /*
2361   Class       : FreeBorders
2362   Description : Predicate for free borders
2363 */
2364 //================================================================================
2365
2366 FreeBorders::FreeBorders()
2367 {
2368   myMesh = 0;
2369 }
2370
2371 void FreeBorders::SetMesh( const SMDS_Mesh* theMesh )
2372 {
2373   myMesh = theMesh;
2374 }
2375
2376 bool FreeBorders::IsSatisfy( long theId )
2377 {
2378   return getNbMultiConnection( myMesh, theId ) == 1;
2379 }
2380
2381 SMDSAbs_ElementType FreeBorders::GetType() const
2382 {
2383   return SMDSAbs_Edge;
2384 }
2385
2386
2387 //================================================================================
2388 /*
2389   Class       : FreeEdges
2390   Description : Predicate for free Edges
2391 */
2392 //================================================================================
2393
2394 FreeEdges::FreeEdges()
2395 {
2396   myMesh = 0;
2397 }
2398
2399 void FreeEdges::SetMesh( const SMDS_Mesh* theMesh )
2400 {
2401   myMesh = theMesh;
2402 }
2403
2404 bool FreeEdges::IsFreeEdge( const SMDS_MeshNode** theNodes, const int theFaceId  )
2405 {
2406   TColStd_MapOfInteger aMap;
2407   for ( int i = 0; i < 2; i++ )
2408   {
2409     SMDS_ElemIteratorPtr anElemIter = theNodes[ i ]->GetInverseElementIterator(SMDSAbs_Face);
2410     while( anElemIter->more() )
2411     {
2412       if ( const SMDS_MeshElement* anElem = anElemIter->next())
2413       {
2414         const int anId = anElem->GetID();
2415         if ( anId != theFaceId && !aMap.Add( anId ))
2416           return false;
2417       }
2418     }
2419   }
2420   return true;
2421 }
2422
2423 bool FreeEdges::IsSatisfy( long theId )
2424 {
2425   if ( myMesh == 0 )
2426     return false;
2427
2428   const SMDS_MeshElement* aFace = myMesh->FindElement( theId );
2429   if ( aFace == 0 || aFace->GetType() != SMDSAbs_Face || aFace->NbNodes() < 3 )
2430     return false;
2431
2432   SMDS_NodeIteratorPtr anIter = aFace->interlacedNodesIterator();
2433   if ( !anIter )
2434     return false;
2435
2436   int i = 0, nbNodes = aFace->NbNodes();
2437   std::vector <const SMDS_MeshNode*> aNodes( nbNodes+1 );
2438   while( anIter->more() )
2439     if ( ! ( aNodes[ i++ ] = anIter->next() ))
2440       return false;
2441   aNodes[ nbNodes ] = aNodes[ 0 ];
2442
2443   for ( i = 0; i < nbNodes; i++ )
2444     if ( IsFreeEdge( &aNodes[ i ], theId ) )
2445       return true;
2446
2447   return false;
2448 }
2449
2450 SMDSAbs_ElementType FreeEdges::GetType() const
2451 {
2452   return SMDSAbs_Face;
2453 }
2454
2455 FreeEdges::Border::Border(long theElemId, long thePntId1, long thePntId2):
2456   myElemId(theElemId)
2457 {
2458   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
2459   if(thePntId1 > thePntId2){
2460     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
2461   }
2462 }
2463
2464 bool FreeEdges::Border::operator<(const FreeEdges::Border& x) const{
2465   if(myPntId[0] < x.myPntId[0]) return true;
2466   if(myPntId[0] == x.myPntId[0])
2467     if(myPntId[1] < x.myPntId[1]) return true;
2468   return false;
2469 }
2470
2471 inline void UpdateBorders(const FreeEdges::Border& theBorder,
2472                           FreeEdges::TBorders& theRegistry,
2473                           FreeEdges::TBorders& theContainer)
2474 {
2475   if(theRegistry.find(theBorder) == theRegistry.end()){
2476     theRegistry.insert(theBorder);
2477     theContainer.insert(theBorder);
2478   }else{
2479     theContainer.erase(theBorder);
2480   }
2481 }
2482
2483 void FreeEdges::GetBoreders(TBorders& theBorders)
2484 {
2485   TBorders aRegistry;
2486   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
2487   for(; anIter->more(); ){
2488     const SMDS_MeshFace* anElem = anIter->next();
2489     long anElemId = anElem->GetID();
2490     SMDS_ElemIteratorPtr aNodesIter;
2491     if ( anElem->IsQuadratic() )
2492       aNodesIter = static_cast<const SMDS_VtkFace*>(anElem)->
2493         interlacedNodesElemIterator();
2494     else
2495       aNodesIter = anElem->nodesIterator();
2496     long aNodeId[2];
2497     const SMDS_MeshElement* aNode;
2498     if(aNodesIter->more()){
2499       aNode = aNodesIter->next();
2500       aNodeId[0] = aNodeId[1] = aNode->GetID();
2501     }
2502     for(; aNodesIter->more(); ){
2503       aNode = aNodesIter->next();
2504       long anId = aNode->GetID();
2505       Border aBorder(anElemId,aNodeId[1],anId);
2506       aNodeId[1] = anId;
2507       UpdateBorders(aBorder,aRegistry,theBorders);
2508     }
2509     Border aBorder(anElemId,aNodeId[0],aNodeId[1]);
2510     UpdateBorders(aBorder,aRegistry,theBorders);
2511   }
2512 }
2513
2514 //================================================================================
2515 /*
2516   Class       : FreeNodes
2517   Description : Predicate for free nodes
2518 */
2519 //================================================================================
2520
2521 FreeNodes::FreeNodes()
2522 {
2523   myMesh = 0;
2524 }
2525
2526 void FreeNodes::SetMesh( const SMDS_Mesh* theMesh )
2527 {
2528   myMesh = theMesh;
2529 }
2530
2531 bool FreeNodes::IsSatisfy( long theNodeId )
2532 {
2533   const SMDS_MeshNode* aNode = myMesh->FindNode( theNodeId );
2534   if (!aNode)
2535     return false;
2536
2537   return (aNode->NbInverseElements() < 1);
2538 }
2539
2540 SMDSAbs_ElementType FreeNodes::GetType() const
2541 {
2542   return SMDSAbs_Node;
2543 }
2544
2545
2546 //================================================================================
2547 /*
2548   Class       : FreeFaces
2549   Description : Predicate for free faces
2550 */
2551 //================================================================================
2552
2553 FreeFaces::FreeFaces()
2554 {
2555   myMesh = 0;
2556 }
2557
2558 void FreeFaces::SetMesh( const SMDS_Mesh* theMesh )
2559 {
2560   myMesh = theMesh;
2561 }
2562
2563 bool FreeFaces::IsSatisfy( long theId )
2564 {
2565   if (!myMesh) return false;
2566   // check that faces nodes refers to less than two common volumes
2567   const SMDS_MeshElement* aFace = myMesh->FindElement( theId );
2568   if ( !aFace || aFace->GetType() != SMDSAbs_Face )
2569     return false;
2570
2571   int nbNode = aFace->NbNodes();
2572
2573   // collect volumes to check that number of volumes with count equal nbNode not less than 2
2574   typedef map< SMDS_MeshElement*, int > TMapOfVolume; // map of volume counters
2575   typedef map< SMDS_MeshElement*, int >::iterator TItrMapOfVolume; // iterator
2576   TMapOfVolume mapOfVol;
2577
2578   SMDS_ElemIteratorPtr nodeItr = aFace->nodesIterator();
2579   while ( nodeItr->more() ) {
2580     const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(nodeItr->next());
2581     if ( !aNode ) continue;
2582     SMDS_ElemIteratorPtr volItr = aNode->GetInverseElementIterator(SMDSAbs_Volume);
2583     while ( volItr->more() ) {
2584       SMDS_MeshElement* aVol = (SMDS_MeshElement*)volItr->next();
2585       TItrMapOfVolume itr = mapOfVol.insert(make_pair(aVol, 0)).first;
2586       (*itr).second++;
2587     } 
2588   }
2589   int nbVol = 0;
2590   TItrMapOfVolume volItr = mapOfVol.begin();
2591   TItrMapOfVolume volEnd = mapOfVol.end();
2592   for ( ; volItr != volEnd; ++volItr )
2593     if ( (*volItr).second >= nbNode )
2594        nbVol++;
2595   // face is not free if number of volumes constructed on thier nodes more than one
2596   return (nbVol < 2);
2597 }
2598
2599 SMDSAbs_ElementType FreeFaces::GetType() const
2600 {
2601   return SMDSAbs_Face;
2602 }
2603
2604 //================================================================================
2605 /*
2606   Class       : LinearOrQuadratic
2607   Description : Predicate to verify whether a mesh element is linear
2608 */
2609 //================================================================================
2610
2611 LinearOrQuadratic::LinearOrQuadratic()
2612 {
2613   myMesh = 0;
2614 }
2615
2616 void LinearOrQuadratic::SetMesh( const SMDS_Mesh* theMesh )
2617 {
2618   myMesh = theMesh;
2619 }
2620
2621 bool LinearOrQuadratic::IsSatisfy( long theId )
2622 {
2623   if (!myMesh) return false;
2624   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
2625   if ( !anElem || (myType != SMDSAbs_All && anElem->GetType() != myType) )
2626     return false;
2627   return (!anElem->IsQuadratic());
2628 }
2629
2630 void LinearOrQuadratic::SetType( SMDSAbs_ElementType theType )
2631 {
2632   myType = theType;
2633 }
2634
2635 SMDSAbs_ElementType LinearOrQuadratic::GetType() const
2636 {
2637   return myType;
2638 }
2639
2640 //================================================================================
2641 /*
2642   Class       : GroupColor
2643   Description : Functor for check color of group to whic mesh element belongs to
2644 */
2645 //================================================================================
2646
2647 GroupColor::GroupColor()
2648 {
2649 }
2650
2651 bool GroupColor::IsSatisfy( long theId )
2652 {
2653   return (myIDs.find( theId ) != myIDs.end());
2654 }
2655
2656 void GroupColor::SetType( SMDSAbs_ElementType theType )
2657 {
2658   myType = theType;
2659 }
2660
2661 SMDSAbs_ElementType GroupColor::GetType() const
2662 {
2663   return myType;
2664 }
2665
2666 static bool isEqual( const Quantity_Color& theColor1,
2667                      const Quantity_Color& theColor2 )
2668 {
2669   // tolerance to compare colors
2670   const double tol = 5*1e-3;
2671   return ( fabs( theColor1.Red()   - theColor2.Red() )   < tol &&
2672            fabs( theColor1.Green() - theColor2.Green() ) < tol &&
2673            fabs( theColor1.Blue()  - theColor2.Blue() )  < tol );
2674 }
2675
2676 void GroupColor::SetMesh( const SMDS_Mesh* theMesh )
2677 {
2678   myIDs.clear();
2679   
2680   const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh);
2681   if ( !aMesh )
2682     return;
2683
2684   int nbGrp = aMesh->GetNbGroups();
2685   if ( !nbGrp )
2686     return;
2687   
2688   // iterates on groups and find necessary elements ids
2689   const std::set<SMESHDS_GroupBase*>& aGroups = aMesh->GetGroups();
2690   set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin();
2691   for (; GrIt != aGroups.end(); GrIt++) {
2692     SMESHDS_GroupBase* aGrp = (*GrIt);
2693     if ( !aGrp )
2694       continue;
2695     // check type and color of group
2696     if ( !isEqual( myColor, aGrp->GetColor() ) )
2697       continue;
2698     if ( myType != SMDSAbs_All && myType != (SMDSAbs_ElementType)aGrp->GetType() )
2699       continue;
2700
2701     SMDSAbs_ElementType aGrpElType = (SMDSAbs_ElementType)aGrp->GetType();
2702     if ( myType == aGrpElType || (myType == SMDSAbs_All && aGrpElType != SMDSAbs_Node) ) {
2703       // add elements IDS into control
2704       int aSize = aGrp->Extent();
2705       for (int i = 0; i < aSize; i++)
2706         myIDs.insert( aGrp->GetID(i+1) );
2707     }
2708   }
2709 }
2710
2711 void GroupColor::SetColorStr( const TCollection_AsciiString& theStr )
2712 {
2713   Kernel_Utils::Localizer loc;
2714   TCollection_AsciiString aStr = theStr;
2715   aStr.RemoveAll( ' ' );
2716   aStr.RemoveAll( '\t' );
2717   for ( int aPos = aStr.Search( ";;" ); aPos != -1; aPos = aStr.Search( ";;" ) )
2718     aStr.Remove( aPos, 2 );
2719   Standard_Real clr[3];
2720   clr[0] = clr[1] = clr[2] = 0.;
2721   for ( int i = 0; i < 3; i++ ) {
2722     TCollection_AsciiString tmpStr = aStr.Token( ";", i+1 );
2723     if ( !tmpStr.IsEmpty() && tmpStr.IsRealValue() )
2724       clr[i] = tmpStr.RealValue();
2725   }
2726   myColor = Quantity_Color( clr[0], clr[1], clr[2], Quantity_TOC_RGB );
2727 }
2728
2729 //=======================================================================
2730 // name    : GetRangeStr
2731 // Purpose : Get range as a string.
2732 //           Example: "1,2,3,50-60,63,67,70-"
2733 //=======================================================================
2734
2735 void GroupColor::GetColorStr( TCollection_AsciiString& theResStr ) const
2736 {
2737   theResStr.Clear();
2738   theResStr += TCollection_AsciiString( myColor.Red() );
2739   theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Green() );
2740   theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Blue() );
2741 }
2742
2743 //================================================================================
2744 /*
2745   Class       : ElemGeomType
2746   Description : Predicate to check element geometry type
2747 */
2748 //================================================================================
2749
2750 ElemGeomType::ElemGeomType()
2751 {
2752   myMesh = 0;
2753   myType = SMDSAbs_All;
2754   myGeomType = SMDSGeom_TRIANGLE;
2755 }
2756
2757 void ElemGeomType::SetMesh( const SMDS_Mesh* theMesh )
2758 {
2759   myMesh = theMesh;
2760 }
2761
2762 bool ElemGeomType::IsSatisfy( long theId )
2763 {
2764   if (!myMesh) return false;
2765   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
2766   if ( !anElem )
2767     return false;
2768   const SMDSAbs_ElementType anElemType = anElem->GetType();
2769   if ( myType != SMDSAbs_All && anElemType != myType )
2770     return false;
2771   bool isOk = ( anElem->GetGeomType() == myGeomType );
2772   return isOk;
2773 }
2774
2775 void ElemGeomType::SetType( SMDSAbs_ElementType theType )
2776 {
2777   myType = theType;
2778 }
2779
2780 SMDSAbs_ElementType ElemGeomType::GetType() const
2781 {
2782   return myType;
2783 }
2784
2785 void ElemGeomType::SetGeomType( SMDSAbs_GeometryType theType )
2786 {
2787   myGeomType = theType;
2788 }
2789
2790 SMDSAbs_GeometryType ElemGeomType::GetGeomType() const
2791 {
2792   return myGeomType;
2793 }
2794
2795 //================================================================================
2796 /*
2797   Class       : ElemEntityType
2798   Description : Predicate to check element entity type
2799 */
2800 //================================================================================
2801
2802 ElemEntityType::ElemEntityType():
2803   myMesh( 0 ),
2804   myType( SMDSAbs_All ),
2805   myEntityType( SMDSEntity_0D )
2806 {
2807 }
2808
2809 void ElemEntityType::SetMesh( const SMDS_Mesh* theMesh )
2810 {
2811   myMesh = theMesh;
2812 }
2813
2814 bool ElemEntityType::IsSatisfy( long theId )
2815 {
2816   if ( !myMesh ) return false;
2817   if ( myType == SMDSAbs_Node )
2818     return myMesh->FindNode( theId );
2819   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
2820   return ( anElem &&
2821            myEntityType == anElem->GetEntityType() );
2822 }
2823
2824 void ElemEntityType::SetType( SMDSAbs_ElementType theType )
2825 {
2826   myType = theType;
2827 }
2828
2829 SMDSAbs_ElementType ElemEntityType::GetType() const
2830 {
2831   return myType;
2832 }
2833
2834 void ElemEntityType::SetElemEntityType( SMDSAbs_EntityType theEntityType )
2835 {
2836   myEntityType = theEntityType;
2837 }
2838
2839 SMDSAbs_EntityType ElemEntityType::GetElemEntityType() const
2840 {
2841   return myEntityType;
2842 }
2843
2844 //================================================================================
2845 /*!
2846  * \brief Class ConnectedElements
2847  */
2848 //================================================================================
2849
2850 ConnectedElements::ConnectedElements():
2851   myNodeID(0), myType( SMDSAbs_All ), myOkIDsReady( false ) {}
2852
2853 SMDSAbs_ElementType ConnectedElements::GetType() const
2854 { return myType; }
2855
2856 int ConnectedElements::GetNode() const
2857 { return myXYZ.empty() ? myNodeID : 0; } // myNodeID can be found by myXYZ
2858
2859 std::vector<double> ConnectedElements::GetPoint() const
2860 { return myXYZ; }
2861
2862 void ConnectedElements::clearOkIDs()
2863 { myOkIDsReady = false; myOkIDs.clear(); }
2864
2865 void ConnectedElements::SetType( SMDSAbs_ElementType theType )
2866 {
2867   if ( myType != theType || myMeshModifTracer.IsMeshModified() )
2868     clearOkIDs();
2869   myType = theType;
2870 }
2871
2872 void ConnectedElements::SetMesh( const SMDS_Mesh* theMesh )
2873 {
2874   myMeshModifTracer.SetMesh( theMesh );
2875   if ( myMeshModifTracer.IsMeshModified() )
2876   {
2877     clearOkIDs();
2878     if ( !myXYZ.empty() )
2879       SetPoint( myXYZ[0], myXYZ[1], myXYZ[2] ); // find a node near myXYZ it in a new mesh
2880   }
2881 }
2882
2883 void ConnectedElements::SetNode( int nodeID )
2884 {
2885   myNodeID = nodeID;
2886   myXYZ.clear();
2887
2888   bool isSameDomain = false;
2889   if ( myOkIDsReady && myMeshModifTracer.GetMesh() && !myMeshModifTracer.IsMeshModified() )
2890     if ( const SMDS_MeshNode* n = myMeshModifTracer.GetMesh()->FindNode( myNodeID ))
2891     {
2892       SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator( myType );
2893       while ( !isSameDomain && eIt->more() )
2894         isSameDomain = IsSatisfy( eIt->next()->GetID() );
2895     }
2896   if ( !isSameDomain )
2897     clearOkIDs();
2898 }
2899
2900 void ConnectedElements::SetPoint( double x, double y, double z )
2901 {
2902   myXYZ.resize(3);
2903   myXYZ[0] = x;
2904   myXYZ[1] = y;
2905   myXYZ[2] = z;
2906   myNodeID = 0;
2907
2908   bool isSameDomain = false;
2909
2910   // find myNodeID by myXYZ if possible
2911   if ( myMeshModifTracer.GetMesh() )
2912   {
2913     auto_ptr<SMESH_ElementSearcher> searcher
2914       ( SMESH_MeshAlgos::GetElementSearcher( (SMDS_Mesh&) *myMeshModifTracer.GetMesh() ));
2915
2916     vector< const SMDS_MeshElement* > foundElems;
2917     searcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_All, foundElems );
2918
2919     if ( !foundElems.empty() )
2920     {
2921       myNodeID = foundElems[0]->GetNode(0)->GetID();
2922       if ( myOkIDsReady && !myMeshModifTracer.IsMeshModified() )
2923         isSameDomain = IsSatisfy( foundElems[0]->GetID() );
2924     }
2925   }
2926   if ( !isSameDomain )
2927     clearOkIDs();
2928 }
2929
2930 bool ConnectedElements::IsSatisfy( long theElementId )
2931 {
2932   // Here we do NOT check if the mesh has changed, we do it in Set...() only!!!
2933
2934   if ( !myOkIDsReady )
2935   {
2936     if ( !myMeshModifTracer.GetMesh() )
2937       return false;
2938     const SMDS_MeshNode* node0 = myMeshModifTracer.GetMesh()->FindNode( myNodeID );
2939     if ( !node0 )
2940       return false;
2941
2942     list< const SMDS_MeshNode* > nodeQueue( 1, node0 );
2943     std::set< int > checkedNodeIDs;
2944     // algo:
2945     // foreach node in nodeQueue:
2946     //   foreach element sharing a node:
2947     //     add ID of an element of myType to myOkIDs;
2948     //     push all element nodes absent from checkedNodeIDs to nodeQueue;
2949     while ( !nodeQueue.empty() )
2950     {
2951       const SMDS_MeshNode* node = nodeQueue.front();
2952       nodeQueue.pop_front();
2953
2954       // loop on elements sharing the node
2955       SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
2956       while ( eIt->more() )
2957       {
2958         // keep elements of myType
2959         const SMDS_MeshElement* element = eIt->next();
2960         if ( element->GetType() == myType )
2961           myOkIDs.insert( myOkIDs.end(), element->GetID() );
2962
2963         // enqueue nodes of the element
2964         SMDS_ElemIteratorPtr nIt = element->nodesIterator();
2965         while ( nIt->more() )
2966         {
2967           const SMDS_MeshNode* n = static_cast< const SMDS_MeshNode* >( nIt->next() );
2968           if ( checkedNodeIDs.insert( n->GetID() ).second )
2969             nodeQueue.push_back( n );
2970         }
2971       }
2972     }
2973     if ( myType == SMDSAbs_Node )
2974       std::swap( myOkIDs, checkedNodeIDs );
2975
2976     size_t totalNbElems = myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType );
2977     if ( myOkIDs.size() == totalNbElems )
2978       myOkIDs.clear();
2979
2980     myOkIDsReady = true;
2981   }
2982
2983   return myOkIDs.empty() ? true : myOkIDs.count( theElementId );
2984 }
2985
2986 //================================================================================
2987 /*!
2988  * \brief Class CoplanarFaces
2989  */
2990 //================================================================================
2991
2992 CoplanarFaces::CoplanarFaces()
2993   : myFaceID(0), myToler(0)
2994 {
2995 }
2996 void CoplanarFaces::SetMesh( const SMDS_Mesh* theMesh )
2997 {
2998   myMeshModifTracer.SetMesh( theMesh );
2999   if ( myMeshModifTracer.IsMeshModified() )
3000   {
3001     // Build a set of coplanar face ids
3002
3003     myCoplanarIDs.clear();
3004
3005     if ( !myMeshModifTracer.GetMesh() || !myFaceID || !myToler )
3006       return;
3007
3008     const SMDS_MeshElement* face = myMeshModifTracer.GetMesh()->FindElement( myFaceID );
3009     if ( !face || face->GetType() != SMDSAbs_Face )
3010       return;
3011
3012     bool normOK;
3013     gp_Vec myNorm = getNormale( static_cast<const SMDS_MeshFace*>(face), &normOK );
3014     if (!normOK)
3015       return;
3016
3017     const double radianTol = myToler * M_PI / 180.;
3018     std::set< SMESH_TLink > checkedLinks;
3019
3020     std::list< pair< const SMDS_MeshElement*, gp_Vec > > faceQueue;
3021     faceQueue.push_back( make_pair( face, myNorm ));
3022     while ( !faceQueue.empty() )
3023     {
3024       face   = faceQueue.front().first;
3025       myNorm = faceQueue.front().second;
3026       faceQueue.pop_front();
3027
3028       for ( int i = 0, nbN = face->NbCornerNodes(); i < nbN; ++i )
3029       {
3030         const SMDS_MeshNode*  n1 = face->GetNode( i );
3031         const SMDS_MeshNode*  n2 = face->GetNode(( i+1 )%nbN);
3032         if ( !checkedLinks.insert( SMESH_TLink( n1, n2 )).second )
3033           continue;
3034         SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator(SMDSAbs_Face);
3035         while ( fIt->more() )
3036         {
3037           const SMDS_MeshElement* f = fIt->next();
3038           if ( f->GetNodeIndex( n2 ) > -1 )
3039           {
3040             gp_Vec norm = getNormale( static_cast<const SMDS_MeshFace*>(f), &normOK );
3041             if (!normOK || myNorm.Angle( norm ) <= radianTol)
3042             {
3043               myCoplanarIDs.insert( f->GetID() );
3044               faceQueue.push_back( make_pair( f, norm ));
3045             }
3046           }
3047         }
3048       }
3049     }
3050   }
3051 }
3052 bool CoplanarFaces::IsSatisfy( long theElementId )
3053 {
3054   return myCoplanarIDs.count( theElementId );
3055 }
3056
3057 /*
3058  *Class       : RangeOfIds
3059   *Description : Predicate for Range of Ids.
3060   *              Range may be specified with two ways.
3061   *              1. Using AddToRange method
3062   *              2. With SetRangeStr method. Parameter of this method is a string
3063   *                 like as "1,2,3,50-60,63,67,70-"
3064 */
3065
3066 //=======================================================================
3067 // name    : RangeOfIds
3068 // Purpose : Constructor
3069 //=======================================================================
3070 RangeOfIds::RangeOfIds()
3071 {
3072   myMesh = 0;
3073   myType = SMDSAbs_All;
3074 }
3075
3076 //=======================================================================
3077 // name    : SetMesh
3078 // Purpose : Set mesh
3079 //=======================================================================
3080 void RangeOfIds::SetMesh( const SMDS_Mesh* theMesh )
3081 {
3082   myMesh = theMesh;
3083 }
3084
3085 //=======================================================================
3086 // name    : AddToRange
3087 // Purpose : Add ID to the range
3088 //=======================================================================
3089 bool RangeOfIds::AddToRange( long theEntityId )
3090 {
3091   myIds.Add( theEntityId );
3092   return true;
3093 }
3094
3095 //=======================================================================
3096 // name    : GetRangeStr
3097 // Purpose : Get range as a string.
3098 //           Example: "1,2,3,50-60,63,67,70-"
3099 //=======================================================================
3100 void RangeOfIds::GetRangeStr( TCollection_AsciiString& theResStr )
3101 {
3102   theResStr.Clear();
3103
3104   TColStd_SequenceOfInteger     anIntSeq;
3105   TColStd_SequenceOfAsciiString aStrSeq;
3106
3107   TColStd_MapIteratorOfMapOfInteger anIter( myIds );
3108   for ( ; anIter.More(); anIter.Next() )
3109   {
3110     int anId = anIter.Key();
3111     TCollection_AsciiString aStr( anId );
3112     anIntSeq.Append( anId );
3113     aStrSeq.Append( aStr );
3114   }
3115
3116   for ( int i = 1, n = myMin.Length(); i <= n; i++ )
3117   {
3118     int aMinId = myMin( i );
3119     int aMaxId = myMax( i );
3120
3121     TCollection_AsciiString aStr;
3122     if ( aMinId != IntegerFirst() )
3123       aStr += aMinId;
3124
3125     aStr += "-";
3126
3127     if ( aMaxId != IntegerLast() )
3128       aStr += aMaxId;
3129
3130     // find position of the string in result sequence and insert string in it
3131     if ( anIntSeq.Length() == 0 )
3132     {
3133       anIntSeq.Append( aMinId );
3134       aStrSeq.Append( aStr );
3135     }
3136     else
3137     {
3138       if ( aMinId < anIntSeq.First() )
3139       {
3140         anIntSeq.Prepend( aMinId );
3141         aStrSeq.Prepend( aStr );
3142       }
3143       else if ( aMinId > anIntSeq.Last() )
3144       {
3145         anIntSeq.Append( aMinId );
3146         aStrSeq.Append( aStr );
3147       }
3148       else
3149         for ( int j = 1, k = anIntSeq.Length(); j <= k; j++ )
3150           if ( aMinId < anIntSeq( j ) )
3151           {
3152             anIntSeq.InsertBefore( j, aMinId );
3153             aStrSeq.InsertBefore( j, aStr );
3154             break;
3155           }
3156     }
3157   }
3158
3159   if ( aStrSeq.Length() == 0 )
3160     return;
3161
3162   theResStr = aStrSeq( 1 );
3163   for ( int j = 2, k = aStrSeq.Length(); j <= k; j++  )
3164   {
3165     theResStr += ",";
3166     theResStr += aStrSeq( j );
3167   }
3168 }
3169
3170 //=======================================================================
3171 // name    : SetRangeStr
3172 // Purpose : Define range with string
3173 //           Example of entry string: "1,2,3,50-60,63,67,70-"
3174 //=======================================================================
3175 bool RangeOfIds::SetRangeStr( const TCollection_AsciiString& theStr )
3176 {
3177   myMin.Clear();
3178   myMax.Clear();
3179   myIds.Clear();
3180
3181   TCollection_AsciiString aStr = theStr;
3182   //aStr.RemoveAll( ' ' );
3183   //aStr.RemoveAll( '\t' );
3184   for ( int i = 1; i <= aStr.Length(); ++i )
3185     if ( isspace( aStr.Value( i )))
3186       aStr.SetValue( i, ',');
3187
3188   for ( int aPos = aStr.Search( ",," ); aPos != -1; aPos = aStr.Search( ",," ) )
3189     aStr.Remove( aPos, 1 );
3190
3191   TCollection_AsciiString tmpStr = aStr.Token( ",", 1 );
3192   int i = 1;
3193   while ( tmpStr != "" )
3194   {
3195     tmpStr = aStr.Token( ",", i++ );
3196     int aPos = tmpStr.Search( '-' );
3197
3198     if ( aPos == -1 )
3199     {
3200       if ( tmpStr.IsIntegerValue() )
3201         myIds.Add( tmpStr.IntegerValue() );
3202       else
3203         return false;
3204     }
3205     else
3206     {
3207       TCollection_AsciiString aMaxStr = tmpStr.Split( aPos );
3208       TCollection_AsciiString aMinStr = tmpStr;
3209
3210       while ( aMinStr.Search( "-" ) != -1 ) aMinStr.RemoveAll( '-' );
3211       while ( aMaxStr.Search( "-" ) != -1 ) aMaxStr.RemoveAll( '-' );
3212
3213       if ( (!aMinStr.IsEmpty() && !aMinStr.IsIntegerValue()) ||
3214            (!aMaxStr.IsEmpty() && !aMaxStr.IsIntegerValue()) )
3215         return false;
3216
3217       myMin.Append( aMinStr.IsEmpty() ? IntegerFirst() : aMinStr.IntegerValue() );
3218       myMax.Append( aMaxStr.IsEmpty() ? IntegerLast()  : aMaxStr.IntegerValue() );
3219     }
3220   }
3221
3222   return true;
3223 }
3224
3225 //=======================================================================
3226 // name    : GetType
3227 // Purpose : Get type of supported entities
3228 //=======================================================================
3229 SMDSAbs_ElementType RangeOfIds::GetType() const
3230 {
3231   return myType;
3232 }
3233
3234 //=======================================================================
3235 // name    : SetType
3236 // Purpose : Set type of supported entities
3237 //=======================================================================
3238 void RangeOfIds::SetType( SMDSAbs_ElementType theType )
3239 {
3240   myType = theType;
3241 }
3242
3243 //=======================================================================
3244 // name    : IsSatisfy
3245 // Purpose : Verify whether entity satisfies to this rpedicate
3246 //=======================================================================
3247 bool RangeOfIds::IsSatisfy( long theId )
3248 {
3249   if ( !myMesh )
3250     return false;
3251
3252   if ( myType == SMDSAbs_Node )
3253   {
3254     if ( myMesh->FindNode( theId ) == 0 )
3255       return false;
3256   }
3257   else
3258   {
3259     const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
3260     if ( anElem == 0 || (myType != anElem->GetType() && myType != SMDSAbs_All ))
3261       return false;
3262   }
3263
3264   if ( myIds.Contains( theId ) )
3265     return true;
3266
3267   for ( int i = 1, n = myMin.Length(); i <= n; i++ )
3268     if ( theId >= myMin( i ) && theId <= myMax( i ) )
3269       return true;
3270
3271   return false;
3272 }
3273
3274 /*
3275   Class       : Comparator
3276   Description : Base class for comparators
3277 */
3278 Comparator::Comparator():
3279   myMargin(0)
3280 {}
3281
3282 Comparator::~Comparator()
3283 {}
3284
3285 void Comparator::SetMesh( const SMDS_Mesh* theMesh )
3286 {
3287   if ( myFunctor )
3288     myFunctor->SetMesh( theMesh );
3289 }
3290
3291 void Comparator::SetMargin( double theValue )
3292 {
3293   myMargin = theValue;
3294 }
3295
3296 void Comparator::SetNumFunctor( NumericalFunctorPtr theFunct )
3297 {
3298   myFunctor = theFunct;
3299 }
3300
3301 SMDSAbs_ElementType Comparator::GetType() const
3302 {
3303   return myFunctor ? myFunctor->GetType() : SMDSAbs_All;
3304 }
3305
3306 double Comparator::GetMargin()
3307 {
3308   return myMargin;
3309 }
3310
3311
3312 /*
3313   Class       : LessThan
3314   Description : Comparator "<"
3315 */
3316 bool LessThan::IsSatisfy( long theId )
3317 {
3318   return myFunctor && myFunctor->GetValue( theId ) < myMargin;
3319 }
3320
3321
3322 /*
3323   Class       : MoreThan
3324   Description : Comparator ">"
3325 */
3326 bool MoreThan::IsSatisfy( long theId )
3327 {
3328   return myFunctor && myFunctor->GetValue( theId ) > myMargin;
3329 }
3330
3331
3332 /*
3333   Class       : EqualTo
3334   Description : Comparator "="
3335 */
3336 EqualTo::EqualTo():
3337   myToler(Precision::Confusion())
3338 {}
3339
3340 bool EqualTo::IsSatisfy( long theId )
3341 {
3342   return myFunctor && fabs( myFunctor->GetValue( theId ) - myMargin ) < myToler;
3343 }
3344
3345 void EqualTo::SetTolerance( double theToler )
3346 {
3347   myToler = theToler;
3348 }
3349
3350 double EqualTo::GetTolerance()
3351 {
3352   return myToler;
3353 }
3354
3355 /*
3356   Class       : LogicalNOT
3357   Description : Logical NOT predicate
3358 */
3359 LogicalNOT::LogicalNOT()
3360 {}
3361
3362 LogicalNOT::~LogicalNOT()
3363 {}
3364
3365 bool LogicalNOT::IsSatisfy( long theId )
3366 {
3367   return myPredicate && !myPredicate->IsSatisfy( theId );
3368 }
3369
3370 void LogicalNOT::SetMesh( const SMDS_Mesh* theMesh )
3371 {
3372   if ( myPredicate )
3373     myPredicate->SetMesh( theMesh );
3374 }
3375
3376 void LogicalNOT::SetPredicate( PredicatePtr thePred )
3377 {
3378   myPredicate = thePred;
3379 }
3380
3381 SMDSAbs_ElementType LogicalNOT::GetType() const
3382 {
3383   return myPredicate ? myPredicate->GetType() : SMDSAbs_All;
3384 }
3385
3386
3387 /*
3388   Class       : LogicalBinary
3389   Description : Base class for binary logical predicate
3390 */
3391 LogicalBinary::LogicalBinary()
3392 {}
3393
3394 LogicalBinary::~LogicalBinary()
3395 {}
3396
3397 void LogicalBinary::SetMesh( const SMDS_Mesh* theMesh )
3398 {
3399   if ( myPredicate1 )
3400     myPredicate1->SetMesh( theMesh );
3401
3402   if ( myPredicate2 )
3403     myPredicate2->SetMesh( theMesh );
3404 }
3405
3406 void LogicalBinary::SetPredicate1( PredicatePtr thePredicate )
3407 {
3408   myPredicate1 = thePredicate;
3409 }
3410
3411 void LogicalBinary::SetPredicate2( PredicatePtr thePredicate )
3412 {
3413   myPredicate2 = thePredicate;
3414 }
3415
3416 SMDSAbs_ElementType LogicalBinary::GetType() const
3417 {
3418   if ( !myPredicate1 || !myPredicate2 )
3419     return SMDSAbs_All;
3420
3421   SMDSAbs_ElementType aType1 = myPredicate1->GetType();
3422   SMDSAbs_ElementType aType2 = myPredicate2->GetType();
3423
3424   return aType1 == aType2 ? aType1 : SMDSAbs_All;
3425 }
3426
3427
3428 /*
3429   Class       : LogicalAND
3430   Description : Logical AND
3431 */
3432 bool LogicalAND::IsSatisfy( long theId )
3433 {
3434   return
3435     myPredicate1 &&
3436     myPredicate2 &&
3437     myPredicate1->IsSatisfy( theId ) &&
3438     myPredicate2->IsSatisfy( theId );
3439 }
3440
3441
3442 /*
3443   Class       : LogicalOR
3444   Description : Logical OR
3445 */
3446 bool LogicalOR::IsSatisfy( long theId )
3447 {
3448   return
3449     myPredicate1 &&
3450     myPredicate2 &&
3451     (myPredicate1->IsSatisfy( theId ) ||
3452     myPredicate2->IsSatisfy( theId ));
3453 }
3454
3455
3456 /*
3457                               FILTER
3458 */
3459
3460 // #ifdef WITH_TBB
3461 // #include <tbb/parallel_for.h>
3462 // #include <tbb/enumerable_thread_specific.h>
3463
3464 // namespace Parallel
3465 // {
3466 //   typedef tbb::enumerable_thread_specific< TIdSequence > TIdSeq;
3467
3468 //   struct Predicate
3469 //   {
3470 //     const SMDS_Mesh* myMesh;
3471 //     PredicatePtr     myPredicate;
3472 //     TIdSeq &         myOKIds;
3473 //     Predicate( const SMDS_Mesh* m, PredicatePtr p, TIdSeq & ids ):
3474 //       myMesh(m), myPredicate(p->Duplicate()), myOKIds(ids) {}
3475 //     void operator() ( const tbb::blocked_range<size_t>& r ) const
3476 //     {
3477 //       for ( size_t i = r.begin(); i != r.end(); ++i )
3478 //         if ( myPredicate->IsSatisfy( i ))
3479 //           myOKIds.local().push_back();
3480 //     }
3481 //   }
3482 // }
3483 // #endif
3484
3485 Filter::Filter()
3486 {}
3487
3488 Filter::~Filter()
3489 {}
3490
3491 void Filter::SetPredicate( PredicatePtr thePredicate )
3492 {
3493   myPredicate = thePredicate;
3494 }
3495
3496 void Filter::GetElementsId( const SMDS_Mesh* theMesh,
3497                             PredicatePtr     thePredicate,
3498                             TIdSequence&     theSequence )
3499 {
3500   theSequence.clear();
3501
3502   if ( !theMesh || !thePredicate )
3503     return;
3504
3505   thePredicate->SetMesh( theMesh );
3506
3507   SMDS_ElemIteratorPtr elemIt = theMesh->elementsIterator( thePredicate->GetType() );
3508   if ( elemIt ) {
3509     while ( elemIt->more() ) {
3510       const SMDS_MeshElement* anElem = elemIt->next();
3511       long anId = anElem->GetID();
3512       if ( thePredicate->IsSatisfy( anId ) )
3513         theSequence.push_back( anId );
3514     }
3515   }
3516 }
3517
3518 void Filter::GetElementsId( const SMDS_Mesh*     theMesh,
3519                             Filter::TIdSequence& theSequence )
3520 {
3521   GetElementsId(theMesh,myPredicate,theSequence);
3522 }
3523
3524 /*
3525                               ManifoldPart
3526 */
3527
3528 typedef std::set<SMDS_MeshFace*>                    TMapOfFacePtr;
3529
3530 /*
3531    Internal class Link
3532 */
3533
3534 ManifoldPart::Link::Link( SMDS_MeshNode* theNode1,
3535                           SMDS_MeshNode* theNode2 )
3536 {
3537   myNode1 = theNode1;
3538   myNode2 = theNode2;
3539 }
3540
3541 ManifoldPart::Link::~Link()
3542 {
3543   myNode1 = 0;
3544   myNode2 = 0;
3545 }
3546
3547 bool ManifoldPart::Link::IsEqual( const ManifoldPart::Link& theLink ) const
3548 {
3549   if ( myNode1 == theLink.myNode1 &&
3550        myNode2 == theLink.myNode2 )
3551     return true;
3552   else if ( myNode1 == theLink.myNode2 &&
3553             myNode2 == theLink.myNode1 )
3554     return true;
3555   else
3556     return false;
3557 }
3558
3559 bool ManifoldPart::Link::operator<( const ManifoldPart::Link& x ) const
3560 {
3561   if(myNode1 < x.myNode1) return true;
3562   if(myNode1 == x.myNode1)
3563     if(myNode2 < x.myNode2) return true;
3564   return false;
3565 }
3566
3567 bool ManifoldPart::IsEqual( const ManifoldPart::Link& theLink1,
3568                             const ManifoldPart::Link& theLink2 )
3569 {
3570   return theLink1.IsEqual( theLink2 );
3571 }
3572
3573 ManifoldPart::ManifoldPart()
3574 {
3575   myMesh = 0;
3576   myAngToler = Precision::Angular();
3577   myIsOnlyManifold = true;
3578 }
3579
3580 ManifoldPart::~ManifoldPart()
3581 {
3582   myMesh = 0;
3583 }
3584
3585 void ManifoldPart::SetMesh( const SMDS_Mesh* theMesh )
3586 {
3587   myMesh = theMesh;
3588   process();
3589 }
3590
3591 SMDSAbs_ElementType ManifoldPart::GetType() const
3592 { return SMDSAbs_Face; }
3593
3594 bool ManifoldPart::IsSatisfy( long theElementId )
3595 {
3596   return myMapIds.Contains( theElementId );
3597 }
3598
3599 void ManifoldPart::SetAngleTolerance( const double theAngToler )
3600 { myAngToler = theAngToler; }
3601
3602 double ManifoldPart::GetAngleTolerance() const
3603 { return myAngToler; }
3604
3605 void ManifoldPart::SetIsOnlyManifold( const bool theIsOnly )
3606 { myIsOnlyManifold = theIsOnly; }
3607
3608 void ManifoldPart::SetStartElem( const long  theStartId )
3609 { myStartElemId = theStartId; }
3610
3611 bool ManifoldPart::process()
3612 {
3613   myMapIds.Clear();
3614   myMapBadGeomIds.Clear();
3615
3616   myAllFacePtr.clear();
3617   myAllFacePtrIntDMap.clear();
3618   if ( !myMesh )
3619     return false;
3620
3621   // collect all faces into own map
3622   SMDS_FaceIteratorPtr anFaceItr = myMesh->facesIterator();
3623   for (; anFaceItr->more(); )
3624   {
3625     SMDS_MeshFace* aFacePtr = (SMDS_MeshFace*)anFaceItr->next();
3626     myAllFacePtr.push_back( aFacePtr );
3627     myAllFacePtrIntDMap[aFacePtr] = myAllFacePtr.size()-1;
3628   }
3629
3630   SMDS_MeshFace* aStartFace = (SMDS_MeshFace*)myMesh->FindElement( myStartElemId );
3631   if ( !aStartFace )
3632     return false;
3633
3634   // the map of non manifold links and bad geometry
3635   TMapOfLink aMapOfNonManifold;
3636   TColStd_MapOfInteger aMapOfTreated;
3637
3638   // begin cycle on faces from start index and run on vector till the end
3639   //  and from begin to start index to cover whole vector
3640   const int aStartIndx = myAllFacePtrIntDMap[aStartFace];
3641   bool isStartTreat = false;
3642   for ( int fi = aStartIndx; !isStartTreat || fi != aStartIndx ; fi++ )
3643   {
3644     if ( fi == aStartIndx )
3645       isStartTreat = true;
3646     // as result next time when fi will be equal to aStartIndx
3647
3648     SMDS_MeshFace* aFacePtr = myAllFacePtr[ fi ];
3649     if ( aMapOfTreated.Contains( aFacePtr->GetID() ) )
3650       continue;
3651
3652     aMapOfTreated.Add( aFacePtr->GetID() );
3653     TColStd_MapOfInteger aResFaces;
3654     if ( !findConnected( myAllFacePtrIntDMap, aFacePtr,
3655                          aMapOfNonManifold, aResFaces ) )
3656       continue;
3657     TColStd_MapIteratorOfMapOfInteger anItr( aResFaces );
3658     for ( ; anItr.More(); anItr.Next() )
3659     {
3660       int aFaceId = anItr.Key();
3661       aMapOfTreated.Add( aFaceId );
3662       myMapIds.Add( aFaceId );
3663     }
3664
3665     if ( fi == ( myAllFacePtr.size() - 1 ) )
3666       fi = 0;
3667   } // end run on vector of faces
3668   return !myMapIds.IsEmpty();
3669 }
3670
3671 static void getLinks( const SMDS_MeshFace* theFace,
3672                       ManifoldPart::TVectorOfLink& theLinks )
3673 {
3674   int aNbNode = theFace->NbNodes();
3675   SMDS_ElemIteratorPtr aNodeItr = theFace->nodesIterator();
3676   int i = 1;
3677   SMDS_MeshNode* aNode = 0;
3678   for ( ; aNodeItr->more() && i <= aNbNode; )
3679   {
3680
3681     SMDS_MeshNode* aN1 = (SMDS_MeshNode*)aNodeItr->next();
3682     if ( i == 1 )
3683       aNode = aN1;
3684     i++;
3685     SMDS_MeshNode* aN2 = ( i >= aNbNode ) ? aNode : (SMDS_MeshNode*)aNodeItr->next();
3686     i++;
3687     ManifoldPart::Link aLink( aN1, aN2 );
3688     theLinks.push_back( aLink );
3689   }
3690 }
3691
3692 bool ManifoldPart::findConnected
3693                  ( const ManifoldPart::TDataMapFacePtrInt& theAllFacePtrInt,
3694                   SMDS_MeshFace*                           theStartFace,
3695                   ManifoldPart::TMapOfLink&                theNonManifold,
3696                   TColStd_MapOfInteger&                    theResFaces )
3697 {
3698   theResFaces.Clear();
3699   if ( !theAllFacePtrInt.size() )
3700     return false;
3701
3702   if ( getNormale( theStartFace ).SquareModulus() <= gp::Resolution() )
3703   {
3704     myMapBadGeomIds.Add( theStartFace->GetID() );
3705     return false;
3706   }
3707
3708   ManifoldPart::TMapOfLink aMapOfBoundary, aMapToSkip;
3709   ManifoldPart::TVectorOfLink aSeqOfBoundary;
3710   theResFaces.Add( theStartFace->GetID() );
3711   ManifoldPart::TDataMapOfLinkFacePtr aDMapLinkFace;
3712
3713   expandBoundary( aMapOfBoundary, aSeqOfBoundary,
3714                  aDMapLinkFace, theNonManifold, theStartFace );
3715
3716   bool isDone = false;
3717   while ( !isDone && aMapOfBoundary.size() != 0 )
3718   {
3719     bool isToReset = false;
3720     ManifoldPart::TVectorOfLink::iterator pLink = aSeqOfBoundary.begin();
3721     for ( ; !isToReset && pLink != aSeqOfBoundary.end(); ++pLink )
3722     {
3723       ManifoldPart::Link aLink = *pLink;
3724       if ( aMapToSkip.find( aLink ) != aMapToSkip.end() )
3725         continue;
3726       // each link could be treated only once
3727       aMapToSkip.insert( aLink );
3728
3729       ManifoldPart::TVectorOfFacePtr aFaces;
3730       // find next
3731       if ( myIsOnlyManifold &&
3732            (theNonManifold.find( aLink ) != theNonManifold.end()) )
3733         continue;
3734       else
3735       {
3736         getFacesByLink( aLink, aFaces );
3737         // filter the element to keep only indicated elements
3738         ManifoldPart::TVectorOfFacePtr aFiltered;
3739         ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin();
3740         for ( ; pFace != aFaces.end(); ++pFace )
3741         {
3742           SMDS_MeshFace* aFace = *pFace;
3743           if ( myAllFacePtrIntDMap.find( aFace ) != myAllFacePtrIntDMap.end() )
3744             aFiltered.push_back( aFace );
3745         }
3746         aFaces = aFiltered;
3747         if ( aFaces.size() < 2 )  // no neihgbour faces
3748           continue;
3749         else if ( myIsOnlyManifold && aFaces.size() > 2 ) // non manifold case
3750         {
3751           theNonManifold.insert( aLink );
3752           continue;
3753         }
3754       }
3755
3756       // compare normal with normals of neighbor element
3757       SMDS_MeshFace* aPrevFace = aDMapLinkFace[ aLink ];
3758       ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin();
3759       for ( ; pFace != aFaces.end(); ++pFace )
3760       {
3761         SMDS_MeshFace* aNextFace = *pFace;
3762         if ( aPrevFace == aNextFace )
3763           continue;
3764         int anNextFaceID = aNextFace->GetID();
3765         if ( myIsOnlyManifold && theResFaces.Contains( anNextFaceID ) )
3766          // should not be with non manifold restriction. probably bad topology
3767           continue;
3768         // check if face was treated and skipped
3769         if ( myMapBadGeomIds.Contains( anNextFaceID ) ||
3770              !isInPlane( aPrevFace, aNextFace ) )
3771           continue;
3772         // add new element to connected and extend the boundaries.
3773         theResFaces.Add( anNextFaceID );
3774         expandBoundary( aMapOfBoundary, aSeqOfBoundary,
3775                         aDMapLinkFace, theNonManifold, aNextFace );
3776         isToReset = true;
3777       }
3778     }
3779     isDone = !isToReset;
3780   }
3781
3782   return !theResFaces.IsEmpty();
3783 }
3784
3785 bool ManifoldPart::isInPlane( const SMDS_MeshFace* theFace1,
3786                               const SMDS_MeshFace* theFace2 )
3787 {
3788   gp_Dir aNorm1 = gp_Dir( getNormale( theFace1 ) );
3789   gp_XYZ aNorm2XYZ = getNormale( theFace2 );
3790   if ( aNorm2XYZ.SquareModulus() <= gp::Resolution() )
3791   {
3792     myMapBadGeomIds.Add( theFace2->GetID() );
3793     return false;
3794   }
3795   if ( aNorm1.IsParallel( gp_Dir( aNorm2XYZ ), myAngToler ) )
3796     return true;
3797
3798   return false;
3799 }
3800
3801 void ManifoldPart::expandBoundary
3802                    ( ManifoldPart::TMapOfLink&            theMapOfBoundary,
3803                      ManifoldPart::TVectorOfLink&         theSeqOfBoundary,
3804                      ManifoldPart::TDataMapOfLinkFacePtr& theDMapLinkFacePtr,
3805                      ManifoldPart::TMapOfLink&            theNonManifold,
3806                      SMDS_MeshFace*                       theNextFace ) const
3807 {
3808   ManifoldPart::TVectorOfLink aLinks;
3809   getLinks( theNextFace, aLinks );
3810   int aNbLink = (int)aLinks.size();
3811   for ( int i = 0; i < aNbLink; i++ )
3812   {
3813     ManifoldPart::Link aLink = aLinks[ i ];
3814     if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) )
3815       continue;
3816     if ( theMapOfBoundary.find( aLink ) != theMapOfBoundary.end() )
3817     {
3818       if ( myIsOnlyManifold )
3819       {
3820         // remove from boundary
3821         theMapOfBoundary.erase( aLink );
3822         ManifoldPart::TVectorOfLink::iterator pLink = theSeqOfBoundary.begin();
3823         for ( ; pLink != theSeqOfBoundary.end(); ++pLink )
3824         {
3825           ManifoldPart::Link aBoundLink = *pLink;
3826           if ( aBoundLink.IsEqual( aLink ) )
3827           {
3828             theSeqOfBoundary.erase( pLink );
3829             break;
3830           }
3831         }
3832       }
3833     }
3834     else
3835     {
3836       theMapOfBoundary.insert( aLink );
3837       theSeqOfBoundary.push_back( aLink );
3838       theDMapLinkFacePtr[ aLink ] = theNextFace;
3839     }
3840   }
3841 }
3842
3843 void ManifoldPart::getFacesByLink( const ManifoldPart::Link& theLink,
3844                                    ManifoldPart::TVectorOfFacePtr& theFaces ) const
3845 {
3846   std::set<SMDS_MeshCell *> aSetOfFaces;
3847   // take all faces that shared first node
3848   SMDS_ElemIteratorPtr anItr = theLink.myNode1->facesIterator();
3849   for ( ; anItr->more(); )
3850   {
3851     SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next();
3852     if ( !aFace )
3853       continue;
3854     aSetOfFaces.insert( aFace );
3855   }
3856   // take all faces that shared second node
3857   anItr = theLink.myNode2->facesIterator();
3858   // find the common part of two sets
3859   for ( ; anItr->more(); )
3860   {
3861     SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next();
3862     if ( aSetOfFaces.count( aFace ) )
3863       theFaces.push_back( aFace );
3864   }
3865 }
3866
3867 /*
3868   Class       : BelongToMeshGroup
3869   Description : Verify whether a mesh element is included into a mesh group
3870 */
3871 BelongToMeshGroup::BelongToMeshGroup(): myGroup( 0 )
3872 {
3873 }
3874
3875 void BelongToMeshGroup::SetGroup( SMESHDS_GroupBase* g )
3876 {
3877   myGroup = g;
3878 }
3879
3880 void BelongToMeshGroup::SetStoreName( const std::string& sn )
3881 {
3882   myStoreName = sn;
3883 }
3884
3885 void BelongToMeshGroup::SetMesh( const SMDS_Mesh* theMesh )
3886 {
3887   if ( myGroup && myGroup->GetMesh() != theMesh )
3888   {
3889     myGroup = 0;
3890   }
3891   if ( !myGroup && !myStoreName.empty() )
3892   {
3893     if ( const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh))
3894     {
3895       const std::set<SMESHDS_GroupBase*>& grps = aMesh->GetGroups();
3896       std::set<SMESHDS_GroupBase*>::const_iterator g = grps.begin();
3897       for ( ; g != grps.end() && !myGroup; ++g )
3898         if ( *g && myStoreName == (*g)->GetStoreName() )
3899           myGroup = *g;
3900     }
3901   }
3902   if ( myGroup )
3903   {
3904     myGroup->IsEmpty(); // make GroupOnFilter update its predicate
3905   }
3906 }
3907
3908 bool BelongToMeshGroup::IsSatisfy( long theElementId )
3909 {
3910   return myGroup ? myGroup->Contains( theElementId ) : false;
3911 }
3912
3913 SMDSAbs_ElementType BelongToMeshGroup::GetType() const
3914 {
3915   return myGroup ? myGroup->GetType() : SMDSAbs_All;
3916 }
3917
3918 /*
3919   ElementsOnSurface
3920 */
3921
3922 ElementsOnSurface::ElementsOnSurface()
3923 {
3924   myIds.Clear();
3925   myType = SMDSAbs_All;
3926   mySurf.Nullify();
3927   myToler = Precision::Confusion();
3928   myUseBoundaries = false;
3929 }
3930
3931 ElementsOnSurface::~ElementsOnSurface()
3932 {
3933 }
3934
3935 void ElementsOnSurface::SetMesh( const SMDS_Mesh* theMesh )
3936 {
3937   myMeshModifTracer.SetMesh( theMesh );
3938   if ( myMeshModifTracer.IsMeshModified())
3939     process();
3940 }
3941
3942 bool ElementsOnSurface::IsSatisfy( long theElementId )
3943 {
3944   return myIds.Contains( theElementId );
3945 }
3946
3947 SMDSAbs_ElementType ElementsOnSurface::GetType() const
3948 { return myType; }
3949
3950 void ElementsOnSurface::SetTolerance( const double theToler )
3951 {
3952   if ( myToler != theToler )
3953     myIds.Clear();
3954   myToler = theToler;
3955 }
3956
3957 double ElementsOnSurface::GetTolerance() const
3958 { return myToler; }
3959
3960 void ElementsOnSurface::SetUseBoundaries( bool theUse )
3961 {
3962   if ( myUseBoundaries != theUse ) {
3963     myUseBoundaries = theUse;
3964     SetSurface( mySurf, myType );
3965   }
3966 }
3967
3968 void ElementsOnSurface::SetSurface( const TopoDS_Shape& theShape,
3969                                     const SMDSAbs_ElementType theType )
3970 {
3971   myIds.Clear();
3972   myType = theType;
3973   mySurf.Nullify();
3974   if ( theShape.IsNull() || theShape.ShapeType() != TopAbs_FACE )
3975     return;
3976   mySurf = TopoDS::Face( theShape );
3977   BRepAdaptor_Surface SA( mySurf, myUseBoundaries );
3978   Standard_Real
3979     u1 = SA.FirstUParameter(),
3980     u2 = SA.LastUParameter(),
3981     v1 = SA.FirstVParameter(),
3982     v2 = SA.LastVParameter();
3983   Handle(Geom_Surface) surf = BRep_Tool::Surface( mySurf );
3984   myProjector.Init( surf, u1,u2, v1,v2 );
3985   process();
3986 }
3987
3988 void ElementsOnSurface::process()
3989 {
3990   myIds.Clear();
3991   if ( mySurf.IsNull() )
3992     return;
3993
3994   if ( !myMeshModifTracer.GetMesh() )
3995     return;
3996
3997   myIds.ReSize( myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType ));
3998
3999   SMDS_ElemIteratorPtr anIter = myMeshModifTracer.GetMesh()->elementsIterator( myType );
4000   for(; anIter->more(); )
4001     process( anIter->next() );
4002 }
4003
4004 void ElementsOnSurface::process( const SMDS_MeshElement* theElemPtr )
4005 {
4006   SMDS_ElemIteratorPtr aNodeItr = theElemPtr->nodesIterator();
4007   bool isSatisfy = true;
4008   for ( ; aNodeItr->more(); )
4009   {
4010     SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next();
4011     if ( !isOnSurface( aNode ) )
4012     {
4013       isSatisfy = false;
4014       break;
4015     }
4016   }
4017   if ( isSatisfy )
4018     myIds.Add( theElemPtr->GetID() );
4019 }
4020
4021 bool ElementsOnSurface::isOnSurface( const SMDS_MeshNode* theNode )
4022 {
4023   if ( mySurf.IsNull() )
4024     return false;
4025
4026   gp_Pnt aPnt( theNode->X(), theNode->Y(), theNode->Z() );
4027   //  double aToler2 = myToler * myToler;
4028 //   if ( mySurf->IsKind(STANDARD_TYPE(Geom_Plane)))
4029 //   {
4030 //     gp_Pln aPln = Handle(Geom_Plane)::DownCast(mySurf)->Pln();
4031 //     if ( aPln.SquareDistance( aPnt ) > aToler2 )
4032 //       return false;
4033 //   }
4034 //   else if ( mySurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)))
4035 //   {
4036 //     gp_Cylinder aCyl = Handle(Geom_CylindricalSurface)::DownCast(mySurf)->Cylinder();
4037 //     double aRad = aCyl.Radius();
4038 //     gp_Ax3 anAxis = aCyl.Position();
4039 //     gp_XYZ aLoc = aCyl.Location().XYZ();
4040 //     double aXDist = anAxis.XDirection().XYZ() * ( aPnt.XYZ() - aLoc );
4041 //     double aYDist = anAxis.YDirection().XYZ() * ( aPnt.XYZ() - aLoc );
4042 //     if ( fabs(aXDist*aXDist + aYDist*aYDist - aRad*aRad) > aToler2 )
4043 //       return false;
4044 //   }
4045 //   else
4046 //     return false;
4047   myProjector.Perform( aPnt );
4048   bool isOn = ( myProjector.IsDone() && myProjector.LowerDistance() <= myToler );
4049
4050   return isOn;
4051 }
4052
4053
4054 /*
4055   ElementsOnShape
4056 */
4057
4058 ElementsOnShape::ElementsOnShape()
4059   : //myMesh(0),
4060     myType(SMDSAbs_All),
4061     myToler(Precision::Confusion()),
4062     myAllNodesFlag(false)
4063 {
4064 }
4065
4066 ElementsOnShape::~ElementsOnShape()
4067 {
4068   clearClassifiers();
4069 }
4070
4071 SMDSAbs_ElementType ElementsOnShape::GetType() const
4072 {
4073   return myType;
4074 }
4075
4076 void ElementsOnShape::SetTolerance (const double theToler)
4077 {
4078   if (myToler != theToler) {
4079     myToler = theToler;
4080     SetShape(myShape, myType);
4081   }
4082 }
4083
4084 double ElementsOnShape::GetTolerance() const
4085 {
4086   return myToler;
4087 }
4088
4089 void ElementsOnShape::SetAllNodes (bool theAllNodes)
4090 {
4091   myAllNodesFlag = theAllNodes;
4092 }
4093
4094 void ElementsOnShape::SetMesh (const SMDS_Mesh* theMesh)
4095 {
4096   myMeshModifTracer.SetMesh( theMesh );
4097   if ( myMeshModifTracer.IsMeshModified())
4098   {
4099     size_t nbNodes = theMesh ? theMesh->NbNodes() : 0;
4100     if ( myNodeIsChecked.size() == nbNodes )
4101     {
4102       std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false );
4103     }
4104     else
4105     {
4106       SMESHUtils::FreeVector( myNodeIsChecked );
4107       SMESHUtils::FreeVector( myNodeIsOut );
4108       myNodeIsChecked.resize( nbNodes, false );
4109       myNodeIsOut.resize( nbNodes );
4110     }
4111   }
4112 }
4113
4114 bool ElementsOnShape::getNodeIsOut( const SMDS_MeshNode* n, bool& isOut )
4115 {
4116   if ( n->GetID() >= (int) myNodeIsChecked.size() ||
4117        !myNodeIsChecked[ n->GetID() ])
4118     return false;
4119
4120   isOut = myNodeIsOut[ n->GetID() ];
4121   return true;
4122 }
4123
4124 void ElementsOnShape::setNodeIsOut( const SMDS_MeshNode* n, bool  isOut )
4125 {
4126   if ( n->GetID() < (int) myNodeIsChecked.size() )
4127   {
4128     myNodeIsChecked[ n->GetID() ] = true;
4129     myNodeIsOut    [ n->GetID() ] = isOut;
4130   }
4131 }
4132
4133 void ElementsOnShape::SetShape (const TopoDS_Shape&       theShape,
4134                                 const SMDSAbs_ElementType theType)
4135 {
4136   myType  = theType;
4137   myShape = theShape;
4138   if ( myShape.IsNull() ) return;
4139
4140   TopTools_IndexedMapOfShape shapesMap;
4141   TopAbs_ShapeEnum shapeTypes[4] = { TopAbs_SOLID, TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX };
4142   TopExp_Explorer sub;
4143   for ( int i = 0; i < 4; ++i )
4144   {
4145     if ( shapesMap.IsEmpty() )
4146       for ( sub.Init( myShape, shapeTypes[i] ); sub.More(); sub.Next() )
4147         shapesMap.Add( sub.Current() );
4148     if ( i > 0 )
4149       for ( sub.Init( myShape, shapeTypes[i], shapeTypes[i-1] ); sub.More(); sub.Next() )
4150         shapesMap.Add( sub.Current() );
4151   }
4152
4153   clearClassifiers();
4154   myClassifiers.resize( shapesMap.Extent() );
4155   for ( int i = 0; i < shapesMap.Extent(); ++i )
4156     myClassifiers[ i ] = new TClassifier( shapesMap( i+1 ), myToler );
4157
4158   if ( theType == SMDSAbs_Node )
4159   {
4160     SMESHUtils::FreeVector( myNodeIsChecked );
4161     SMESHUtils::FreeVector( myNodeIsOut );
4162   }
4163   else
4164   {
4165     std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false );
4166   }
4167 }
4168
4169 void ElementsOnShape::clearClassifiers()
4170 {
4171   for ( size_t i = 0; i < myClassifiers.size(); ++i )
4172     delete myClassifiers[ i ];
4173   myClassifiers.clear();
4174 }
4175
4176 bool ElementsOnShape::IsSatisfy (long elemId)
4177 {
4178   const SMDS_Mesh*        mesh = myMeshModifTracer.GetMesh();
4179   const SMDS_MeshElement* elem =
4180     ( myType == SMDSAbs_Node ? mesh->FindNode( elemId ) : mesh->FindElement( elemId ));
4181   if ( !elem || myClassifiers.empty() )
4182     return false;
4183
4184   bool isSatisfy = myAllNodesFlag, isNodeOut;
4185
4186   gp_XYZ centerXYZ (0, 0, 0);
4187
4188   SMDS_ElemIteratorPtr aNodeItr = elem->nodesIterator();
4189   while (aNodeItr->more() && (isSatisfy == myAllNodesFlag))
4190   {
4191     SMESH_TNodeXYZ aPnt( aNodeItr->next() );
4192     centerXYZ += aPnt;
4193
4194     isNodeOut = true;
4195     if ( !getNodeIsOut( aPnt._node, isNodeOut ))
4196     {
4197       for ( size_t i = 0; i < myClassifiers.size() && isNodeOut; ++i )
4198         isNodeOut = myClassifiers[i]->IsOut( aPnt );
4199
4200       setNodeIsOut( aPnt._node, isNodeOut );
4201     }
4202     isSatisfy = !isNodeOut;
4203   }
4204
4205   // Check the center point for volumes MantisBug 0020168
4206   if (isSatisfy &&
4207       myAllNodesFlag &&
4208       myClassifiers[0]->ShapeType() == TopAbs_SOLID)
4209   {
4210     centerXYZ /= elem->NbNodes();
4211     isSatisfy = false;
4212     for ( size_t i = 0; i < myClassifiers.size() && !isSatisfy; ++i )
4213       isSatisfy = ! myClassifiers[i]->IsOut( centerXYZ );
4214   }
4215
4216   return isSatisfy;
4217 }
4218
4219 TopAbs_ShapeEnum ElementsOnShape::TClassifier::ShapeType() const
4220 {
4221   return myShape.ShapeType();
4222 }
4223
4224 bool ElementsOnShape::TClassifier::IsOut(const gp_Pnt& p)
4225 {
4226   return (this->*myIsOutFun)( p );
4227 }
4228
4229 void ElementsOnShape::TClassifier::Init (const TopoDS_Shape& theShape, double theTol)
4230 {
4231   myShape = theShape;
4232   myTol   = theTol;
4233   switch ( myShape.ShapeType() )
4234   {
4235   case TopAbs_SOLID: {
4236     if ( isBox( theShape ))
4237     {
4238       myIsOutFun = & ElementsOnShape::TClassifier::isOutOfBox;
4239     }
4240     else
4241     {
4242       mySolidClfr.Load(theShape);
4243       myIsOutFun = & ElementsOnShape::TClassifier::isOutOfSolid;
4244     }
4245     break;
4246   }
4247   case TopAbs_FACE:  {
4248     Standard_Real u1,u2,v1,v2;
4249     Handle(Geom_Surface) surf = BRep_Tool::Surface( TopoDS::Face( theShape ));
4250     surf->Bounds( u1,u2,v1,v2 );
4251     myProjFace.Init(surf, u1,u2, v1,v2, myTol );
4252     myIsOutFun = & ElementsOnShape::TClassifier::isOutOfFace;
4253     break;
4254   }
4255   case TopAbs_EDGE:  {
4256     Standard_Real u1, u2;
4257     Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge(theShape), u1, u2);
4258     myProjEdge.Init(curve, u1, u2);
4259     myIsOutFun = & ElementsOnShape::TClassifier::isOutOfEdge;
4260     break;
4261   }
4262   case TopAbs_VERTEX:{
4263     myVertexXYZ = BRep_Tool::Pnt( TopoDS::Vertex( theShape ) );
4264     myIsOutFun = & ElementsOnShape::TClassifier::isOutOfVertex;
4265     break;
4266   }
4267   default:
4268     throw SALOME_Exception("Programmer error in usage of ElementsOnShape::TClassifier");
4269   }
4270 }
4271
4272 bool ElementsOnShape::TClassifier::isOutOfSolid (const gp_Pnt& p)
4273 {
4274   mySolidClfr.Perform( p, myTol );
4275   return ( mySolidClfr.State() != TopAbs_IN && mySolidClfr.State() != TopAbs_ON );
4276 }
4277
4278 bool ElementsOnShape::TClassifier::isOutOfBox (const gp_Pnt& p)
4279 {
4280   return myBox.IsOut( p.XYZ() );
4281 }
4282
4283 bool ElementsOnShape::TClassifier::isOutOfFace  (const gp_Pnt& p)
4284 {
4285   myProjFace.Perform( p );
4286   if ( myProjFace.IsDone() && myProjFace.LowerDistance() <= myTol )
4287   {
4288     // check relatively to the face
4289     Quantity_Parameter u, v;
4290     myProjFace.LowerDistanceParameters(u, v);
4291     gp_Pnt2d aProjPnt (u, v);
4292     BRepClass_FaceClassifier aClsf ( TopoDS::Face( myShape ), aProjPnt, myTol );
4293     if ( aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON )
4294       return false;
4295   }
4296   return true;
4297 }
4298
4299 bool ElementsOnShape::TClassifier::isOutOfEdge  (const gp_Pnt& p)
4300 {
4301   myProjEdge.Perform( p );
4302   return ! ( myProjEdge.NbPoints() > 0 && myProjEdge.LowerDistance() <= myTol );
4303 }
4304
4305 bool ElementsOnShape::TClassifier::isOutOfVertex(const gp_Pnt& p)
4306 {
4307   return ( myVertexXYZ.Distance( p ) > myTol );
4308 }
4309
4310 bool ElementsOnShape::TClassifier::isBox (const TopoDS_Shape& theShape)
4311 {
4312   TopTools_IndexedMapOfShape vMap;
4313   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4314   if ( vMap.Extent() != 8 )
4315     return false;
4316
4317   myBox.Clear();
4318   for ( int i = 1; i <= 8; ++i )
4319     myBox.Add( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))).XYZ() );
4320
4321   gp_XYZ pMin = myBox.CornerMin(), pMax = myBox.CornerMax();
4322   for ( int i = 1; i <= 8; ++i )
4323   {
4324     gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vMap( i )));
4325     for ( int iC = 1; iC <= 3; ++ iC )
4326     {
4327       double d1 = Abs( pMin.Coord( iC ) - p.Coord( iC ));
4328       double d2 = Abs( pMax.Coord( iC ) - p.Coord( iC ));
4329       if ( Min( d1, d2 ) > myTol )
4330         return false;
4331     }
4332   }
4333   myBox.Enlarge( myTol );
4334   return true;
4335 }
4336
4337
4338 /*
4339   Class       : BelongToGeom
4340   Description : Predicate for verifying whether entity belongs to
4341                 specified geometrical support
4342 */
4343
4344 BelongToGeom::BelongToGeom()
4345   : myMeshDS(NULL),
4346     myType(SMDSAbs_All),
4347     myIsSubshape(false),
4348     myTolerance(Precision::Confusion())
4349 {}
4350
4351 void BelongToGeom::SetMesh( const SMDS_Mesh* theMesh )
4352 {
4353   myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh);
4354   init();
4355 }
4356
4357 void BelongToGeom::SetGeom( const TopoDS_Shape& theShape )
4358 {
4359   myShape = theShape;
4360   init();
4361 }
4362
4363 static bool IsSubShape (const TopTools_IndexedMapOfShape& theMap,
4364                         const TopoDS_Shape& theShape)
4365 {
4366   if (theMap.Contains(theShape)) return true;
4367
4368   if (theShape.ShapeType() == TopAbs_COMPOUND ||
4369       theShape.ShapeType() == TopAbs_COMPSOLID)
4370   {
4371     TopoDS_Iterator anIt (theShape, Standard_True, Standard_True);
4372     for (; anIt.More(); anIt.Next())
4373     {
4374       if (!IsSubShape(theMap, anIt.Value())) {
4375         return false;
4376       }
4377     }
4378     return true;
4379   }
4380
4381   return false;
4382 }
4383
4384 void BelongToGeom::init()
4385 {
4386   if (!myMeshDS || myShape.IsNull()) return;
4387
4388   // is sub-shape of main shape?
4389   TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh();
4390   if (aMainShape.IsNull()) {
4391     myIsSubshape = false;
4392   }
4393   else {
4394     TopTools_IndexedMapOfShape aMap;
4395     TopExp::MapShapes(aMainShape, aMap);
4396     myIsSubshape = IsSubShape(aMap, myShape);
4397   }
4398
4399   //if (!myIsSubshape) // to be always ready to check an element not bound to geometry
4400   {
4401     myElementsOnShapePtr.reset(new ElementsOnShape());
4402     myElementsOnShapePtr->SetTolerance(myTolerance);
4403     myElementsOnShapePtr->SetAllNodes(true); // "belong", while false means "lays on"
4404     myElementsOnShapePtr->SetMesh(myMeshDS);
4405     myElementsOnShapePtr->SetShape(myShape, myType);
4406   }
4407 }
4408
4409 static bool IsContains( const SMESHDS_Mesh*     theMeshDS,
4410                         const TopoDS_Shape&     theShape,
4411                         const SMDS_MeshElement* theElem,
4412                         TopAbs_ShapeEnum        theFindShapeEnum,
4413                         TopAbs_ShapeEnum        theAvoidShapeEnum = TopAbs_SHAPE )
4414 {
4415   TopExp_Explorer anExp( theShape,theFindShapeEnum,theAvoidShapeEnum );
4416
4417   while( anExp.More() )
4418   {
4419     const TopoDS_Shape& aShape = anExp.Current();
4420     if( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape ) ){
4421       if( aSubMesh->Contains( theElem ) )
4422         return true;
4423     }
4424     anExp.Next();
4425   }
4426   return false;
4427 }
4428
4429 bool BelongToGeom::IsSatisfy (long theId)
4430 {
4431   if (myMeshDS == 0 || myShape.IsNull())
4432     return false;
4433
4434   if (!myIsSubshape)
4435   {
4436     return myElementsOnShapePtr->IsSatisfy(theId);
4437   }
4438
4439   // Case of submesh
4440   if (myType == SMDSAbs_Node)
4441   {
4442     if( const SMDS_MeshNode* aNode = myMeshDS->FindNode( theId ) )
4443     {
4444       if ( aNode->getshapeId() < 1 )
4445         return myElementsOnShapePtr->IsSatisfy(theId);
4446
4447       const SMDS_PositionPtr& aPosition = aNode->GetPosition();
4448       SMDS_TypeOfPosition aTypeOfPosition = aPosition->GetTypeOfPosition();
4449       switch( aTypeOfPosition )
4450       {
4451       case SMDS_TOP_VERTEX : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_VERTEX ));
4452       case SMDS_TOP_EDGE   : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_EDGE ));
4453       case SMDS_TOP_FACE   : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_FACE ));
4454       case SMDS_TOP_3DSPACE: return ( IsContains( myMeshDS,myShape,aNode,TopAbs_SOLID ) ||
4455                                       IsContains( myMeshDS,myShape,aNode,TopAbs_SHELL ));
4456       }
4457     }
4458   }
4459   else
4460   {
4461     if ( const SMDS_MeshElement* anElem = myMeshDS->FindElement( theId ))
4462     {
4463       if ( anElem->getshapeId() < 1 )
4464         return myElementsOnShapePtr->IsSatisfy(theId);
4465
4466       if( myType == SMDSAbs_All )
4467       {
4468         return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE ) ||
4469                  IsContains( myMeshDS,myShape,anElem,TopAbs_FACE ) ||
4470                  IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )||
4471                  IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL ));
4472       }
4473       else if( myType == anElem->GetType() )
4474       {
4475         switch( myType )
4476         {
4477         case SMDSAbs_Edge  : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE ));
4478         case SMDSAbs_Face  : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_FACE ));
4479         case SMDSAbs_Volume: return ( IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )||
4480                                       IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL ));
4481         }
4482       }
4483     }
4484   }
4485
4486   return false;
4487 }
4488
4489 void BelongToGeom::SetType (SMDSAbs_ElementType theType)
4490 {
4491   myType = theType;
4492   init();
4493 }
4494
4495 SMDSAbs_ElementType BelongToGeom::GetType() const
4496 {
4497   return myType;
4498 }
4499
4500 TopoDS_Shape BelongToGeom::GetShape()
4501 {
4502   return myShape;
4503 }
4504
4505 const SMESHDS_Mesh* BelongToGeom::GetMeshDS() const
4506 {
4507   return myMeshDS;
4508 }
4509
4510 void BelongToGeom::SetTolerance (double theTolerance)
4511 {
4512   myTolerance = theTolerance;
4513   if (!myIsSubshape)
4514     init();
4515 }
4516
4517 double BelongToGeom::GetTolerance()
4518 {
4519   return myTolerance;
4520 }
4521
4522 /*
4523   Class       : LyingOnGeom
4524   Description : Predicate for verifying whether entiy lying or partially lying on
4525                 specified geometrical support
4526 */
4527
4528 LyingOnGeom::LyingOnGeom()
4529   : myMeshDS(NULL),
4530     myType(SMDSAbs_All),
4531     myIsSubshape(false),
4532     myTolerance(Precision::Confusion())
4533 {}
4534
4535 void LyingOnGeom::SetMesh( const SMDS_Mesh* theMesh )
4536 {
4537   myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh);
4538   init();
4539 }
4540
4541 void LyingOnGeom::SetGeom( const TopoDS_Shape& theShape )
4542 {
4543   myShape = theShape;
4544   init();
4545 }
4546
4547 void LyingOnGeom::init()
4548 {
4549   if (!myMeshDS || myShape.IsNull()) return;
4550
4551   // is sub-shape of main shape?
4552   TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh();
4553   if (aMainShape.IsNull()) {
4554     myIsSubshape = false;
4555   }
4556   else {
4557     myIsSubshape = myMeshDS->IsGroupOfSubShapes( myShape );
4558   }
4559
4560   if (myIsSubshape)
4561   {
4562     TopTools_IndexedMapOfShape shapes;
4563     TopExp::MapShapes( myShape, shapes );
4564     mySubShapesIDs.Clear();
4565     for ( int i = 1; i <= shapes.Extent(); ++i )
4566     {
4567       int subID = myMeshDS->ShapeToIndex( shapes( i ));
4568       if ( subID > 0 )
4569         mySubShapesIDs.Add( subID );
4570     }
4571   }
4572   else
4573   {
4574     myElementsOnShapePtr.reset(new ElementsOnShape());
4575     myElementsOnShapePtr->SetTolerance(myTolerance);
4576     myElementsOnShapePtr->SetAllNodes(false); // lays on, while true means "belong"
4577     myElementsOnShapePtr->SetMesh(myMeshDS);
4578     myElementsOnShapePtr->SetShape(myShape, myType);
4579   }
4580 }
4581
4582 bool LyingOnGeom::IsSatisfy( long theId )
4583 {
4584   if ( myMeshDS == 0 || myShape.IsNull() )
4585     return false;
4586
4587   if (!myIsSubshape)
4588   {
4589     return myElementsOnShapePtr->IsSatisfy(theId);
4590   }
4591
4592   // Case of sub-mesh
4593
4594   const SMDS_MeshElement* elem =
4595     ( myType == SMDSAbs_Node ) ? myMeshDS->FindNode( theId ) : myMeshDS->FindElement( theId );
4596
4597   if ( mySubShapesIDs.Contains( elem->getshapeId() ))
4598     return true;
4599
4600   if ( elem->GetType() != SMDSAbs_Node )
4601   {
4602     SMDS_ElemIteratorPtr nodeItr = elem->nodesIterator();
4603     while ( nodeItr->more() )
4604     {
4605       const SMDS_MeshElement* aNode = nodeItr->next();
4606       if ( mySubShapesIDs.Contains( aNode->getshapeId() ))
4607         return true;
4608     }
4609   }
4610
4611   return false;
4612 }
4613
4614 void LyingOnGeom::SetType( SMDSAbs_ElementType theType )
4615 {
4616   myType = theType;
4617   init();
4618 }
4619
4620 SMDSAbs_ElementType LyingOnGeom::GetType() const
4621 {
4622   return myType;
4623 }
4624
4625 TopoDS_Shape LyingOnGeom::GetShape()
4626 {
4627   return myShape;
4628 }
4629
4630 const SMESHDS_Mesh* LyingOnGeom::GetMeshDS() const
4631 {
4632   return myMeshDS;
4633 }
4634
4635 void LyingOnGeom::SetTolerance (double theTolerance)
4636 {
4637   myTolerance = theTolerance;
4638   if (!myIsSubshape)
4639     init();
4640 }
4641
4642 double LyingOnGeom::GetTolerance()
4643 {
4644   return myTolerance;
4645 }
4646
4647 bool LyingOnGeom::Contains( const SMESHDS_Mesh*     theMeshDS,
4648                             const TopoDS_Shape&     theShape,
4649                             const SMDS_MeshElement* theElem,
4650                             TopAbs_ShapeEnum        theFindShapeEnum,
4651                             TopAbs_ShapeEnum        theAvoidShapeEnum )
4652 {
4653   // if (IsContains(theMeshDS, theShape, theElem, theFindShapeEnum, theAvoidShapeEnum))
4654   //   return true;
4655
4656   // TopTools_MapOfShape aSubShapes;
4657   // TopExp_Explorer exp( theShape, theFindShapeEnum, theAvoidShapeEnum );
4658   // for ( ; exp.More(); exp.Next() )
4659   // {
4660   //   const TopoDS_Shape& aShape = exp.Current();
4661   //   if ( !aSubShapes.Add( aShape )) continue;
4662
4663   //   if ( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape ))
4664   //   {
4665   //     if ( aSubMesh->Contains( theElem ))
4666   //       return true;
4667
4668   //     SMDS_ElemIteratorPtr nodeItr = theElem->nodesIterator();
4669   //     while ( nodeItr->more() )
4670   //     {
4671   //       const SMDS_MeshElement* aNode = nodeItr->next();
4672   //       if ( aSubMesh->Contains( aNode ))
4673   //         return true;
4674   //     }
4675   //   }
4676   // }
4677   return false;
4678 }
4679
4680 TSequenceOfXYZ::TSequenceOfXYZ(): myElem(0)
4681 {}
4682
4683 TSequenceOfXYZ::TSequenceOfXYZ(size_type n) : myArray(n), myElem(0)
4684 {}
4685
4686 TSequenceOfXYZ::TSequenceOfXYZ(size_type n, const gp_XYZ& t) : myArray(n,t), myElem(0)
4687 {}
4688
4689 TSequenceOfXYZ::TSequenceOfXYZ(const TSequenceOfXYZ& theSequenceOfXYZ) : myArray(theSequenceOfXYZ.myArray), myElem(theSequenceOfXYZ.myElem)
4690 {}
4691
4692 template <class InputIterator>
4693 TSequenceOfXYZ::TSequenceOfXYZ(InputIterator theBegin, InputIterator theEnd): myArray(theBegin,theEnd), myElem(0)
4694 {}
4695
4696 TSequenceOfXYZ::~TSequenceOfXYZ()
4697 {}
4698
4699 TSequenceOfXYZ& TSequenceOfXYZ::operator=(const TSequenceOfXYZ& theSequenceOfXYZ)
4700 {
4701   myArray = theSequenceOfXYZ.myArray;
4702   myElem  = theSequenceOfXYZ.myElem;
4703   return *this;
4704 }
4705
4706 gp_XYZ& TSequenceOfXYZ::operator()(size_type n)
4707 {
4708   return myArray[n-1];
4709 }
4710
4711 const gp_XYZ& TSequenceOfXYZ::operator()(size_type n) const
4712 {
4713   return myArray[n-1];
4714 }
4715
4716 void TSequenceOfXYZ::clear()
4717 {
4718   myArray.clear();
4719 }
4720
4721 void TSequenceOfXYZ::reserve(size_type n)
4722 {
4723   myArray.reserve(n);
4724 }
4725
4726 void TSequenceOfXYZ::push_back(const gp_XYZ& v)
4727 {
4728   myArray.push_back(v);
4729 }
4730
4731 TSequenceOfXYZ::size_type TSequenceOfXYZ::size() const
4732 {
4733   return myArray.size();
4734 }
4735
4736 SMDSAbs_EntityType TSequenceOfXYZ::getElementEntity() const
4737 {
4738   return myElem ? myElem->GetEntityType() : SMDSEntity_Last;
4739 }
4740
4741 TMeshModifTracer::TMeshModifTracer():
4742   myMeshModifTime(0), myMesh(0)
4743 {
4744 }
4745 void TMeshModifTracer::SetMesh( const SMDS_Mesh* theMesh )
4746 {
4747   if ( theMesh != myMesh )
4748     myMeshModifTime = 0;
4749   myMesh = theMesh;
4750 }
4751 bool TMeshModifTracer::IsMeshModified()
4752 {
4753   bool modified = false;
4754   if ( myMesh )
4755   {
4756     modified = ( myMeshModifTime != myMesh->GetMTime() );
4757     myMeshModifTime = myMesh->GetMTime();
4758   }
4759   return modified;
4760 }