Salome HOME
fd3a5bb10f8376a3dbb7789039c964905b7facd3
[modules/smesh.git] / src / StdMeshers / StdMeshers_QuadToTriaAdaptor.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_QuadToTriaAdaptor.cxx
21 // Module    : SMESH
22 // Created   : Wen May 07 16:37:07 2008
23 // Author    : Sergey KUUL (skl)
24
25 #include "StdMeshers_QuadToTriaAdaptor.hxx"
26
27 #include "SMDS_IteratorOnIterators.hxx"
28 #include "SMDS_SetIterator.hxx"
29 #include "SMESHDS_GroupBase.hxx"
30 #include "SMESHDS_Mesh.hxx"
31 #include "SMESH_Algo.hxx"
32 #include "SMESH_Group.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_MeshAlgos.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_subMesh.hxx"
37
38 #include <IntAna_IntConicQuad.hxx>
39 #include <IntAna_Quadric.hxx>
40 #include <TColgp_Array1OfPnt.hxx>
41 #include <TColgp_Array1OfVec.hxx>
42 #include <TColgp_SequenceOfPnt.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopoDS.hxx>
45 #include <TopoDS_Iterator.hxx>
46 #include <gp_Lin.hxx>
47 #include <gp_Pln.hxx>
48
49 #include "utilities.h"
50
51 #include <string>
52 #include <numeric>
53 #include <limits>
54
55 using namespace std;
56
57 enum EQuadNature { NOT_QUAD, QUAD, DEGEN_QUAD, PYRAM_APEX = 4, TRIA_APEX = 0 };
58
59 // std-like iterator used to get coordinates of nodes of mesh element
60 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
61
62 namespace
63 {
64   //================================================================================
65   /*!
66    * \brief Return true if two nodes of triangles are equal
67    */
68   //================================================================================
69
70   bool EqualTriangles(const SMDS_MeshElement* F1,const SMDS_MeshElement* F2)
71   {
72     return
73       ( F1->GetNode(1)==F2->GetNode(2) && F1->GetNode(2)==F2->GetNode(1) ) ||
74       ( F1->GetNode(1)==F2->GetNode(1) && F1->GetNode(2)==F2->GetNode(2) );
75   }
76   //================================================================================
77   /*!
78    * \brief Return true if two adjacent pyramids are too close one to another
79    * so that a tetrahedron to built between them would have too poor quality
80    */
81   //================================================================================
82
83   bool TooCloseAdjacent( const SMDS_MeshElement* PrmI,
84                          const SMDS_MeshElement* PrmJ,
85                          const bool              hasShape)
86   {
87     const SMDS_MeshNode* nApexI = PrmI->GetNode(4);
88     const SMDS_MeshNode* nApexJ = PrmJ->GetNode(4);
89     if ( nApexI == nApexJ ||
90          nApexI->getshapeId() != nApexJ->getshapeId() )
91       return false;
92
93     // Find two common base nodes and their indices within PrmI and PrmJ
94     const SMDS_MeshNode* baseNodes[2] = { 0,0 };
95     int baseNodesIndI[2], baseNodesIndJ[2];
96     for ( int i = 0; i < 4 ; ++i )
97     {
98       int j = PrmJ->GetNodeIndex( PrmI->GetNode(i));
99       if ( j >= 0 )
100       {
101         int ind = baseNodes[0] ? 1:0;
102         if ( baseNodes[ ind ])
103           return false; // pyramids with a common base face
104         baseNodes    [ ind ] = PrmI->GetNode(i);
105         baseNodesIndI[ ind ] = i;
106         baseNodesIndJ[ ind ] = j;
107       }
108     }
109     if ( !baseNodes[1] ) return false; // not adjacent
110
111     // Get normals of triangles sharing baseNodes
112     gp_XYZ apexI = SMESH_TNodeXYZ( nApexI );
113     gp_XYZ apexJ = SMESH_TNodeXYZ( nApexJ );
114     gp_XYZ base1 = SMESH_TNodeXYZ( baseNodes[0]);
115     gp_XYZ base2 = SMESH_TNodeXYZ( baseNodes[1]);
116     gp_Vec baseVec( base1, base2 );
117     gp_Vec baI( base1, apexI );
118     gp_Vec baJ( base1, apexJ );
119     gp_Vec nI = baseVec.Crossed( baI );
120     gp_Vec nJ = baseVec.Crossed( baJ );
121
122     // Check angle between normals
123     double  angle = nI.Angle( nJ );
124     bool tooClose = ( angle < 15. * M_PI / 180. );
125
126     // Check if pyramids collide
127     if ( !tooClose && ( baI * baJ > 0 ) && ( nI * nJ > 0 ))
128     {
129       // find out if nI points outside of PrmI or inside
130       int    dInd = baseNodesIndI[1] - baseNodesIndI[0];
131       bool isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
132
133       // find out sign of projection of baI to nJ
134       double proj = baI * nJ;
135
136       tooClose = ( isOutI ? proj > 0 : proj < 0 );
137     }
138
139     // Check if PrmI and PrmJ are in same domain
140     if ( tooClose && !hasShape )
141     {
142       // check order of baseNodes within pyramids, it must be opposite
143       int dInd;
144       dInd = baseNodesIndI[1] - baseNodesIndI[0];
145       bool isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
146       dInd = baseNodesIndJ[1] - baseNodesIndJ[0];
147       bool isOutJ = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
148       if ( isOutJ == isOutI )
149         return false; // other domain
150
151       // direct both normals outside pyramid
152       ( isOutI ? nJ : nI ).Reverse();
153
154       // check absence of a face separating domains between pyramids
155       TIDSortedElemSet emptySet, avoidSet;
156       int i1, i2;
157       while ( const SMDS_MeshElement* f =
158               SMESH_MeshAlgos::FindFaceInSet( baseNodes[0], baseNodes[1],
159                                               emptySet, avoidSet, &i1, &i2 ))
160       {
161         avoidSet.insert( f );
162
163         // face node other than baseNodes
164         int otherNodeInd = 0;
165         while ( otherNodeInd == i1 || otherNodeInd == i2 ) otherNodeInd++;
166         const SMDS_MeshNode* otherFaceNode = f->GetNode( otherNodeInd );
167
168         if ( otherFaceNode == nApexI || otherFaceNode == nApexJ )
169           continue; // f is a temporary triangle
170
171         // check if f is a base face of either of pyramids
172         if ( f->NbCornerNodes() == 4 &&
173              ( PrmI->GetNodeIndex( otherFaceNode ) >= 0 ||
174                PrmJ->GetNodeIndex( otherFaceNode ) >= 0 ))
175           continue; // f is a base quadrangle
176
177         // check projections of face direction (baOFN) to triange normals (nI and nJ)
178         gp_Vec baOFN( base2, SMESH_TNodeXYZ( otherFaceNode ));
179         if ( nI * baOFN > 0 && nJ * baOFN > 0 &&
180              baI* baOFN > 0 && baJ* baOFN > 0 ) // issue 0023212
181         {
182           tooClose = false; // f is between pyramids
183           break;
184         }
185       }
186     }
187
188     return tooClose;
189   }
190
191   //================================================================================
192   /*!
193    * \brief Move medium nodes of merged quadratic pyramids
194    */
195   //================================================================================
196
197   void UpdateQuadraticPyramids(const set<const SMDS_MeshNode*>& commonApex,
198                                SMESHDS_Mesh*                    meshDS)
199   {
200     typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
201     TStdElemIterator itEnd;
202
203     // shift of node index to get medium nodes between the 4 base nodes and the apex
204     const int base2MediumShift = 9;
205
206     set<const SMDS_MeshNode*>::const_iterator nIt = commonApex.begin();
207     for ( ; nIt != commonApex.end(); ++nIt )
208     {
209       SMESH_TNodeXYZ apex( *nIt );
210
211       vector< const SMDS_MeshElement* > pyrams // pyramids sharing the apex node
212         ( TStdElemIterator( apex._node->GetInverseElementIterator( SMDSAbs_Volume )), itEnd );
213
214       // Select medium nodes to keep and medium nodes to remove
215
216       typedef map < const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
217       TN2NMap base2medium; // to keep
218       vector< const SMDS_MeshNode* > nodesToRemove;
219
220       for ( unsigned i = 0; i < pyrams.size(); ++i )
221         for ( int baseIndex = 0; baseIndex < PYRAM_APEX; ++baseIndex )
222         {
223           SMESH_TNodeXYZ         base = pyrams[i]->GetNode( baseIndex );
224           const SMDS_MeshNode* medium = pyrams[i]->GetNode( baseIndex + base2MediumShift );
225           TN2NMap::iterator b2m = base2medium.insert( make_pair( base._node, medium )).first;
226           if ( b2m->second != medium )
227           {
228             nodesToRemove.push_back( medium );
229           }
230           else
231           {
232             // move the kept medium node
233             gp_XYZ newXYZ = 0.5 * ( apex + base );
234             meshDS->MoveNode( medium, newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
235           }
236         }
237
238       // Within pyramids, replace nodes to remove by nodes to keep
239
240       for ( unsigned i = 0; i < pyrams.size(); ++i )
241       {
242         vector< const SMDS_MeshNode* > nodes( pyrams[i]->begin_nodes(),
243                                               pyrams[i]->end_nodes() );
244         for ( int baseIndex = 0; baseIndex < PYRAM_APEX; ++baseIndex )
245         {
246           const SMDS_MeshNode* base = pyrams[i]->GetNode( baseIndex );
247           nodes[ baseIndex + base2MediumShift ] = base2medium[ base ];
248         }
249         meshDS->ChangeElementNodes( pyrams[i], &nodes[0], nodes.size());
250       }
251
252       // Remove the replaced nodes
253
254       if ( !nodesToRemove.empty() )
255       {
256         SMESHDS_SubMesh * sm = meshDS->MeshElements( nodesToRemove[0]->getshapeId() );
257         for ( unsigned i = 0; i < nodesToRemove.size(); ++i )
258           meshDS->RemoveFreeNode( nodesToRemove[i], sm, /*fromGroups=*/false);
259       }
260     }
261   }
262
263   //================================================================================
264   /*!
265    * \brief Store an error about overlapping faces
266    */
267   //================================================================================
268
269   bool overlapError( SMESH_Mesh&             mesh,
270                      const SMDS_MeshElement* face1,
271                      const SMDS_MeshElement* face2,
272                      const TopoDS_Shape&     shape = TopoDS_Shape())
273   {
274     if ( !face1 || !face2 ) return false;
275
276     SMESH_Comment msg;
277     msg << "face " << face1->GetID() << " overlaps face " << face2->GetID();
278
279     SMESH_subMesh * sm = 0;
280     if ( shape.IsNull() )
281     {
282       sm = mesh.GetSubMesh( mesh.GetShapeToMesh() );
283     }
284     else if ( shape.ShapeType() >= TopAbs_SOLID )
285     {
286       sm = mesh.GetSubMesh( shape );
287     }
288     else
289     {
290       TopoDS_Iterator it ( shape );
291       if ( it.More() )
292         sm = mesh.GetSubMesh( it.Value() );
293     }
294     if ( sm )
295     {
296       SMESH_ComputeErrorPtr& err = sm->GetComputeError();
297       if ( !err || err->IsOK() )
298       {
299         SMESH_BadInputElements* badElems =
300           new SMESH_BadInputElements( mesh.GetMeshDS(),COMPERR_BAD_INPUT_MESH, msg, sm->GetAlgo() );
301         badElems->add( face1 );
302         badElems->add( face2 );
303         err.reset( badElems );
304       }
305     }
306
307     return false; // == "algo fails"
308   }
309 }
310
311 //================================================================================
312 /*!
313  * \brief Merge the two pyramids (i.e. fuse their apex) and others already merged with them
314  */
315 //================================================================================
316
317 void StdMeshers_QuadToTriaAdaptor::MergePiramids( const SMDS_MeshElement*     PrmI,
318                                                   const SMDS_MeshElement*     PrmJ,
319                                                   set<const SMDS_MeshNode*> & nodesToMove)
320 {
321   // cout << endl << "Merge " << PrmI->GetID() << " " << PrmJ->GetID() << " "
322   //      << PrmI->GetNode(4) << PrmJ->GetNode(4) << endl;
323   const SMDS_MeshNode* Nrem = PrmJ->GetNode(4); // node to remove
324   //int nbJ = Nrem->NbInverseElements( SMDSAbs_Volume );
325   SMESH_TNodeXYZ Pj( Nrem );
326
327   // an apex node to make common to all merged pyramids
328   SMDS_MeshNode* CommonNode = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
329   if ( CommonNode == Nrem ) return; // already merged
330   //int nbI = CommonNode->NbInverseElements( SMDSAbs_Volume );
331   SMESH_TNodeXYZ Pi( CommonNode );
332   gp_XYZ Pnew = /*( nbI*Pi + nbJ*Pj ) / (nbI+nbJ);*/ 0.5 * ( Pi + Pj );
333   CommonNode->setXYZ( Pnew.X(), Pnew.Y(), Pnew.Z() );
334
335   nodesToMove.insert( CommonNode );
336   nodesToMove.erase ( Nrem );
337
338   typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
339   TStdElemIterator itEnd;
340
341   // find and remove coincided faces of merged pyramids
342   vector< const SMDS_MeshElement* > inverseElems
343     // copy inverse elements to avoid iteration on changing container
344     ( TStdElemIterator( CommonNode->GetInverseElementIterator(SMDSAbs_Face)), itEnd);
345   for ( size_t i = 0; i < inverseElems.size(); ++i )
346   {
347     const SMDS_MeshElement* FI = inverseElems[i];
348     const SMDS_MeshElement* FJEqual = 0;
349     SMDS_ElemIteratorPtr triItJ = Nrem->GetInverseElementIterator(SMDSAbs_Face);
350     while ( !FJEqual && triItJ->more() )
351     {
352       const SMDS_MeshElement* FJ = triItJ->next();
353       if ( EqualTriangles( FJ, FI ))
354         FJEqual = FJ;
355     }
356     if ( FJEqual )
357     {
358       removeTmpElement( FI );
359       removeTmpElement( FJEqual );
360       myRemovedTrias.insert( FI );
361       myRemovedTrias.insert( FJEqual );
362     }
363   }
364
365   // set the common apex node to pyramids and triangles merged with J
366   vector< const SMDS_MeshNode* > nodes;
367   inverseElems.assign( TStdElemIterator( Nrem->GetInverseElementIterator()), itEnd );
368   for ( size_t i = 0; i < inverseElems.size(); ++i )
369   {
370     const SMDS_MeshElement* elem = inverseElems[i];
371     nodes.assign( elem->begin_nodes(), elem->end_nodes() );
372     nodes[ elem->GetType() == SMDSAbs_Volume ? PYRAM_APEX : TRIA_APEX ] = CommonNode;
373     GetMeshDS()->ChangeElementNodes( elem, &nodes[0], nodes.size());
374   }
375   ASSERT( Nrem->NbInverseElements() == 0 );
376   GetMeshDS()->RemoveFreeNode( Nrem,
377                                GetMeshDS()->MeshElements( Nrem->getshapeId()),
378                                /*fromGroups=*/false);
379 }
380
381 //================================================================================
382 /*!
383  * \brief Merges adjacent pyramids
384  */
385 //================================================================================
386
387 void StdMeshers_QuadToTriaAdaptor::MergeAdjacent(const SMDS_MeshElement*    PrmI,
388                                                  set<const SMDS_MeshNode*>& nodesToMove,
389                                                  const bool                 isRecursion)
390 {
391   TIDSortedElemSet adjacentPyrams;
392   bool mergedPyrams = false;
393   for ( int k=0; k<4; k++ ) // loop on 4 base nodes of PrmI
394   {
395     const SMDS_MeshNode*   n = PrmI->GetNode(k);
396     SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
397     while ( vIt->more() )
398     {
399       const SMDS_MeshElement* PrmJ = vIt->next();
400       if ( PrmJ == PrmI || PrmJ->NbCornerNodes() != 5 || !adjacentPyrams.insert( PrmJ ).second  )
401         continue;
402       if ( TooCloseAdjacent( PrmI, PrmJ, GetMesh()->HasShapeToMesh() ))
403       {
404         MergePiramids( PrmI, PrmJ, nodesToMove );
405         mergedPyrams = true;
406         // container of inverse elements can change
407         // vIt = n->GetInverseElementIterator( SMDSAbs_Volume ); -- iterator re-implemented
408       }
409     }
410   }
411   if ( mergedPyrams && !isRecursion )
412   {
413     TIDSortedElemSet::iterator prm;
414     for (prm = adjacentPyrams.begin(); prm != adjacentPyrams.end(); ++prm)
415       MergeAdjacent( *prm, nodesToMove, true );
416   }
417 }
418
419 //================================================================================
420 /*!
421  * \brief Constructor
422  */
423 //================================================================================
424
425 StdMeshers_QuadToTriaAdaptor::StdMeshers_QuadToTriaAdaptor():
426   myElemSearcher(0)
427 {
428 }
429
430 //================================================================================
431 /*!
432  * \brief Destructor
433  */
434 //================================================================================
435
436 StdMeshers_QuadToTriaAdaptor::~StdMeshers_QuadToTriaAdaptor()
437 {
438   // temporary faces are deleted by ~SMESH_ProxyMesh()
439   if ( myElemSearcher ) delete myElemSearcher;
440   myElemSearcher=0;
441 }
442
443 //=======================================================================
444 //function : FindBestPoint
445 //purpose  : Return a point P laying on the line (PC,V) so that triangle
446 //           (P, P1, P2) to be equilateral as much as possible
447 //           V - normal to (P1,P2,PC)
448 //=======================================================================
449
450 static gp_Pnt FindBestPoint(const gp_Pnt& P1, const gp_Pnt& P2,
451                             const gp_Pnt& PC, const gp_Vec& V)
452 {
453   gp_Pnt Pbest = PC;
454   const double a2 = P1.SquareDistance(P2);
455   const double b2 = P1.SquareDistance(PC);
456   const double c2 = P2.SquareDistance(PC);
457   if ( a2 < ( b2 + Sqrt( 4 * b2 * c2 ) + c2 ) / 4 ) // ( a < (b+c)/2 )
458     return Pbest;
459   else {
460     // find shift along V in order a to became equal to (b+c)/2
461     const double Vsize = V.Magnitude();
462     if ( fabs( Vsize ) > std::numeric_limits<double>::min() )
463     {
464       const double shift = sqrt( a2 + (b2-c2)*(b2-c2)/16/a2 - (b2+c2)/2 );
465       Pbest.ChangeCoord() += shift * V.XYZ() / Vsize;
466     }
467   }
468   return Pbest;
469 }
470
471 //=======================================================================
472 //function : HasIntersection3
473 //purpose  : Find intersection point between a triangle (P1,P2,P3)
474 //           and a segment [PC,P]
475 //=======================================================================
476
477 static bool HasIntersection3(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
478                              const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3)
479 {
480   const double EPSILON = 1e-6;
481   double segLen = P.Distance( PC );
482
483   gp_XYZ  orig = PC.XYZ();
484   gp_XYZ   dir = ( P.XYZ() - PC.XYZ() ) / segLen;
485   gp_XYZ vert0 = P1.XYZ();
486   gp_XYZ vert1 = P2.XYZ();
487   gp_XYZ vert2 = P3.XYZ();
488
489   gp_XYZ edge1 = vert1 - vert0;
490   gp_XYZ edge2 = vert2 - vert0;
491
492   /* begin calculating determinant - also used to calculate U parameter */
493   gp_XYZ pvec = dir ^ edge2;
494
495   /* if determinant is near zero, ray lies in plane of triangle */
496   double det = edge1 * pvec;
497
498   const double ANGL_EPSILON = 1e-12;
499   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
500     return false;
501
502   /* calculate distance from vert0 to ray origin */
503   gp_XYZ  tvec = orig - vert0;
504
505   /* calculate U parameter and test bounds */
506   double u = ( tvec * pvec ) / det;
507   //if (u < 0.0 || u > 1.0)
508   if (u < -EPSILON || u > 1.0 + EPSILON)
509     return false;
510
511   /* prepare to test V parameter */
512   gp_XYZ qvec = tvec ^ edge1;
513
514   /* calculate V parameter and test bounds */
515   double v = (dir * qvec) / det;
516   //if ( v < 0.0 || u + v > 1.0 )
517   if ( v < -EPSILON || u + v > 1.0 + EPSILON)
518     return false;
519
520   /* calculate t, ray intersects triangle */
521   double t = (edge2 * qvec) / det;
522
523   Pint = orig + dir * t;
524
525   return ( t > 0.  &&  t < segLen );
526 }
527
528 //=======================================================================
529 //function : HasIntersection
530 //purpose  : Auxilare for CheckIntersection()
531 //=======================================================================
532
533 static bool HasIntersection(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
534                             TColgp_SequenceOfPnt& aContour)
535 {
536   if ( aContour.Length() == 3 ) {
537     return HasIntersection3( P, PC, Pint, aContour(1), aContour(2), aContour(3) );
538   }
539   else {
540     bool check = false;
541     if( (aContour(1).SquareDistance(aContour(2)) > 1.e-12) &&
542         (aContour(1).SquareDistance(aContour(3)) > 1.e-12) &&
543         (aContour(2).SquareDistance(aContour(3)) > 1.e-12) ) {
544       check = HasIntersection3( P, PC, Pint, aContour(1), aContour(2), aContour(3) );
545     }
546     if(check) return true;
547     if( (aContour(1).SquareDistance(aContour(4)) > 1.e-12) &&
548         (aContour(1).SquareDistance(aContour(3)) > 1.e-12) &&
549         (aContour(4).SquareDistance(aContour(3)) > 1.e-12) ) {
550       check = HasIntersection3( P, PC, Pint, aContour(1), aContour(3), aContour(4) );
551     }
552     if(check) return true;
553   }
554
555   return false;
556 }
557
558 //================================================================================
559 /*!
560  * \brief Return allowed height of a pyramid
561  *  \param Papex - optimal pyramid apex
562  *  \param PC - gravity center of a quadrangle
563  *  \param PN - four nodes of the quadrangle
564  *  \param aMesh - mesh
565  *  \param NotCheckedFace - the quadrangle face
566  *  \param Shape - the shape being meshed
567  *  \retval false if mesh invalidity detected
568  */
569 //================================================================================
570
571 bool StdMeshers_QuadToTriaAdaptor::LimitHeight (gp_Pnt&                             Papex,
572                                                 const gp_Pnt&                       PC,
573                                                 const TColgp_Array1OfPnt&           PN,
574                                                 const vector<const SMDS_MeshNode*>& FNodes,
575                                                 SMESH_Mesh&                         aMesh,
576                                                 const SMDS_MeshElement*             NotCheckedFace,
577                                                 const bool                          UseApexRay,
578                                                 const TopoDS_Shape&                 Shape)
579 {
580   if ( !myElemSearcher )
581     myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *aMesh.GetMeshDS() );
582   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
583
584   // Find intersection of faces with (P,PC) segment elongated 3 times
585
586   double height = Papex.Distance( PC );
587   gp_Ax1 line( PC, gp_Vec( PC, Papex ));
588   gp_Pnt Pint, Ptest;
589   vector< const SMDS_MeshElement* > suspectFaces;
590   TColgp_SequenceOfPnt aContour;
591
592   if ( UseApexRay )
593   {
594     double idealHeight = height;
595     const SMDS_MeshElement* intFace = 0;
596
597     // find intersection closest to PC
598     Ptest = PC.XYZ() + line.Direction().XYZ() * height * 3;
599
600     searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces );
601     for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
602     {
603       const SMDS_MeshElement* face = suspectFaces[iF];
604       if ( face == NotCheckedFace ) continue;
605
606       aContour.Clear();
607       for ( int i = 0, nb = face->NbCornerNodes(); i < nb; ++i )
608         aContour.Append( SMESH_TNodeXYZ( face->GetNode(i) ));
609
610       if ( HasIntersection( Ptest, PC, Pint, aContour ))
611       {
612         double dInt = PC.Distance( Pint ) / 3.;
613         if ( dInt < height )
614         {
615           height = dInt;
616           intFace = face;
617         }
618       }
619     }
620     if ( height < 1e-2 * idealHeight && intFace )
621       return overlapError( aMesh, NotCheckedFace, intFace, Shape );
622   }
623
624   // Find faces intersecting triangular facets of the pyramid (issue 23212)
625
626   gp_XYZ center   = PC.XYZ() + line.Direction().XYZ() * height * 0.5;
627   double diameter = Max( PN(1).Distance(PN(3)), PN(2).Distance(PN(4)));
628   suspectFaces.clear();
629   searcher->GetElementsInSphere( center, diameter * 0.6, SMDSAbs_Face, suspectFaces);
630
631   const double upShift = 1.5;
632   Ptest = PC.XYZ() + line.Direction().XYZ() * height * upShift; // tmp apex
633
634   for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
635   {
636     const SMDS_MeshElement* face = suspectFaces[iF];
637     if ( face == NotCheckedFace ) continue;
638     if ( face->GetNodeIndex( FNodes[0] ) >= 0 ||
639          face->GetNodeIndex( FNodes[1] ) >= 0 ||
640          face->GetNodeIndex( FNodes[2] ) >= 0 ||
641          face->GetNodeIndex( FNodes[3] ) >= 0 )
642       continue; // neighbor face of the quadrangle
643
644     // limit height using points of intersection of face links with pyramid facets
645     int   nbN = face->NbCornerNodes();
646     gp_Pnt P1 = SMESH_TNodeXYZ( face->GetNode( nbN-1 )); // 1st link end
647     for ( int i = 0; i < nbN; ++i )
648     {
649       gp_Pnt P2 = SMESH_TNodeXYZ( face->GetNode(i) );    // 2nd link end
650
651       for ( int iN = 1; iN <= 4; ++iN ) // loop on pyramid facets
652       {
653         if ( HasIntersection3( P1, P2, Pint, PN(iN), PN(iN+1), Ptest ))
654         {
655           height = Min( height, gp_Vec( PC, Pint ) * line.Direction() );
656           //Ptest = PC.XYZ() + line.Direction().XYZ() * height * upShift; // new tmp apex
657         }
658       }
659       P1 = P2;
660     }
661   }
662
663   Papex  = PC.XYZ() + line.Direction().XYZ() * height;
664
665   return true;
666 }
667
668 //================================================================================
669 /*!
670  * \brief Prepare data for the given face
671  *  \param PN - coordinates of face nodes
672  *  \param VN - cross products of vectors (PC-PN(i)) ^ (PC-PN(i+1))
673  *  \param FNodes - face nodes
674  *  \param PC - gravity center of nodes
675  *  \param VNorm - face normal (sum of VN)
676  *  \param volumes - two volumes sharing the given face, the first is in VNorm direction
677  *  \retval int - 0 if given face is not quad,
678  *                1 if given face is quad,
679  *                2 if given face is degenerate quad (two nodes are coincided)
680  */
681 //================================================================================
682
683 int StdMeshers_QuadToTriaAdaptor::Preparation(const SMDS_MeshElement*       face,
684                                               TColgp_Array1OfPnt&           PN,
685                                               TColgp_Array1OfVec&           VN,
686                                               vector<const SMDS_MeshNode*>& FNodes,
687                                               gp_Pnt&                       PC,
688                                               gp_Vec&                       VNorm,
689                                               const SMDS_MeshElement**      volumes)
690 {
691   if( face->NbCornerNodes() != 4 )
692   {
693     return NOT_QUAD;
694   }
695
696   int i = 0;
697   gp_XYZ xyzC(0., 0., 0.);
698   for ( i = 0; i < 4; ++i )
699   {
700     gp_XYZ p = SMESH_TNodeXYZ( FNodes[i] = face->GetNode(i) );
701     PN.SetValue( i+1, p );
702     xyzC += p;
703   }
704   PC = xyzC/4;
705
706   int nbp = 4;
707
708   int j = 0;
709   for(i=1; i<4; i++) {
710     j = i+1;
711     for(; j<=4; j++) {
712       if( PN(i).Distance(PN(j)) < 1.e-6 )
713         break;
714     }
715     if(j<=4) break;
716   }
717   //int deg_num = IsDegenarate(PN);
718   //if(deg_num>0) {
719   bool hasdeg = false;
720   if(i<4) {
721     //cout<<"find degeneration"<<endl;
722     hasdeg = true;
723     gp_Pnt Pdeg = PN(i);
724
725     list< const SMDS_MeshNode* >::iterator itdg = myDegNodes.begin();
726     const SMDS_MeshNode* DegNode = 0;
727     for(; itdg!=myDegNodes.end(); itdg++) {
728       const SMDS_MeshNode* N = (*itdg);
729       gp_Pnt Ptmp(N->X(),N->Y(),N->Z());
730       if(Pdeg.Distance(Ptmp)<1.e-6) {
731         DegNode = N;
732         //DegNode = const_cast<SMDS_MeshNode*>(N);
733         break;
734       }
735     }
736     if(!DegNode) {
737       DegNode = FNodes[i-1];
738       myDegNodes.push_back(DegNode);
739     }
740     else {
741       FNodes[i-1] = DegNode;
742     }
743     for(i=j; i<4; i++) {
744       PN.SetValue(i,PN.Value(i+1));
745       FNodes[i-1] = FNodes[i];
746     }
747     nbp = 3;
748   }
749
750   PN.SetValue(nbp+1,PN(1));
751   FNodes[nbp] = FNodes[0];
752   // find normal direction
753   gp_Vec V1(PC,PN(nbp));
754   gp_Vec V2(PC,PN(1));
755   VNorm = V1.Crossed(V2);
756   VN.SetValue(nbp,VNorm);
757   for(i=1; i<nbp; i++) {
758     V1 = gp_Vec(PC,PN(i));
759     V2 = gp_Vec(PC,PN(i+1));
760     gp_Vec Vtmp = V1.Crossed(V2);
761     VN.SetValue(i,Vtmp);
762     VNorm += Vtmp;
763   }
764
765   // find volumes sharing the face
766   if ( volumes )
767   {
768     volumes[0] = volumes[1] = 0;
769     SMDS_ElemIteratorPtr vIt = FNodes[0]->GetInverseElementIterator( SMDSAbs_Volume );
770     while ( vIt->more() )
771     {
772       const SMDS_MeshElement* vol = vIt->next();
773       bool volSharesAllNodes = true;
774       for ( int i = 1; i < face->NbNodes() && volSharesAllNodes; ++i )
775         volSharesAllNodes = ( vol->GetNodeIndex( FNodes[i] ) >= 0 );
776       if ( volSharesAllNodes )
777         volumes[ volumes[0] ? 1 : 0 ] = vol;
778       // we could additionally check that vol has all FNodes in its one face using SMDS_VolumeTool
779     }
780     // define volume position relating to the face normal
781     if ( volumes[0] )
782     {
783       // get volume gc
784       SMDS_ElemIteratorPtr nodeIt = volumes[0]->nodesIterator();
785       gp_XYZ volGC(0,0,0);
786       volGC = accumulate( TXyzIterator(nodeIt), TXyzIterator(), volGC ) / volumes[0]->NbNodes();
787
788       if ( VNorm * gp_Vec( PC, volGC ) < 0 )
789         swap( volumes[0], volumes[1] );
790     }
791   }
792
793   //cout<<"  VNorm("<<VNorm.X()<<","<<VNorm.Y()<<","<<VNorm.Z()<<")"<<endl;
794   return hasdeg ? DEGEN_QUAD : QUAD;
795 }
796
797
798 //=======================================================================
799 //function : Compute
800 //purpose  :
801 //=======================================================================
802
803 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh&         aMesh,
804                                            const TopoDS_Shape& aShape,
805                                            SMESH_ProxyMesh*    aProxyMesh)
806 {
807   SMESH_ProxyMesh::setMesh( aMesh );
808
809   if ( aShape.ShapeType() != TopAbs_SOLID &&
810        aShape.ShapeType() != TopAbs_SHELL )
811     return false;
812
813   myShape = aShape;
814
815   vector<const SMDS_MeshElement*> myPyramids;
816
817   const SMESHDS_SubMesh * aSubMeshDSFace;
818   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
819   SMESH_MesherHelper helper(aMesh);
820   helper.IsQuadraticSubMesh(aShape);
821   helper.SetElementsOnShape( true );
822
823   if ( myElemSearcher ) delete myElemSearcher;
824   vector< SMDS_ElemIteratorPtr > itVec;
825   if ( aProxyMesh )
826   {
827     itVec.push_back( aProxyMesh->GetFaces( aShape ));
828   }
829   else
830   {
831     for ( TopExp_Explorer exp(aShape,TopAbs_FACE); exp.More(); exp.Next() )
832       if (( aSubMeshDSFace = meshDS->MeshElements( exp.Current() )))
833         itVec.push_back( aSubMeshDSFace->GetElements() );
834   }
835   typedef
836     SMDS_IteratorOnIterators< const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIter;
837   SMDS_ElemIteratorPtr faceIt( new TIter( itVec ));
838   myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS, faceIt );
839
840   TColgp_Array1OfPnt PN(1,5);
841   TColgp_Array1OfVec VN(1,4);
842   vector<const SMDS_MeshNode*> FNodes(5);
843   gp_Pnt PC;
844   gp_Vec VNorm;
845
846   for ( TopExp_Explorer exp(aShape,TopAbs_FACE); exp.More(); exp.Next() )
847   {
848     const TopoDS_Shape& aShapeFace = exp.Current();
849     if ( aProxyMesh )
850       aSubMeshDSFace = aProxyMesh->GetSubMesh( aShapeFace );
851     else
852       aSubMeshDSFace = meshDS->MeshElements( aShapeFace );
853
854     vector<const SMDS_MeshElement*> trias, quads;
855     bool hasNewTrias = false;
856
857     if ( aSubMeshDSFace )
858     {
859       bool isRev = false;
860       if ( helper.NbAncestors( aShapeFace, aMesh, aShape.ShapeType() ) > 1 )
861         isRev = helper.IsReversedSubMesh( TopoDS::Face(aShapeFace) );
862
863       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
864       while ( iteratorElem->more() ) // loop on elements on a geometrical face
865       {
866         const SMDS_MeshElement* face = iteratorElem->next();
867         // preparation step to get face info
868         int stat = Preparation(face, PN, VN, FNodes, PC, VNorm);
869         switch ( stat )
870         {
871         case NOT_QUAD:
872
873           trias.push_back( face );
874           break;
875
876         case DEGEN_QUAD:
877           {
878             // degenerate face
879             // add triangles to result map
880             SMDS_MeshFace* NewFace;
881             if(!isRev)
882               NewFace = meshDS->AddFace( FNodes[0], FNodes[1], FNodes[2] );
883             else
884               NewFace = meshDS->AddFace( FNodes[0], FNodes[2], FNodes[1] );
885             storeTmpElement( NewFace );
886             trias.push_back ( NewFace );
887             quads.push_back( face );
888             hasNewTrias = true;
889             break;
890           }
891
892         case QUAD:
893           {
894             if(!isRev) VNorm.Reverse();
895             double xc = 0., yc = 0., zc = 0.;
896             int i = 1;
897             for(; i<=4; i++) {
898               gp_Pnt Pbest;
899               if(!isRev)
900                 Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i).Reversed());
901               else
902                 Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i));
903               xc += Pbest.X();
904               yc += Pbest.Y();
905               zc += Pbest.Z();
906             }
907             gp_Pnt PCbest(xc/4., yc/4., zc/4.);
908
909             // check PCbest
910             double height = PCbest.Distance(PC);
911             if ( height < 1.e-6 ) {
912               // create new PCbest using a bit shift along VNorm
913               PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
914             }
915             else {
916               // check possible intersection with other faces
917               if ( !LimitHeight( PCbest, PC, PN, FNodes, aMesh, face, /*UseApexRay=*/true, aShape ))
918                 return false;
919             }
920             // create node for PCbest
921             SMDS_MeshNode* NewNode = helper.AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
922
923             // add triangles to result map
924             for(i=0; i<4; i++)
925             {
926               trias.push_back ( meshDS->AddFace( NewNode, FNodes[i], FNodes[i+1] ));
927               storeTmpElement( trias.back() );
928             }
929             // create a pyramid
930             if ( isRev ) swap( FNodes[1], FNodes[3]);
931             SMDS_MeshVolume* aPyram =
932               helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
933             myPyramids.push_back(aPyram);
934
935             quads.push_back( face );
936             hasNewTrias = true;
937             break;
938
939           } // case QUAD:
940
941         } // switch ( stat )
942       } // end loop on elements on a face submesh
943
944       bool sourceSubMeshIsProxy = false;
945       if ( aProxyMesh )
946       {
947         // move proxy sub-mesh from other proxy mesh to this
948         sourceSubMeshIsProxy = takeProxySubMesh( aShapeFace, aProxyMesh );
949         // move also tmp elements added in mesh
950         takeTmpElemsInMesh( aProxyMesh );
951       }
952       if ( hasNewTrias )
953       {
954         SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh( aShapeFace );
955         prxSubMesh->ChangeElements( trias.begin(), trias.end() );
956
957         // delete tmp quadrangles removed from aProxyMesh
958         if ( sourceSubMeshIsProxy )
959         {
960           for ( unsigned i = 0; i < quads.size(); ++i )
961             removeTmpElement( quads[i] );
962
963           delete myElemSearcher;
964           myElemSearcher =
965             SMESH_MeshAlgos::GetElementSearcher( *meshDS, aProxyMesh->GetFaces(aShape));
966         }
967       }
968     }
969   } // end for(TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
970
971   return Compute2ndPart(aMesh, myPyramids);
972 }
973
974 //================================================================================
975 /*!
976  * \brief Computes pyramids in mesh with no shape
977  */
978 //================================================================================
979
980 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh)
981 {
982   SMESH_ProxyMesh::setMesh( aMesh );
983   SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Triangle );
984   SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Quad_Triangle );
985   if ( aMesh.NbQuadrangles() < 1 )
986     return false;
987
988   // find if there is a group of faces identified as skin faces, with normal going outside the volume
989   std::string groupName = "skinFaces";
990   SMESHDS_GroupBase* groupDS = 0;
991   SMESH_Mesh::GroupIteratorPtr groupIt = aMesh.GetGroups();
992   while ( groupIt->more() )
993   {
994     groupDS = 0;
995     SMESH_Group * group = groupIt->next();
996     if ( !group ) continue;
997     groupDS = group->GetGroupDS();
998     if ( !groupDS || groupDS->IsEmpty() )
999     {
1000       groupDS = 0;
1001       continue;
1002     }
1003     if (groupDS->GetType() != SMDSAbs_Face)
1004     {
1005       groupDS = 0;
1006       continue;
1007     }
1008     std::string grpName = group->GetName();
1009     if (grpName == groupName)
1010     {
1011       break;
1012     }
1013     else
1014       groupDS = 0;
1015   }
1016
1017   const bool toFindVolumes = aMesh.NbVolumes() > 0;
1018
1019   vector<const SMDS_MeshElement*> myPyramids;
1020   SMESH_MesherHelper helper(aMesh);
1021   helper.IsQuadraticSubMesh(aMesh.GetShapeToMesh());
1022   helper.SetElementsOnShape( true );
1023
1024   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1025   SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh();
1026
1027   if ( !myElemSearcher )
1028     myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS );
1029   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
1030   SMESHUtils::Deleter<SMESH_ElementSearcher>
1031     volSearcher( SMESH_MeshAlgos::GetElementSearcher( *meshDS ));
1032   vector< const SMDS_MeshElement* > suspectFaces, foundVolumes;
1033
1034   TColgp_Array1OfPnt PN(1,5);
1035   TColgp_Array1OfVec VN(1,4);
1036   vector<const SMDS_MeshNode*> FNodes(5);
1037   TColgp_SequenceOfPnt aContour;
1038
1039   SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
1040   while( fIt->more())
1041   {
1042     const SMDS_MeshElement* face = fIt->next();
1043     if ( !face ) continue;
1044     // retrieve needed information about a face
1045     gp_Pnt PC;
1046     gp_Vec VNorm;
1047     const SMDS_MeshElement* volumes[2];
1048     int what = Preparation(face, PN, VN, FNodes, PC, VNorm, volumes);
1049     if ( what == NOT_QUAD )
1050       continue;
1051     if ( volumes[0] && volumes[1] )
1052       continue; // face is shared by two volumes - no room for a pyramid
1053
1054     if ( what == DEGEN_QUAD )
1055     {
1056       // degenerate face
1057       // add a triangle to the proxy mesh
1058       SMDS_MeshFace* NewFace;
1059
1060       // check orientation
1061       double tmp = PN(1).Distance(PN(2)) + PN(2).Distance(PN(3));
1062       // far points in VNorm direction
1063       gp_Pnt Ptmp1 = PC.XYZ() + VNorm.XYZ() * tmp * 1.e6;
1064       gp_Pnt Ptmp2 = PC.XYZ() - VNorm.XYZ() * tmp * 1.e6;
1065       // check intersection for Ptmp1 and Ptmp2
1066       bool IsRev = false;
1067       bool IsOK1 = false;
1068       bool IsOK2 = false;
1069       double dist1 = RealLast();
1070       double dist2 = RealLast();
1071       gp_Pnt Pres1,Pres2;
1072
1073       gp_Ax1 line( PC, VNorm );
1074       vector< const SMDS_MeshElement* > suspectFaces;
1075       searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces);
1076
1077       for ( size_t iF = 0; iF < suspectFaces.size(); ++iF ) {
1078         const SMDS_MeshElement* F = suspectFaces[iF];
1079         if ( F == face ) continue;
1080         aContour.Clear();
1081         for ( int i = 0; i < 4; ++i )
1082           aContour.Append( SMESH_TNodeXYZ( F->GetNode(i) ));
1083         gp_Pnt PPP;
1084         if ( !volumes[0] && HasIntersection( Ptmp1, PC, PPP, aContour )) {
1085           IsOK1 = true;
1086           double tmp = PC.Distance(PPP);
1087           if ( tmp < dist1 ) {
1088             Pres1 = PPP;
1089             dist1 = tmp;
1090           }
1091         }
1092         if ( !volumes[1] && HasIntersection( Ptmp2, PC, PPP, aContour )) {
1093           IsOK2 = true;
1094           double tmp = PC.Distance(PPP);
1095           if ( tmp < dist2 ) {
1096             Pres2 = PPP;
1097             dist2 = tmp;
1098           }
1099         }
1100       }
1101
1102       if( IsOK1 && !IsOK2 ) {
1103         // using existed direction
1104       }
1105       else if( !IsOK1 && IsOK2 ) {
1106         // using opposite direction
1107         IsRev = true;
1108       }
1109       else { // IsOK1 && IsOK2
1110         double tmp1 = PC.Distance(Pres1);
1111         double tmp2 = PC.Distance(Pres2);
1112         if(tmp1<tmp2) {
1113           // using existed direction
1114         }
1115         else {
1116           // using opposite direction
1117           IsRev = true;
1118         }
1119       }
1120       if(!IsRev)
1121         NewFace = meshDS->AddFace( FNodes[0], FNodes[1], FNodes[2] );
1122       else
1123         NewFace = meshDS->AddFace( FNodes[0], FNodes[2], FNodes[1] );
1124       storeTmpElement( NewFace );
1125       prxSubMesh->AddElement( NewFace );
1126       continue;
1127     }
1128
1129     // -----------------------------------
1130     // Case of non-degenerated quadrangle
1131     // -----------------------------------
1132
1133     // Find pyramid peak
1134
1135     gp_XYZ PCbest(0., 0., 0.); // pyramid peak
1136     int i = 1;
1137     for ( ; i <= 4; i++ ) {
1138       gp_Pnt Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i));
1139       PCbest += Pbest.XYZ();
1140     }
1141     PCbest /= 4;
1142
1143     double height = PC.Distance(PCbest); // pyramid height to precise
1144     if ( height < 1.e-6 ) {
1145       // create new PCbest using a bit shift along VNorm
1146       PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
1147       height = PC.Distance(PCbest);
1148       if ( height < std::numeric_limits<double>::min() )
1149         return false; // batterfly element
1150     }
1151
1152     // Restrict pyramid height by intersection with other faces
1153
1154     gp_Vec tmpDir(PC,PCbest); tmpDir.Normalize();
1155     double tmp = PN(1).Distance(PN(3)) + PN(2).Distance(PN(4));
1156     // far points: in (PC, PCbest) direction and vice-versa
1157     gp_Pnt farPnt[2] = { PC.XYZ() + tmpDir.XYZ() * tmp * 1.e6,
1158                          PC.XYZ() - tmpDir.XYZ() * tmp * 1.e6 };
1159     // check intersection for farPnt1 and farPnt2
1160     bool   intersected[2] = { false, false };
1161     double dist2int   [2] = { RealLast(), RealLast() };
1162     gp_Pnt intPnt     [2];
1163     int    intFaceInd [2] = { 0, 0 };
1164
1165     if ( toFindVolumes && 0 ) // non-conformal mesh is not suitable for any mesher so far
1166     {
1167       // there are volumes in the mesh, in a non-conformal mesh an neighbor
1168       // volume can be not found yet
1169       for ( int isRev = 0; isRev < 2; ++isRev )
1170       {
1171         if ( volumes[isRev] ) continue;
1172         gp_Pnt testPnt = PC.XYZ() + tmpDir.XYZ() * height * ( isRev ? -0.1: 0.1 );
1173         foundVolumes.clear();
1174         if ( volSearcher->FindElementsByPoint( testPnt, SMDSAbs_Volume, foundVolumes ))
1175           volumes[isRev] = foundVolumes[0];
1176       }
1177       if ( volumes[0] && volumes[1] )
1178         continue; // no room for a pyramid
1179     }
1180
1181     gp_Ax1 line( PC, tmpDir );
1182     suspectFaces.clear();
1183     searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces);
1184
1185     for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
1186     {
1187       const SMDS_MeshElement* F = suspectFaces[iF];
1188       if ( F == face ) continue;
1189       aContour.Clear();
1190       int nbN = F->NbCornerNodes();
1191       for ( i = 0; i < nbN; ++i )
1192         aContour.Append( SMESH_TNodeXYZ( F->GetNode(i) ));
1193       gp_Pnt intP;
1194       for ( int isRev = 0; isRev < 2; ++isRev )
1195       {
1196         if( !volumes[isRev] && HasIntersection(farPnt[isRev], PC, intP, aContour) )
1197         {
1198           double d = PC.Distance( intP );
1199           if ( d < dist2int[isRev] )
1200           {
1201             intersected[isRev] = true;
1202             intPnt     [isRev] = intP;
1203             dist2int   [isRev] = d;
1204             intFaceInd [isRev] = iF;
1205           }
1206         }
1207       }
1208     }
1209
1210     // if the face belong to the group of skinFaces, do not build a pyramid outside
1211     if ( groupDS && groupDS->Contains(face) )
1212     {
1213       intersected[0] = false;
1214     }
1215     else if ( intersected[0] && intersected[1] ) // check if one of pyramids is in a hole
1216     {
1217       gp_Pnt P ( PC.XYZ() + tmpDir.XYZ() * 0.5 * dist2int[0] );
1218       if ( searcher->GetPointState( P ) == TopAbs_OUT )
1219         intersected[0] = false;
1220       else
1221       {
1222         P = ( PC.XYZ() - tmpDir.XYZ() * 0.5 * dist2int[1] );
1223         if ( searcher->GetPointState( P ) == TopAbs_OUT )
1224           intersected[1] = false;
1225       }
1226     }
1227
1228     // Create one or two pyramids
1229
1230     for ( int isRev = 0; isRev < 2; ++isRev )
1231     {
1232       if ( !intersected[isRev] ) continue;
1233       double pyramidH = Min( height, dist2int[isRev]/3. );
1234       gp_Pnt    Papex = PC.XYZ() + tmpDir.XYZ() * (isRev ? -pyramidH : pyramidH);
1235       if ( pyramidH < 1e-2 * height )
1236         return overlapError( aMesh, face, suspectFaces[ intFaceInd[isRev] ] );
1237
1238       if ( !LimitHeight( Papex, PC, PN, FNodes, aMesh, face, /*UseApexRay=*/false ))
1239         return false;
1240
1241       // create node for Papex
1242       SMDS_MeshNode* NewNode = helper.AddNode( Papex.X(), Papex.Y(), Papex.Z() );
1243
1244       // add triangles to result map
1245       for ( i = 0; i < 4; i++) {
1246         SMDS_MeshFace* NewFace;
1247         if(isRev)
1248           NewFace = meshDS->AddFace( NewNode, FNodes[i], FNodes[i+1] );
1249         else
1250           NewFace = meshDS->AddFace( NewNode, FNodes[i+1], FNodes[i] );
1251         storeTmpElement( NewFace );
1252         prxSubMesh->AddElement( NewFace );
1253       }
1254       // create a pyramid
1255       SMDS_MeshVolume* aPyram;
1256       if(isRev)
1257         aPyram = helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
1258       else
1259         aPyram = helper.AddVolume( FNodes[0], FNodes[3], FNodes[2], FNodes[1], NewNode );
1260       myPyramids.push_back(aPyram);
1261     }
1262   } // end loop on all faces
1263
1264   return Compute2ndPart(aMesh, myPyramids);
1265 }
1266
1267 //================================================================================
1268 /*!
1269  * \brief Update created pyramids and faces to avoid their intersection
1270  */
1271 //================================================================================
1272
1273 bool StdMeshers_QuadToTriaAdaptor::Compute2ndPart(SMESH_Mesh&                            aMesh,
1274                                                   const vector<const SMDS_MeshElement*>& myPyramids)
1275 {
1276   if ( myPyramids.empty() )
1277     return true;
1278
1279   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1280   size_t i, j, k;
1281   //int myShapeID = myPyramids[0]->GetNode(4)->getshapeId();
1282   {
1283     SMDS_ElemIteratorPtr
1284       pyramIt( new SMDS_ElementVectorIterator( myPyramids.begin(), myPyramids.end() ));
1285     if ( myElemSearcher ) delete myElemSearcher;
1286     myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS, pyramIt );
1287   }
1288   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>( myElemSearcher );
1289
1290   set<const SMDS_MeshNode*> nodesToMove;
1291
1292   // check adjacent pyramids
1293
1294   for ( i = 0; i <  myPyramids.size(); ++i )
1295   {
1296     const SMDS_MeshElement* PrmI = myPyramids[i];
1297     MergeAdjacent( PrmI, nodesToMove );
1298   }
1299
1300   // iterate on all new pyramids
1301   vector< const SMDS_MeshElement* > suspectPyrams;
1302   for ( i = 0; i <  myPyramids.size(); ++i )
1303   {
1304     const SMDS_MeshElement*  PrmI = myPyramids[i];
1305     const SMDS_MeshNode*    apexI = PrmI->GetNode( PYRAM_APEX );
1306
1307     // compare PrmI with all the rest pyramids
1308
1309     // collect adjacent pyramids and nodes coordinates of PrmI
1310     set<const SMDS_MeshElement*> checkedPyrams;
1311     gp_Pnt PsI[5];
1312     for ( k = 0; k < 5; k++ )
1313     {
1314       const SMDS_MeshNode* n = PrmI->GetNode(k);
1315       PsI[k] = SMESH_TNodeXYZ( n );
1316       SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
1317       while ( vIt->more() )
1318       {
1319         const SMDS_MeshElement* PrmJ = vIt->next();
1320         if ( SMESH_MeshAlgos::GetCommonNodes( PrmI, PrmJ ).size() > 1 )
1321           checkedPyrams.insert( PrmJ );
1322       }
1323     }
1324
1325     // get pyramids to check
1326     gp_XYZ       PC = ( PsI[0].XYZ() + PsI[1].XYZ() + PsI[2].XYZ() + PsI[3].XYZ() ) / 4.;
1327     gp_XYZ      ray = PsI[4].XYZ() - PC;
1328     gp_XYZ   center = PC + 0.5 * ray;
1329     double diameter = Max( PsI[0].Distance(PsI[2]), PsI[1].Distance(PsI[3]));
1330     suspectPyrams.clear();
1331     searcher->GetElementsInSphere( center, diameter * 0.6, SMDSAbs_Volume, suspectPyrams);
1332
1333     // check intersection with distant pyramids
1334     for ( j = 0; j < suspectPyrams.size(); ++j )
1335     {
1336       const SMDS_MeshElement* PrmJ = suspectPyrams[j];
1337       if ( PrmJ == PrmI )
1338         continue;
1339       if ( apexI == PrmJ->GetNode( PYRAM_APEX ))
1340         continue; // pyramids PrmI and PrmJ already merged
1341       if ( !checkedPyrams.insert( PrmJ ).second )
1342         continue; // already checked
1343
1344       gp_Pnt PsJ[5];
1345       for ( k = 0; k < 5; k++ )
1346         PsJ[k] = SMESH_TNodeXYZ( PrmJ->GetNode(k) );
1347
1348       if ( ray * ( PsJ[4].XYZ() - PC ) < 0. )
1349         continue; // PrmJ is below PrmI
1350
1351       for ( k = 0; k < 4; k++ ) // loop on 4 base nodes of PrmI
1352       {
1353         gp_Pnt Pint;
1354         bool hasInt=false;
1355         for ( k = 0; k < 4  &&  !hasInt; k++ )
1356         {
1357           gp_Vec Vtmp( PsI[k], PsI[ PYRAM_APEX ]);
1358           gp_Pnt Pshift = PsI[k].XYZ() + Vtmp.XYZ() * 0.01; // base node moved a bit to apex
1359           hasInt =
1360           ( HasIntersection3( Pshift, PsI[4], Pint, PsJ[0], PsJ[1], PsJ[PYRAM_APEX]) ||
1361             HasIntersection3( Pshift, PsI[4], Pint, PsJ[1], PsJ[2], PsJ[PYRAM_APEX]) ||
1362             HasIntersection3( Pshift, PsI[4], Pint, PsJ[2], PsJ[3], PsJ[PYRAM_APEX]) ||
1363             HasIntersection3( Pshift, PsI[4], Pint, PsJ[3], PsJ[0], PsJ[PYRAM_APEX]) );
1364         }
1365         for ( k = 0; k < 4  &&  !hasInt; k++ )
1366         {
1367           gp_Vec Vtmp( PsJ[k], PsJ[ PYRAM_APEX ]);
1368           gp_Pnt Pshift = PsJ[k].XYZ() + Vtmp.XYZ() * 0.01;
1369           hasInt =
1370             ( HasIntersection3( Pshift, PsJ[4], Pint, PsI[0], PsI[1], PsI[PYRAM_APEX]) ||
1371               HasIntersection3( Pshift, PsJ[4], Pint, PsI[1], PsI[2], PsI[PYRAM_APEX]) ||
1372               HasIntersection3( Pshift, PsJ[4], Pint, PsI[2], PsI[3], PsI[PYRAM_APEX]) ||
1373               HasIntersection3( Pshift, PsJ[4], Pint, PsI[3], PsI[0], PsI[PYRAM_APEX]) );
1374         }
1375
1376         if ( hasInt )
1377         {
1378           // count common nodes of base faces of two pyramids
1379           int nbc = 0;
1380           for ( k = 0; k < 4; k++ )
1381             nbc += int ( PrmI->GetNodeIndex( PrmJ->GetNode(k) ) >= 0 );
1382
1383           if ( nbc == 4 )
1384             continue; // pyrams have a common base face
1385
1386           if ( nbc > 0 )
1387           {
1388             // Merge the two pyramids and others already merged with them
1389             MergePiramids( PrmI, PrmJ, nodesToMove );
1390           }
1391           else  // nbc==0
1392           {
1393             // decrease height of pyramids
1394             gp_XYZ PCi(0,0,0), PCj(0,0,0);
1395             for ( k = 0; k < 4; k++ ) {
1396               PCi += PsI[k].XYZ();
1397               PCj += PsJ[k].XYZ();
1398             }
1399             PCi /= 4; PCj /= 4;
1400             gp_Vec VN1(PCi,PsI[4]);
1401             gp_Vec VN2(PCj,PsJ[4]);
1402             gp_Vec VI1(PCi,Pint);
1403             gp_Vec VI2(PCj,Pint);
1404             double ang1 = fabs(VN1.Angle(VI1));
1405             double ang2 = fabs(VN2.Angle(VI2));
1406             double coef1 = 0.5 - (( ang1 < M_PI/3. ) ? cos(ang1)*0.25 : 0 );
1407             double coef2 = 0.5 - (( ang2 < M_PI/3. ) ? cos(ang2)*0.25 : 0 ); // cos(ang2) ?
1408 //             double coef2 = 0.5;
1409 //             if(ang2<PI/3)
1410 //               coef2 -= cos(ang1)*0.25;
1411
1412             VN1.Scale(coef1);
1413             VN2.Scale(coef2);
1414             SMDS_MeshNode* aNode1 = const_cast<SMDS_MeshNode*>( apexI );
1415             aNode1->setXYZ( PCi.X()+VN1.X(), PCi.Y()+VN1.Y(), PCi.Z()+VN1.Z() );
1416             SMDS_MeshNode* aNode2 = const_cast<SMDS_MeshNode*>(PrmJ->GetNode( PYRAM_APEX ));
1417             aNode2->setXYZ( PCj.X()+VN2.X(), PCj.Y()+VN2.Y(), PCj.Z()+VN2.Z() );
1418             nodesToMove.insert( aNode1 );
1419             nodesToMove.insert( aNode2 );
1420           }
1421           // fix intersections that can appear after apex movement
1422           MergeAdjacent( PrmI, nodesToMove );
1423           MergeAdjacent( PrmJ, nodesToMove );
1424
1425         } // end if(hasInt)
1426       } // loop on suspectPyrams
1427     }  // loop on 4 base nodes of PrmI
1428
1429   } // loop on all pyramids
1430
1431   if( !nodesToMove.empty() && !meshDS->IsEmbeddedMode() )
1432   {
1433     set<const SMDS_MeshNode*>::iterator n = nodesToMove.begin();
1434     for ( ; n != nodesToMove.end(); ++n )
1435       meshDS->MoveNode( *n, (*n)->X(), (*n)->Y(), (*n)->Z() );
1436   }
1437
1438   // move medium nodes of merged quadratic pyramids
1439   if ( myPyramids[0]->IsQuadratic() )
1440     UpdateQuadraticPyramids( nodesToMove, GetMeshDS() );
1441
1442   // erase removed triangles from the proxy mesh
1443   if ( !myRemovedTrias.empty() )
1444   {
1445     for ( int i = 0; i <= meshDS->MaxShapeIndex(); ++i )
1446       if ( SMESH_ProxyMesh::SubMesh* sm = findProxySubMesh(i))
1447       {
1448         vector<const SMDS_MeshElement *> faces;
1449         faces.reserve( sm->NbElements() );
1450         SMDS_ElemIteratorPtr fIt = sm->GetElements();
1451         while ( fIt->more() )
1452         {
1453           const SMDS_MeshElement* tria = fIt->next();
1454           set<const SMDS_MeshElement*>::iterator rmTria = myRemovedTrias.find( tria );
1455           if ( rmTria != myRemovedTrias.end() )
1456             myRemovedTrias.erase( rmTria );
1457           else
1458             faces.push_back( tria );
1459         }
1460         sm->ChangeElements( faces.begin(), faces.end() );
1461       }
1462   }
1463
1464   myDegNodes.clear();
1465
1466   delete myElemSearcher;
1467   myElemSearcher=0;
1468
1469   return true;
1470 }