Salome HOME
not initialized value
[modules/smesh.git] / src / StdMeshers / StdMeshers_QuadToTriaAdaptor.cxx
1 //  Copyright (C) 2007-2010  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.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
21 // File      : StdMeshers_QuadToTriaAdaptor.cxx
22 // Module    : SMESH
23 // Created   : Wen May 07 16:37:07 2008
24 // Author    : Sergey KUUL (skl)
25 //
26 #include "StdMeshers_QuadToTriaAdaptor.hxx"
27
28 #include "SMDS_SetIterator.hxx"
29
30 #include "SMESH_Algo.hxx"
31 #include "SMESH_MesherHelper.hxx"
32
33 #include <IntAna_IntConicQuad.hxx>
34 #include <IntAna_Quadric.hxx>
35 #include <TColgp_HArray1OfPnt.hxx>
36 #include <TColgp_HArray1OfVec.hxx>
37 #include <TColgp_HSequenceOfPnt.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopoDS.hxx>
40 #include <gp_Lin.hxx>
41 #include <gp_Pln.hxx>
42
43 #include <numeric>
44
45 using namespace std;
46
47 enum EQuadNature { NOT_QUAD, QUAD, DEGEN_QUAD, PYRAM_APEX = 4, TRIA_APEX = 0 };
48
49 // std-like iterator used to get coordinates of nodes of mesh element
50 typedef SMDS_StdIterator< SMESH_MeshEditor::TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
51
52 namespace
53 {
54   //================================================================================
55   /*!
56    * \brief Return true if two nodes of triangles are equal
57    */
58   //================================================================================
59
60   bool EqualTriangles(const SMDS_MeshElement* F1,const SMDS_MeshElement* F2)
61   {
62     return
63       ( F1->GetNode(1)==F2->GetNode(2) && F1->GetNode(2)==F2->GetNode(1) ) ||
64       ( F1->GetNode(1)==F2->GetNode(1) && F1->GetNode(2)==F2->GetNode(2) );
65   }
66   //================================================================================
67   /*!
68    * \brief Return true if two adjacent pyramids are too close one to another
69    * so that a tetrahedron to built between them would have too poor quality
70    */
71   //================================================================================
72
73   bool TooCloseAdjacent( const SMDS_MeshElement* PrmI,
74                          const SMDS_MeshElement* PrmJ,
75                          const bool              hasShape)
76   {
77     const SMDS_MeshNode* nApexI = PrmI->GetNode(4);
78     const SMDS_MeshNode* nApexJ = PrmJ->GetNode(4);
79     if ( nApexI == nApexJ ||
80          nApexI->getshapeId() != nApexJ->getshapeId() )
81       return false;
82
83     // Find two common base nodes and their indices within PrmI and PrmJ
84     const SMDS_MeshNode* baseNodes[2] = { 0,0 };
85     int baseNodesIndI[2], baseNodesIndJ[2];
86     for ( int i = 0; i < 4 ; ++i )
87     {
88       int j = PrmJ->GetNodeIndex( PrmI->GetNode(i));
89       if ( j >= 0 )
90       {
91         int ind = baseNodes[0] ? 1:0;
92         if ( baseNodes[ ind ])
93           return false; // pyramids with a common base face
94         baseNodes   [ ind ] = PrmI->GetNode(i);
95         baseNodesIndI[ ind ] = i;
96         baseNodesIndJ[ ind ] = j;
97       }
98     }
99     if ( !baseNodes[1] ) return false; // not adjacent
100
101     // Get normals of triangles sharing baseNodes
102     gp_XYZ apexI = SMESH_MeshEditor::TNodeXYZ( nApexI );
103     gp_XYZ apexJ = SMESH_MeshEditor::TNodeXYZ( nApexJ );
104     gp_XYZ base1 = SMESH_MeshEditor::TNodeXYZ( baseNodes[0]);
105     gp_XYZ base2 = SMESH_MeshEditor::TNodeXYZ( baseNodes[1]);
106     gp_Vec baseVec( base1, base2 );
107     gp_Vec baI( base1, apexI );
108     gp_Vec baJ( base1, apexJ );
109     gp_Vec nI = baseVec.Crossed( baI );
110     gp_Vec nJ = baseVec.Crossed( baJ );
111
112     // Check angle between normals
113     double angle = nI.Angle( nJ );
114     bool tooClose = ( angle < 15 * PI180 );
115
116     // Check if pyramids collide
117     bool isOutI, isOutJ;
118     if ( !tooClose && baI * baJ > 0 )
119     {
120       // find out if nI points outside of PrmI or inside
121       int dInd = baseNodesIndI[1] - baseNodesIndI[0];
122       isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
123
124       // find out sign of projection of nJ to baI
125       double proj = baI * nJ;
126
127       tooClose = isOutI ? proj > 0 : proj < 0;
128     }
129
130     // Check if PrmI and PrmJ are in same domain
131     if ( tooClose && !hasShape )
132     {
133       // check order of baseNodes within pyramids, it must be opposite
134       int dInd;
135       dInd = baseNodesIndI[1] - baseNodesIndI[0];
136       isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
137       dInd = baseNodesIndJ[1] - baseNodesIndJ[0];
138       isOutJ = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
139       if ( isOutJ == isOutI )
140         return false; // other domain
141
142       // check absence of a face separating domains between pyramids
143       TIDSortedElemSet emptySet, avoidSet;
144       int i1, i2;
145       while ( const SMDS_MeshElement* f =
146               SMESH_MeshEditor::FindFaceInSet( baseNodes[0], baseNodes[1],
147                                                emptySet, avoidSet, &i1, &i2 ))
148       {
149         avoidSet.insert( f );
150
151         // face node other than baseNodes
152         int otherNodeInd = 0;
153         while ( otherNodeInd == i1 || otherNodeInd == i2 ) otherNodeInd++;
154         const SMDS_MeshNode* otherFaceNode = f->GetNode( otherNodeInd );
155
156         // check if f is a base face of either of pyramids
157         if ( f->NbCornerNodes() == 4 &&
158              ( PrmI->GetNodeIndex( otherFaceNode ) >= 0 ||
159                PrmJ->GetNodeIndex( otherFaceNode ) >= 0 ))
160           continue; // f is a base quadrangle
161
162         // check projections of face direction (baOFN) to triange normals (nI and nJ)
163         gp_Vec baOFN( base1, SMESH_MeshEditor::TNodeXYZ( otherFaceNode ));
164         ( isOutI ? nJ : nI ).Reverse();
165         if ( nI * baOFN > 0 && nJ * baOFN > 0 )
166         {
167           tooClose = false; // f is between pyramids
168           break;
169         }
170       }
171     }
172
173     return tooClose;
174   }
175 }
176
177 //================================================================================
178 /*!
179  * \brief Merge the two pyramids (i.e. fuse their apex) and others already merged with them
180  */
181 //================================================================================
182
183 void StdMeshers_QuadToTriaAdaptor::MergePiramids( const SMDS_MeshElement*     PrmI,
184                                                   const SMDS_MeshElement*     PrmJ,
185                                                   set<const SMDS_MeshNode*> & nodesToMove)
186 {
187   const SMDS_MeshNode* Nrem = PrmJ->GetNode(4); // node to remove
188   int nbJ = Nrem->NbInverseElements( SMDSAbs_Volume );
189   SMESH_MeshEditor::TNodeXYZ Pj( Nrem );
190
191   // an apex node to make common to all merged pyramids
192   SMDS_MeshNode* CommonNode = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
193   if ( CommonNode == Nrem ) return; // already merged
194   int nbI = CommonNode->NbInverseElements( SMDSAbs_Volume );
195   SMESH_MeshEditor::TNodeXYZ Pi( CommonNode );
196   gp_XYZ Pnew = ( nbI*Pi + nbJ*Pj ) / (nbI+nbJ);
197   CommonNode->setXYZ( Pnew.X(), Pnew.Y(), Pnew.Z() );
198
199   nodesToMove.insert( CommonNode );
200   nodesToMove.erase ( Nrem );
201
202   typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
203   TStdElemIterator itEnd;
204
205   // find and remove coincided faces of merged pyramids
206   vector< const SMDS_MeshElement* > inverseElems
207     // copy inverse elements to avoid iteration on changing conainer 
208     ( TStdElemIterator( CommonNode->GetInverseElementIterator(SMDSAbs_Face)), itEnd);
209   for ( unsigned i = 0; i < inverseElems.size(); ++i )
210   {
211     const SMDS_MeshElement* FI = inverseElems[i];
212     const SMDS_MeshElement* FJEqual = 0;
213     SMDS_ElemIteratorPtr triItJ = Nrem->GetInverseElementIterator(SMDSAbs_Face);
214     while ( !FJEqual && triItJ->more() )
215     {
216       const SMDS_MeshElement* FJ = triItJ->next();
217       if ( EqualTriangles( FJ, FI ))
218         FJEqual = FJ;
219     }
220     if ( FJEqual )
221     {
222       removeTmpElement( FI );
223       removeTmpElement( FJEqual );
224       myRemovedTrias.insert( FI );
225       myRemovedTrias.insert( FJEqual );
226     }
227   }
228
229   // set the common apex node to pyramids and triangles merged with J
230   inverseElems.assign( TStdElemIterator( Nrem->GetInverseElementIterator()), itEnd );
231   for ( unsigned i = 0; i < inverseElems.size(); ++i )
232   {
233     const SMDS_MeshElement* elem = inverseElems[i];
234     vector< const SMDS_MeshNode* > nodes( elem->begin_nodes(), elem->end_nodes() );
235     nodes[ elem->GetType() == SMDSAbs_Volume ? PYRAM_APEX : TRIA_APEX ] = CommonNode;
236     GetMeshDS()->ChangeElementNodes( elem, &nodes[0], nodes.size());
237   }
238   ASSERT( Nrem->NbInverseElements() == 0 );
239   GetMeshDS()->RemoveFreeNode( Nrem,
240                                GetMeshDS()->MeshElements( Nrem->getshapeId()),
241                                /*fromGroups=*/false);
242 }
243
244 //================================================================================
245 /*!
246  * \brief Merges adjacent pyramids
247  */
248 //================================================================================
249
250 void StdMeshers_QuadToTriaAdaptor::MergeAdjacent(const SMDS_MeshElement*    PrmI,
251                                                  set<const SMDS_MeshNode*>& nodesToMove)
252 {
253   TIDSortedElemSet adjacentPyrams;
254   bool mergedPyrams = false;
255   for(int k=0; k<4; k++) // loop on 4 base nodes of PrmI
256   {
257     const SMDS_MeshNode* n = PrmI->GetNode(k);
258     SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
259     while ( vIt->more() )
260     {
261       const SMDS_MeshElement* PrmJ = vIt->next();
262       if ( PrmJ->NbCornerNodes() != 5 || !adjacentPyrams.insert( PrmJ ).second  )
263         continue;
264       if ( PrmI != PrmJ && TooCloseAdjacent( PrmI, PrmJ, GetMesh()->HasShapeToMesh() ))
265       {
266         MergePiramids( PrmI, PrmJ, nodesToMove );
267         mergedPyrams = true;
268         // container of inverse elements can change
269         vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
270       }
271     }
272   }
273   if ( mergedPyrams )
274   {
275     TIDSortedElemSet::iterator prm;
276     for (prm = adjacentPyrams.begin(); prm != adjacentPyrams.end(); ++prm)
277       MergeAdjacent( *prm, nodesToMove );
278   }
279 }
280
281 //================================================================================
282 /*!
283  * \brief Constructor
284  */
285 //================================================================================
286
287 StdMeshers_QuadToTriaAdaptor::StdMeshers_QuadToTriaAdaptor():
288   myElemSearcher(0)
289 {
290 }
291
292 //================================================================================
293 /*!
294  * \brief Destructor
295  */
296 //================================================================================
297
298 StdMeshers_QuadToTriaAdaptor::~StdMeshers_QuadToTriaAdaptor()
299 {
300   // temporary faces are deleted by ~SMESH_ProxyMesh()
301   if ( myElemSearcher ) delete myElemSearcher;
302   myElemSearcher=0;
303 }
304
305
306 //=======================================================================
307 //function : FindBestPoint
308 //purpose  : Return a point P laying on the line (PC,V) so that triangle
309 //           (P, P1, P2) to be equilateral as much as possible
310 //           V - normal to (P1,P2,PC)
311 //=======================================================================
312 static gp_Pnt FindBestPoint(const gp_Pnt& P1, const gp_Pnt& P2,
313                             const gp_Pnt& PC, const gp_Vec& V)
314 {
315   double a = P1.Distance(P2);
316   double b = P1.Distance(PC);
317   double c = P2.Distance(PC);
318   if( a < (b+c)/2 )
319     return PC;
320   else {
321     // find shift along V in order a to became equal to (b+c)/2
322     double shift = sqrt( a*a + (b*b-c*c)*(b*b-c*c)/16/a/a - (b*b+c*c)/2 );
323     gp_Dir aDir(V);
324     gp_Pnt Pbest = PC.XYZ() + aDir.XYZ() * shift;
325     return Pbest;
326   }
327 }
328
329
330 //=======================================================================
331 //function : HasIntersection3
332 //purpose  : Auxilare for HasIntersection()
333 //           find intersection point between triangle (P1,P2,P3)
334 //           and segment [PC,P]
335 //=======================================================================
336 static bool HasIntersection3(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
337                              const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3)
338 {
339   //cout<<"HasIntersection3"<<endl;
340   //cout<<"  PC("<<PC.X()<<","<<PC.Y()<<","<<PC.Z()<<")"<<endl;
341   //cout<<"  P("<<P.X()<<","<<P.Y()<<","<<P.Z()<<")"<<endl;
342   //cout<<"  P1("<<P1.X()<<","<<P1.Y()<<","<<P1.Z()<<")"<<endl;
343   //cout<<"  P2("<<P2.X()<<","<<P2.Y()<<","<<P2.Z()<<")"<<endl;
344   //cout<<"  P3("<<P3.X()<<","<<P3.Y()<<","<<P3.Z()<<")"<<endl;
345   gp_Vec VP1(P1,P2);
346   gp_Vec VP2(P1,P3);
347   IntAna_Quadric IAQ(gp_Pln(P1,VP1.Crossed(VP2)));
348   IntAna_IntConicQuad IAICQ(gp_Lin(PC,gp_Dir(gp_Vec(PC,P))),IAQ);
349   if(IAICQ.IsDone()) {
350     if( IAICQ.IsInQuadric() )
351       return false;
352     if( IAICQ.NbPoints() == 1 ) {
353       gp_Pnt PIn = IAICQ.Point(1);
354       const double preci = 1.e-10 * P.Distance(PC);
355       // check if this point is internal for segment [PC,P]
356       bool IsExternal =
357         ( (PC.X()-PIn.X())*(P.X()-PIn.X()) > preci ) ||
358         ( (PC.Y()-PIn.Y())*(P.Y()-PIn.Y()) > preci ) ||
359         ( (PC.Z()-PIn.Z())*(P.Z()-PIn.Z()) > preci );
360       if(IsExternal) {
361         return false;
362       }
363       // check if this point is internal for triangle (P1,P2,P3)
364       gp_Vec V1(PIn,P1);
365       gp_Vec V2(PIn,P2);
366       gp_Vec V3(PIn,P3);
367       if( V1.Magnitude()<preci ||
368           V2.Magnitude()<preci ||
369           V3.Magnitude()<preci ) {
370         Pint = PIn;
371         return true;
372       }
373       const double angularTol = 1e-6;
374       gp_Vec VC1 = V1.Crossed(V2);
375       gp_Vec VC2 = V2.Crossed(V3);
376       gp_Vec VC3 = V3.Crossed(V1);
377       if(VC1.Magnitude()<gp::Resolution()) {
378         if(VC2.IsOpposite(VC3,angularTol)) {
379           return false;
380         }
381       }
382       else if(VC2.Magnitude()<gp::Resolution()) {
383         if(VC1.IsOpposite(VC3,angularTol)) {
384           return false;
385         }
386       }
387       else if(VC3.Magnitude()<gp::Resolution()) {
388         if(VC1.IsOpposite(VC2,angularTol)) {
389           return false;
390         }
391       }
392       else {
393         if( VC1.IsOpposite(VC2,angularTol) || VC1.IsOpposite(VC3,angularTol) ||
394             VC2.IsOpposite(VC3,angularTol) ) {
395           return false;
396         }
397       }
398       Pint = PIn;
399       return true;
400     }
401   }
402
403   return false;
404 }
405
406
407 //=======================================================================
408 //function : HasIntersection
409 //purpose  : Auxilare for CheckIntersection()
410 //=======================================================================
411
412 static bool HasIntersection(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
413                             Handle(TColgp_HSequenceOfPnt)& aContour)
414 {
415   if(aContour->Length()==3) {
416     return HasIntersection3( P, PC, Pint, aContour->Value(1),
417                              aContour->Value(2), aContour->Value(3) );
418   }
419   else {
420     bool check = false;
421     if( (aContour->Value(1).Distance(aContour->Value(2)) > 1.e-6) &&
422         (aContour->Value(1).Distance(aContour->Value(3)) > 1.e-6) &&
423         (aContour->Value(2).Distance(aContour->Value(3)) > 1.e-6) ) {
424       check = HasIntersection3( P, PC, Pint, aContour->Value(1),
425                                 aContour->Value(2), aContour->Value(3) );
426     }
427     if(check) return true;
428     if( (aContour->Value(1).Distance(aContour->Value(4)) > 1.e-6) &&
429         (aContour->Value(1).Distance(aContour->Value(3)) > 1.e-6) &&
430         (aContour->Value(4).Distance(aContour->Value(3)) > 1.e-6) ) {
431       check = HasIntersection3( P, PC, Pint, aContour->Value(1),
432                                 aContour->Value(3), aContour->Value(4) );
433     }
434     if(check) return true;
435   }
436
437   return false;
438 }
439
440 //================================================================================
441 /*!
442  * \brief Checks if a line segment (P,PC) intersects any mesh face.
443  *  \param P - first segment end
444  *  \param PC - second segment end (it is a gravity center of quadrangle)
445  *  \param Pint - (out) intersection point
446  *  \param aMesh - mesh
447  *  \param aShape - shape to check faces on
448  *  \param NotCheckedFace - mesh face not to check
449  *  \retval bool - true if there is an intersection
450  */
451 //================================================================================
452
453 bool StdMeshers_QuadToTriaAdaptor::CheckIntersection (const gp_Pnt&       P,
454                                                       const gp_Pnt&       PC,
455                                                       gp_Pnt&             Pint,
456                                                       SMESH_Mesh&         aMesh,
457                                                       const TopoDS_Shape& aShape,
458                                                       const SMDS_MeshElement* NotCheckedFace)
459 {
460   if ( !myElemSearcher )
461     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
462   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
463
464   //SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
465   //cout<<"    CheckIntersection: meshDS->NbFaces() = "<<meshDS->NbFaces()<<endl;
466   bool res = false;
467   double dist = RealLast(); // find intersection closest to the segment
468   gp_Pnt Pres;
469
470   gp_Ax1 line( P, gp_Vec(P,PC));
471   vector< const SMDS_MeshElement* > suspectElems;
472   searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectElems);
473   
474 //   for (TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
475 //     const TopoDS_Shape& aShapeFace = exp.Current();
476 //     if(aShapeFace==NotCheckedFace)
477 //       continue;
478 //     const SMESHDS_SubMesh * aSubMeshDSFace = meshDS->MeshElements(aShapeFace);
479 //     if ( aSubMeshDSFace ) {
480 //       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
481 //       while ( iteratorElem->more() ) { // loop on elements on a face
482 //         const SMDS_MeshElement* face = iteratorElem->next();
483   for ( int i = 0; i < suspectElems.size(); ++i )
484   {
485     const SMDS_MeshElement* face = suspectElems[i];
486     if ( face == NotCheckedFace ) continue;
487     Handle(TColgp_HSequenceOfPnt) aContour = new TColgp_HSequenceOfPnt;
488     for ( int i = 0; i < face->NbCornerNodes(); ++i ) 
489       aContour->Append( SMESH_MeshEditor::TNodeXYZ( face->GetNode(i) ));
490     if( HasIntersection(P, PC, Pres, aContour) ) {
491       res = true;
492       double tmp = PC.Distance(Pres);
493       if(tmp<dist) {
494         Pint = Pres;
495         dist = tmp;
496       }
497     }
498   }
499   return res;
500 }
501
502 //================================================================================
503 /*!
504  * \brief Prepare data for the given face
505  *  \param PN - coordinates of face nodes
506  *  \param VN - cross products of vectors (PC-PN(i)) ^ (PC-PN(i+1))
507  *  \param FNodes - face nodes
508  *  \param PC - gravity center of nodes
509  *  \param VNorm - face normal (sum of VN)
510  *  \param volumes - two volumes sharing the given face, the first is in VNorm direction
511  *  \retval int - 0 if given face is not quad,
512  *                1 if given face is quad,
513  *                2 if given face is degenerate quad (two nodes are coincided)
514  */
515 //================================================================================
516
517 int StdMeshers_QuadToTriaAdaptor::Preparation(const SMDS_MeshElement*       face,
518                                               Handle(TColgp_HArray1OfPnt)&  PN,
519                                               Handle(TColgp_HArray1OfVec)&  VN,
520                                               vector<const SMDS_MeshNode*>& FNodes,
521                                               gp_Pnt&                       PC,
522                                               gp_Vec&                       VNorm,
523                                               const SMDS_MeshElement**      volumes)
524 {
525   if( face->NbCornerNodes() != 4 )
526   {
527     //myNbTriangles += int( face->NbCornerNodes() == 3 );
528     return NOT_QUAD;
529   }
530
531   int i = 0;
532   gp_XYZ xyzC(0., 0., 0.);
533   for ( i = 0; i < 4; ++i )
534   {
535     gp_XYZ p = SMESH_MeshEditor::TNodeXYZ( FNodes[i] = face->GetNode(i) );
536     PN->SetValue( i+1, p );
537     xyzC += p;
538   }
539   PC = xyzC/4;
540   //cout<<"  PC("<<PC.X()<<","<<PC.Y()<<","<<PC.Z()<<")"<<endl;
541
542   int nbp = 4;
543
544   int j = 0;
545   for(i=1; i<4; i++) {
546     j = i+1;
547     for(; j<=4; j++) {
548       if( PN->Value(i).Distance(PN->Value(j)) < 1.e-6 )
549         break;
550     }
551     if(j<=4) break;
552   }
553   //int deg_num = IsDegenarate(PN);
554   //if(deg_num>0) {
555   bool hasdeg = false;
556   if(i<4) {
557     //cout<<"find degeneration"<<endl;
558     hasdeg = true;
559     gp_Pnt Pdeg = PN->Value(i);
560
561     list< const SMDS_MeshNode* >::iterator itdg = myDegNodes.begin();
562     const SMDS_MeshNode* DegNode = 0;
563     for(; itdg!=myDegNodes.end(); itdg++) {
564       const SMDS_MeshNode* N = (*itdg);
565       gp_Pnt Ptmp(N->X(),N->Y(),N->Z());
566       if(Pdeg.Distance(Ptmp)<1.e-6) {
567         DegNode = N;
568         //DegNode = const_cast<SMDS_MeshNode*>(N);
569         break;
570       }
571     }
572     if(!DegNode) {
573       DegNode = FNodes[i-1];
574       myDegNodes.push_back(DegNode);
575     }
576     else {
577       FNodes[i-1] = DegNode;
578     }
579     for(i=j; i<4; i++) {
580       PN->SetValue(i,PN->Value(i+1));
581       FNodes[i-1] = FNodes[i];
582     }
583     nbp = 3;
584   }
585
586   PN->SetValue(nbp+1,PN->Value(1));
587   FNodes[nbp] = FNodes[0];
588   // find normal direction
589   gp_Vec V1(PC,PN->Value(nbp));
590   gp_Vec V2(PC,PN->Value(1));
591   VNorm = V1.Crossed(V2);
592   VN->SetValue(nbp,VNorm);
593   for(i=1; i<nbp; i++) {
594     V1 = gp_Vec(PC,PN->Value(i));
595     V2 = gp_Vec(PC,PN->Value(i+1));
596     gp_Vec Vtmp = V1.Crossed(V2);
597     VN->SetValue(i,Vtmp);
598     VNorm += Vtmp;
599   }
600
601   // find volumes sharing the face
602   if ( volumes )
603   {
604     volumes[0] = volumes[1] = 0;
605     SMDS_ElemIteratorPtr vIt = FNodes[0]->GetInverseElementIterator( SMDSAbs_Volume );
606     while ( vIt->more() )
607     {
608       const SMDS_MeshElement* vol = vIt->next();
609       bool volSharesAllNodes = true;
610       for ( int i = 1; i < face->NbNodes() && volSharesAllNodes; ++i )
611         volSharesAllNodes = ( vol->GetNodeIndex( FNodes[i] ) >= 0 );
612       if ( volSharesAllNodes )
613         volumes[ volumes[0] ? 1 : 0 ] = vol;
614       // we could additionally check that vol has all FNodes in its one face using SMDS_VolumeTool
615     }
616     // define volume position relating to the face normal
617     if ( volumes[0] )
618     {
619       // get volume gc
620       SMDS_ElemIteratorPtr nodeIt = volumes[0]->nodesIterator();
621       gp_XYZ volGC(0,0,0);
622       volGC = accumulate( TXyzIterator(nodeIt), TXyzIterator(), volGC ) / volumes[0]->NbNodes();
623
624       if ( VNorm * gp_Vec( PC, volGC ) < 0 )
625         swap( volumes[0], volumes[1] );
626     }
627   }
628
629   //cout<<"  VNorm("<<VNorm.X()<<","<<VNorm.Y()<<","<<VNorm.Z()<<")"<<endl;
630   return hasdeg ? DEGEN_QUAD : QUAD;
631 }
632
633
634 //=======================================================================
635 //function : Compute
636 //purpose  : 
637 //=======================================================================
638
639 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh&           aMesh,
640                                            const TopoDS_Shape&   aShape,
641                                            SMESH_ProxyMesh* aProxyMesh)
642 {
643   SMESH_ProxyMesh::setMesh( aMesh );
644
645   if ( aShape.ShapeType() != TopAbs_SOLID &&
646        aShape.ShapeType() != TopAbs_SHELL )
647     return false;
648
649   vector<const SMDS_MeshElement*> myPyramids;
650
651   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
652   SMESH_MesherHelper helper(aMesh);
653   helper.IsQuadraticSubMesh(aShape);
654   helper.SetElementsOnShape( true );
655
656   if ( myElemSearcher ) delete myElemSearcher;
657   if ( aProxyMesh )
658     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher( aProxyMesh->GetFaces(aShape));
659   else
660     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
661
662   const SMESHDS_SubMesh * aSubMeshDSFace;
663   Handle(TColgp_HArray1OfPnt) PN = new TColgp_HArray1OfPnt(1,5);
664   Handle(TColgp_HArray1OfVec) VN = new TColgp_HArray1OfVec(1,4);
665   vector<const SMDS_MeshNode*> FNodes(5);
666   gp_Pnt PC;
667   gp_Vec VNorm;
668
669   for (TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next())
670   {
671     const TopoDS_Shape& aShapeFace = exp.Current();
672     if ( aProxyMesh )
673       aSubMeshDSFace = aProxyMesh->GetSubMesh( aShapeFace );
674     else
675       aSubMeshDSFace = meshDS->MeshElements( aShapeFace );
676
677     vector<const SMDS_MeshElement*> trias, quads;
678     bool hasNewTrias = false;
679
680     if ( aSubMeshDSFace )
681     {
682       bool isRev = false;
683       if ( helper.NbAncestors( aShapeFace, aMesh, aShape.ShapeType() ) > 1 )
684         isRev = SMESH_Algo::IsReversedSubMesh( TopoDS::Face(aShapeFace), meshDS );
685
686       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
687       while ( iteratorElem->more() ) // loop on elements on a geometrical face
688       {
689         const SMDS_MeshElement* face = iteratorElem->next();
690         // preparation step to get face info
691         int stat = Preparation(face, PN, VN, FNodes, PC, VNorm);
692         switch ( stat )
693         {
694         case NOT_QUAD:
695
696           trias.push_back( face );
697           break;
698
699         case DEGEN_QUAD:
700           {
701             // degenerate face
702             // add triangles to result map
703             SMDS_MeshFace* NewFace;
704             if(!isRev)
705               NewFace = meshDS->AddFace( FNodes[0], FNodes[1], FNodes[2] );
706             else
707               NewFace = meshDS->AddFace( FNodes[0], FNodes[2], FNodes[1] );
708             storeTmpElement( NewFace );
709             trias.push_back ( NewFace );
710             quads.push_back( face );
711             hasNewTrias = true;
712             break;
713           }
714
715         case QUAD:
716           {
717             if(!isRev) VNorm.Reverse();
718             double xc = 0., yc = 0., zc = 0.;
719             int i = 1;
720             for(; i<=4; i++) {
721               gp_Pnt Pbest;
722               if(!isRev)
723                 Pbest = FindBestPoint(PN->Value(i), PN->Value(i+1), PC, VN->Value(i).Reversed());
724               else
725                 Pbest = FindBestPoint(PN->Value(i), PN->Value(i+1), PC, VN->Value(i));
726               xc += Pbest.X();
727               yc += Pbest.Y();
728               zc += Pbest.Z();
729             }
730             gp_Pnt PCbest(xc/4., yc/4., zc/4.);
731
732             // check PCbest
733             double height = PCbest.Distance(PC);
734             if(height<1.e-6) {
735               // create new PCbest using a bit shift along VNorm
736               PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
737             }
738             else {
739               // check possible intersection with other faces
740               gp_Pnt Pint;
741               bool check = CheckIntersection(PCbest, PC, Pint, aMesh, aShape, face);
742               if(check) {
743                 //cout<<"--PC("<<PC.X()<<","<<PC.Y()<<","<<PC.Z()<<")"<<endl;
744                 //cout<<"  PCbest("<<PCbest.X()<<","<<PCbest.Y()<<","<<PCbest.Z()<<")"<<endl;
745                 double dist = PC.Distance(Pint)/3.;
746                 gp_Dir aDir(gp_Vec(PC,PCbest));
747                 PCbest = PC.XYZ() + aDir.XYZ() * dist;
748               }
749               else {
750                 gp_Vec VB(PC,PCbest);
751                 gp_Pnt PCbestTmp = PC.XYZ() + VB.XYZ() * 3.0;
752                 check = CheckIntersection(PCbestTmp, PC, Pint, aMesh, aShape, face);
753                 if(check) {
754                   double dist = PC.Distance(Pint)/3.;
755                   if(dist<height) {
756                     gp_Dir aDir(gp_Vec(PC,PCbest));
757                     PCbest = PC.XYZ() + aDir.XYZ() * dist;
758                   }
759                 }
760               }
761             }
762             // create node for PCbest
763             SMDS_MeshNode* NewNode = helper.AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
764
765             // add triangles to result map
766             for(i=0; i<4; i++)
767             {
768               trias.push_back ( meshDS->AddFace( NewNode, FNodes[i], FNodes[i+1] ));
769               storeTmpElement( trias.back() );
770             }
771             // create a pyramid
772             if ( isRev ) swap( FNodes[1], FNodes[3]);
773             SMDS_MeshVolume* aPyram =
774               helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
775             myPyramids.push_back(aPyram);
776
777             quads.push_back( face );
778             hasNewTrias = true;
779             break;
780
781           } // case QUAD:
782
783         } // switch ( stat )
784       } // end loop on elements on a face submesh
785
786       bool sourceSubMeshIsProxy = false;
787       if ( aProxyMesh )
788       {
789         // move proxy sub-mesh from other proxy mesh to this
790         sourceSubMeshIsProxy = takeProxySubMesh( aShapeFace, aProxyMesh );
791         // move also tmp elements added in mesh
792         takeTmpElemsInMesh( aProxyMesh );
793       }
794       if ( hasNewTrias )
795       {
796         SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh( aShapeFace );
797         prxSubMesh->ChangeElements( trias.begin(), trias.end() );
798
799         // delete tmp quadrangles removed from aProxyMesh
800         if ( sourceSubMeshIsProxy )
801         {
802           for ( unsigned i = 0; i < quads.size(); ++i )
803             removeTmpElement( quads[i] );
804
805           delete myElemSearcher;
806           myElemSearcher =
807             SMESH_MeshEditor(&aMesh).GetElementSearcher( aProxyMesh->GetFaces(aShape));
808         }
809       }
810     }
811   } // end for(TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
812
813   return Compute2ndPart(aMesh, myPyramids);
814 }
815
816 //================================================================================
817 /*!
818  * \brief Computes pyramids in mesh with no shape
819  */
820 //================================================================================
821
822 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh)
823 {
824   SMESH_ProxyMesh::setMesh( aMesh );
825   SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Triangle );
826   SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Quad_Triangle );
827   if ( aMesh.NbQuadrangles() < 1 )
828     return false;
829
830   vector<const SMDS_MeshElement*> myPyramids;
831   SMESH_MesherHelper helper(aMesh);
832   helper.IsQuadraticSubMesh(aMesh.GetShapeToMesh());
833   helper.SetElementsOnShape( true );
834
835   if ( !myElemSearcher )
836     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
837   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
838
839   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
840   SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh();
841
842   SMDS_FaceIteratorPtr fIt = meshDS->facesIterator(/*idInceasingOrder=*/true);
843   while( fIt->more()) 
844   {
845     const SMDS_MeshElement* face = fIt->next();
846     if ( !face ) continue;
847     // retrieve needed information about a face
848     Handle(TColgp_HArray1OfPnt) PN = new TColgp_HArray1OfPnt(1,5);
849     Handle(TColgp_HArray1OfVec) VN = new TColgp_HArray1OfVec(1,4);
850     vector<const SMDS_MeshNode*> FNodes(5);
851     gp_Pnt PC;
852     gp_Vec VNorm;
853     const SMDS_MeshElement* volumes[2];
854     int what = Preparation(face, PN, VN, FNodes, PC, VNorm, volumes);
855     if ( what == NOT_QUAD )
856       continue;
857     if ( volumes[0] && volumes[1] )
858       continue; // face is shared by two volumes - no space for a pyramid
859
860     if ( what == DEGEN_QUAD )
861     {
862       // degenerate face
863       // add a triangle to the proxy mesh
864       SMDS_MeshFace* NewFace;
865
866       // check orientation
867       double tmp = PN->Value(1).Distance(PN->Value(2)) + PN->Value(2).Distance(PN->Value(3));
868       // far points in VNorm direction
869       gp_Pnt Ptmp1 = PC.XYZ() + VNorm.XYZ() * tmp * 1.e6;
870       gp_Pnt Ptmp2 = PC.XYZ() - VNorm.XYZ() * tmp * 1.e6;
871       // check intersection for Ptmp1 and Ptmp2
872       bool IsRev = false;
873       bool IsOK1 = false;
874       bool IsOK2 = false;
875       double dist1 = RealLast();
876       double dist2 = RealLast();
877       gp_Pnt Pres1,Pres2;
878
879       gp_Ax1 line( PC, VNorm );
880       vector< const SMDS_MeshElement* > suspectElems;
881       searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectElems);
882
883       for ( int iF = 0; iF < suspectElems.size(); ++iF ) {
884         const SMDS_MeshElement* F = suspectElems[iF];
885         if(F==face) continue;
886         Handle(TColgp_HSequenceOfPnt) aContour = new TColgp_HSequenceOfPnt;
887         for ( int i = 0; i < 4; ++i )
888           aContour->Append( SMESH_MeshEditor::TNodeXYZ( F->GetNode(i) ));
889         gp_Pnt PPP;
890         if( !volumes[0] && HasIntersection(Ptmp1, PC, PPP, aContour) ) {
891           IsOK1 = true;
892           double tmp = PC.Distance(PPP);
893           if(tmp<dist1) {
894             Pres1 = PPP;
895             dist1 = tmp;
896           }
897         }
898         if( !volumes[1] && HasIntersection(Ptmp2, PC, PPP, aContour) ) {
899           IsOK2 = true;
900           double tmp = PC.Distance(PPP);
901           if(tmp<dist2) {
902             Pres2 = PPP;
903             dist2 = tmp;
904           }
905         }
906       }
907
908       if( IsOK1 && !IsOK2 ) {
909         // using existed direction
910       }
911       else if( !IsOK1 && IsOK2 ) {
912         // using opposite direction
913         IsRev = true;
914       }
915       else { // IsOK1 && IsOK2
916         double tmp1 = PC.Distance(Pres1);
917         double tmp2 = PC.Distance(Pres2);
918         if(tmp1<tmp2) {
919           // using existed direction
920         }
921         else {
922           // using opposite direction
923           IsRev = true;
924         }
925       }
926       if(!IsRev)
927         NewFace = meshDS->AddFace( FNodes[0], FNodes[1], FNodes[2] );
928       else
929         NewFace = meshDS->AddFace( FNodes[0], FNodes[2], FNodes[1] );
930       storeTmpElement( NewFace );
931       prxSubMesh->AddElement( NewFace );
932       continue;
933     }
934
935     // Case of non-degenerated quadrangle 
936
937     // Find pyramid peak
938
939     gp_XYZ PCbest(0., 0., 0.); // pyramid peak
940     int i = 1;
941     for(; i<=4; i++) {
942       gp_Pnt Pbest = FindBestPoint(PN->Value(i), PN->Value(i+1), PC, VN->Value(i));
943       PCbest += Pbest.XYZ();
944     }
945     PCbest /= 4;
946
947     double height = PC.Distance(PCbest); // pyramid height to precise
948     if(height<1.e-6) {
949       // create new PCbest using a bit shift along VNorm
950       PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
951       height = PC.Distance(PCbest);
952     }
953
954     // Restrict pyramid height by intersection with other faces
955     gp_Vec tmpDir(PC,PCbest); tmpDir.Normalize();
956     double tmp = PN->Value(1).Distance(PN->Value(3)) + PN->Value(2).Distance(PN->Value(4));
957     // far points: in (PC, PCbest) direction and vice-versa
958     gp_Pnt farPnt[2] = { PC.XYZ() + tmpDir.XYZ() * tmp * 1.e6,
959                          PC.XYZ() - tmpDir.XYZ() * tmp * 1.e6 };
960     // check intersection for farPnt1 and farPnt2
961     bool   intersected[2] = { false, false };
962     double dist       [2] = { RealLast(), RealLast() };
963     gp_Pnt intPnt[2];
964
965     gp_Ax1 line( PC, tmpDir );
966     vector< const SMDS_MeshElement* > suspectElems;
967     searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectElems);
968
969     for ( int iF = 0; iF < suspectElems.size(); ++iF )
970     {
971       const SMDS_MeshElement* F = suspectElems[iF];
972       if(F==face) continue;
973       Handle(TColgp_HSequenceOfPnt) aContour = new TColgp_HSequenceOfPnt;
974       int nbN = F->NbNodes() / ( F->IsQuadratic() ? 2 : 1 );
975       for ( i = 0; i < nbN; ++i )
976         aContour->Append( SMESH_MeshEditor::TNodeXYZ( F->GetNode(i) ));
977       gp_Pnt intP;
978       for ( int isRev = 0; isRev < 2; ++isRev )
979       {
980         if( !volumes[isRev] && HasIntersection(farPnt[isRev], PC, intP, aContour) ) {
981           intersected[isRev] = true;
982           double d = PC.Distance( intP );
983           if( d < dist[isRev] )
984           {
985             intPnt[isRev] = intP;
986             dist  [isRev] = d;
987           }
988         }
989       }
990     }
991
992     // Create one or two pyramids
993
994     for ( int isRev = 0; isRev < 2; ++isRev )
995     {
996       if( !intersected[isRev] ) continue;
997       double pyramidH = Min( height, PC.Distance(intPnt[isRev])/3.);
998       PCbest = PC.XYZ() + tmpDir.XYZ() * (isRev ? -pyramidH : pyramidH);
999
1000       // create node for PCbest
1001       SMDS_MeshNode* NewNode = helper.AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
1002
1003       // add triangles to result map
1004       for(i=0; i<4; i++) {
1005         SMDS_MeshFace* NewFace;
1006         if(isRev)
1007           NewFace = meshDS->AddFace( NewNode, FNodes[i], FNodes[i+1] );
1008         else
1009           NewFace = meshDS->AddFace( NewNode, FNodes[i+1], FNodes[i] );
1010         storeTmpElement( NewFace );
1011         prxSubMesh->AddElement( NewFace );
1012       }
1013       // create a pyramid
1014       SMDS_MeshVolume* aPyram;
1015       if(isRev)
1016         aPyram = helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
1017       else
1018         aPyram = helper.AddVolume( FNodes[0], FNodes[3], FNodes[2], FNodes[1], NewNode );
1019       myPyramids.push_back(aPyram);
1020     }
1021   } // end loop on all faces
1022
1023   return Compute2ndPart(aMesh, myPyramids);
1024 }
1025
1026 //================================================================================
1027 /*!
1028  * \brief Update created pyramids and faces to avoid their intersection
1029  */
1030 //================================================================================
1031
1032 bool StdMeshers_QuadToTriaAdaptor::Compute2ndPart(SMESH_Mesh&                            aMesh,
1033                                                   const vector<const SMDS_MeshElement*>& myPyramids)
1034 {
1035   if(myPyramids.empty())
1036     return true;
1037
1038   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1039   int i, j, k, myShapeID = myPyramids[0]->GetNode(4)->getshapeId();
1040
1041   if ( !myElemSearcher )
1042     myElemSearcher = SMESH_MeshEditor(&aMesh).GetElementSearcher();
1043   SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
1044
1045   set<const SMDS_MeshNode*> nodesToMove;
1046
1047   // check adjacent pyramids
1048
1049   for ( i = 0; i <  myPyramids.size(); ++i )
1050   {
1051     const SMDS_MeshElement* PrmI = myPyramids[i];
1052     MergeAdjacent( PrmI, nodesToMove );
1053   }
1054
1055   // iterate on all pyramids
1056   for ( i = 0; i <  myPyramids.size(); ++i )
1057   {
1058     const SMDS_MeshElement* PrmI = myPyramids[i];
1059
1060     // compare PrmI with all the rest pyramids
1061
1062     // collect adjacent pyramids and nodes coordinates of PrmI
1063     set<const SMDS_MeshElement*> checkedPyrams;
1064     vector<gp_Pnt> PsI(5);
1065     for(k=0; k<5; k++) // loop on 4 base nodes of PrmI
1066     {
1067       const SMDS_MeshNode* n = PrmI->GetNode(k);
1068       PsI[k] = SMESH_MeshEditor::TNodeXYZ( n );
1069       SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
1070       while ( vIt->more() )
1071         checkedPyrams.insert( vIt->next() );
1072     }
1073
1074     // check intersection with distant pyramids
1075     for(k=0; k<4; k++) // loop on 4 base nodes of PrmI
1076     {
1077       gp_Vec Vtmp(PsI[k],PsI[4]);
1078       gp_Pnt Pshift = PsI[k].XYZ() + Vtmp.XYZ() * 0.01; // base node moved a bit to apex
1079
1080       gp_Ax1 line( PsI[k], Vtmp );
1081       vector< const SMDS_MeshElement* > suspectPyrams;
1082       searcher->GetElementsNearLine( line, SMDSAbs_Volume, suspectPyrams);
1083
1084       for ( j = 0; j < suspectPyrams.size(); ++j )
1085       {
1086         const SMDS_MeshElement* PrmJ = suspectPyrams[j];
1087         if ( PrmJ == PrmI || PrmJ->NbCornerNodes() != 5 )
1088           continue;
1089         if ( myShapeID != PrmJ->GetNode(4)->getshapeId())
1090           continue; // pyramid from other SOLID
1091         if ( PrmI->GetNode(4) == PrmJ->GetNode(4) )
1092           continue; // pyramids PrmI and PrmJ already merged
1093         if ( !checkedPyrams.insert( PrmJ ).second )
1094           continue; // already checked
1095
1096         TXyzIterator xyzIt( PrmJ->nodesIterator() );
1097         vector<gp_Pnt> PsJ( xyzIt, TXyzIterator() );
1098
1099         gp_Pnt Pint;
1100         bool hasInt = 
1101           ( HasIntersection3( Pshift, PsI[4], Pint, PsJ[0], PsJ[1], PsJ[4]) ||
1102             HasIntersection3( Pshift, PsI[4], Pint, PsJ[1], PsJ[2], PsJ[4]) ||
1103             HasIntersection3( Pshift, PsI[4], Pint, PsJ[2], PsJ[3], PsJ[4]) ||
1104             HasIntersection3( Pshift, PsI[4], Pint, PsJ[3], PsJ[0], PsJ[4]) );
1105
1106         for(k=0; k<4 && !hasInt; k++) {
1107           gp_Vec Vtmp(PsJ[k],PsJ[4]);
1108           gp_Pnt Pshift = PsJ[k].XYZ() + Vtmp.XYZ() * 0.01;
1109           hasInt = 
1110             ( HasIntersection3( Pshift, PsJ[4], Pint, PsI[0], PsI[1], PsI[4]) ||
1111               HasIntersection3( Pshift, PsJ[4], Pint, PsI[1], PsI[2], PsI[4]) ||
1112               HasIntersection3( Pshift, PsJ[4], Pint, PsI[2], PsI[3], PsI[4]) ||
1113               HasIntersection3( Pshift, PsJ[4], Pint, PsI[3], PsI[0], PsI[4]) );
1114         }
1115
1116         if ( hasInt )
1117         {
1118           // count common nodes of base faces of two pyramids
1119           int nbc = 0;
1120           for (k=0; k<4; k++)
1121             nbc += int ( PrmI->GetNodeIndex( PrmJ->GetNode(k) ) >= 0 );
1122
1123           if ( nbc == 4 )
1124             continue; // pyrams have a common base face
1125
1126           if(nbc>0)
1127           {
1128             // Merge the two pyramids and others already merged with them
1129             MergePiramids( PrmI, PrmJ, nodesToMove );
1130           }
1131           else { // nbc==0
1132
1133             // decrease height of pyramids
1134             gp_XYZ PCi(0,0,0), PCj(0,0,0);
1135             for(k=0; k<4; k++) {
1136               PCi += PsI[k].XYZ();
1137               PCj += PsJ[k].XYZ();
1138             }
1139             PCi /= 4; PCj /= 4; 
1140             gp_Vec VN1(PCi,PsI[4]);
1141             gp_Vec VN2(PCj,PsJ[4]);
1142             gp_Vec VI1(PCi,Pint);
1143             gp_Vec VI2(PCj,Pint);
1144             double ang1 = fabs(VN1.Angle(VI1));
1145             double ang2 = fabs(VN2.Angle(VI2));
1146             double coef1 = 0.5 - (( ang1<PI/3 ) ? cos(ang1)*0.25 : 0 );
1147             double coef2 = 0.5 - (( ang2<PI/3 ) ? cos(ang2)*0.25 : 0 ); // cos(ang2) ?
1148 //             double coef2 = 0.5;
1149 //             if(ang2<PI/3)
1150 //               coef2 -= cos(ang1)*0.25;
1151
1152             VN1.Scale(coef1);
1153             VN2.Scale(coef2);
1154             SMDS_MeshNode* aNode1 = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
1155             aNode1->setXYZ( PCi.X()+VN1.X(), PCi.Y()+VN1.Y(), PCi.Z()+VN1.Z() );
1156             SMDS_MeshNode* aNode2 = const_cast<SMDS_MeshNode*>(PrmJ->GetNode(4));
1157             aNode2->setXYZ( PCj.X()+VN2.X(), PCj.Y()+VN2.Y(), PCj.Z()+VN2.Z() );
1158             nodesToMove.insert( aNode1 );
1159             nodesToMove.insert( aNode2 );
1160           }
1161           // fix intersections that could appear after apex movement
1162           MergeAdjacent( PrmI, nodesToMove );
1163           MergeAdjacent( PrmJ, nodesToMove );
1164
1165         } // end if(hasInt)
1166       } // loop on suspectPyrams
1167     }  // loop on 4 base nodes of PrmI
1168
1169   } // loop on all pyramids
1170
1171   if( !nodesToMove.empty() && !meshDS->IsEmbeddedMode() )
1172   {
1173     set<const SMDS_MeshNode*>::iterator n = nodesToMove.begin();
1174     for ( ; n != nodesToMove.end(); ++n )
1175       meshDS->MoveNode( *n, (*n)->X(), (*n)->Y(), (*n)->Z() );
1176   }
1177
1178   // erase removed triangles from the proxy mesh
1179   if ( !myRemovedTrias.empty() )
1180   {
1181     for ( int i = 0; i <= meshDS->MaxShapeIndex(); ++i )
1182       if ( SMESH_ProxyMesh::SubMesh* sm = findProxySubMesh(i))
1183       {
1184         vector<const SMDS_MeshElement *> faces;
1185         faces.reserve( sm->NbElements() );
1186         SMDS_ElemIteratorPtr fIt = sm->GetElements();
1187         while ( fIt->more() )
1188         {
1189           const SMDS_MeshElement* tria = fIt->next();
1190           set<const SMDS_MeshElement*>::iterator rmTria = myRemovedTrias.find( tria );
1191           if ( rmTria != myRemovedTrias.end() )
1192             myRemovedTrias.erase( rmTria );
1193           else
1194             faces.push_back( tria );
1195         }
1196         sm->ChangeElements( faces.begin(), faces.end() );
1197       }
1198   }
1199
1200   myDegNodes.clear();
1201
1202   delete myElemSearcher;
1203   myElemSearcher=0;
1204
1205   return true;
1206 }
1207
1208 //================================================================================
1209 /*!
1210  * \brief Return list of created triangles for given face
1211  */
1212 //================================================================================
1213
1214 // const list<const SMDS_MeshFace* >* StdMeshers_QuadToTriaAdaptor::GetTriangles (const SMDS_MeshElement* aQuad)
1215 // {
1216 //   TQuad2Trias::iterator it = myResMap.find(aQuad);
1217 //   return ( it != myResMap.end() ?  & it->second : 0 );
1218 // }