1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46 #include "StdMeshers_ViscousLayers2D.hxx"
48 #include <Adaptor3d_HSurface.hxx>
49 #include <BRepAdaptor_Curve.hxx>
50 #include <BRepAdaptor_Curve2d.hxx>
51 #include <BRepAdaptor_Surface.hxx>
52 #include <BRepLProp_SLProps.hxx>
53 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Bnd_B2d.hxx>
56 #include <Bnd_B3d.hxx>
58 #include <GCPnts_AbscissaPoint.hxx>
59 #include <GCPnts_TangentialDeflection.hxx>
60 #include <Geom2d_Circle.hxx>
61 #include <Geom2d_Line.hxx>
62 #include <Geom2d_TrimmedCurve.hxx>
63 #include <GeomAdaptor_Curve.hxx>
64 #include <GeomLib.hxx>
65 #include <Geom_Circle.hxx>
66 #include <Geom_Curve.hxx>
67 #include <Geom_Line.hxx>
68 #include <Geom_TrimmedCurve.hxx>
69 #include <Precision.hxx>
70 #include <Standard_ErrorHandler.hxx>
71 #include <Standard_Failure.hxx>
72 #include <TColStd_Array1OfReal.hxx>
74 #include <TopExp_Explorer.hxx>
75 #include <TopTools_IndexedMapOfShape.hxx>
76 #include <TopTools_ListOfShape.hxx>
77 #include <TopTools_MapIteratorOfMapOfShape.hxx>
78 #include <TopTools_MapOfShape.hxx>
80 #include <TopoDS_Edge.hxx>
81 #include <TopoDS_Face.hxx>
82 #include <TopoDS_Vertex.hxx>
84 #include <gp_Cone.hxx>
85 #include <gp_Sphere.hxx>
97 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
101 #define BLOCK_INFLATION // of individual _LayerEdge's
102 #define OLD_NEF_POLYGON
106 //================================================================================
111 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
113 const double theMinSmoothCosin = 0.1;
114 const double theSmoothThickToElemSizeRatio = 0.3;
115 const double theMinSmoothTriaAngle = 30;
116 const double theMinSmoothQuadAngle = 45;
118 // what part of thickness is allowed till intersection
119 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
120 const double theThickToIntersection = 1.5;
122 bool needSmoothing( double cosin, double tgtThick, double elemSize )
124 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
126 double getSmoothingThickness( double cosin, double elemSize )
128 return theSmoothThickToElemSizeRatio * elemSize / cosin;
132 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
133 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
135 struct _MeshOfSolid : public SMESH_ProxyMesh,
136 public SMESH_subMeshEventListenerData
138 bool _n2nMapComputed;
139 SMESH_ComputeErrorPtr _warning;
141 _MeshOfSolid( SMESH_Mesh* mesh)
142 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
144 SMESH_ProxyMesh::setMesh( *mesh );
147 // returns submesh for a geom face
148 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
150 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
151 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
153 void setNode2Node(const SMDS_MeshNode* srcNode,
154 const SMDS_MeshNode* proxyNode,
155 const SMESH_ProxyMesh::SubMesh* subMesh)
157 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
160 //--------------------------------------------------------------------------------
162 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
163 * It is used to clear an inferior dim sub-meshes modified by viscous layers
165 class _ShrinkShapeListener : SMESH_subMeshEventListener
167 _ShrinkShapeListener()
168 : SMESH_subMeshEventListener(/*isDeletable=*/false,
169 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
171 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
172 virtual void ProcessEvent(const int event,
174 SMESH_subMesh* solidSM,
175 SMESH_subMeshEventListenerData* data,
176 const SMESH_Hypothesis* hyp)
178 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
180 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
184 //--------------------------------------------------------------------------------
186 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
187 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
188 * delete the data as soon as it has been used
190 class _ViscousListener : SMESH_subMeshEventListener
193 SMESH_subMeshEventListener(/*isDeletable=*/false,
194 "StdMeshers_ViscousLayers::_ViscousListener") {}
195 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
197 virtual void ProcessEvent(const int event,
199 SMESH_subMesh* subMesh,
200 SMESH_subMeshEventListenerData* data,
201 const SMESH_Hypothesis* hyp)
203 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
204 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
205 SMESH_subMesh::SUBMESH_COMPUTED != event ))
207 // delete SMESH_ProxyMesh containing temporary faces
208 subMesh->DeleteEventListener( this );
211 // Finds or creates proxy mesh of the solid
212 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
213 const TopoDS_Shape& solid,
216 if ( !mesh ) return 0;
217 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
218 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
219 if ( !data && toCreate )
221 data = new _MeshOfSolid(mesh);
222 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
223 sm->SetEventListener( Get(), data, sm );
227 // Removes proxy mesh of the solid
228 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
230 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
234 //================================================================================
236 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
237 * the main shape when sub-mesh of the main shape is cleared,
238 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
241 //================================================================================
243 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
245 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
246 SMESH_subMeshEventListenerData* data =
247 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
250 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
251 data->mySubMeshes.end())
252 data->mySubMeshes.push_back( sub );
256 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
257 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
261 //--------------------------------------------------------------------------------
263 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
264 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
265 * The class is used to check validity of face or volumes around a smoothed node;
266 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
270 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
271 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
272 _Simplex(const SMDS_MeshNode* nPrev=0,
273 const SMDS_MeshNode* nNext=0,
274 const SMDS_MeshNode* nOpp=0)
275 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
276 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
278 const double M[3][3] =
279 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
280 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
281 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
282 vol = ( + M[0][0] * M[1][1] * M[2][2]
283 + M[0][1] * M[1][2] * M[2][0]
284 + M[0][2] * M[1][0] * M[2][1]
285 - M[0][0] * M[1][2] * M[2][1]
286 - M[0][1] * M[1][0] * M[2][2]
287 - M[0][2] * M[1][1] * M[2][0]);
290 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
292 SMESH_TNodeXYZ pSrc( nSrc );
293 return IsForward( &pSrc, &pTgt, vol );
295 bool IsForward(const gp_XY& tgtUV,
296 const SMDS_MeshNode* smoothedNode,
297 const TopoDS_Face& face,
298 SMESH_MesherHelper& helper,
299 const double refSign) const
301 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
302 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
303 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
305 return d*refSign > 1e-100;
307 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
309 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
310 if ( !_nOpp ) // triangle
312 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
313 double tp2 = tp.SquareMagnitude();
314 double pn2 = pn.SquareMagnitude();
315 double nt2 = nt.SquareMagnitude();
317 if ( tp2 < pn2 && tp2 < nt2 )
318 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
319 else if ( pn2 < nt2 )
320 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
322 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
324 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
325 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
326 return minAngle < theMaxCos2;
330 SMESH_TNodeXYZ pOpp( _nOpp );
331 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
332 double tp2 = tp.SquareMagnitude();
333 double po2 = po.SquareMagnitude();
334 double on2 = on.SquareMagnitude();
335 double nt2 = nt.SquareMagnitude();
336 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
337 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
338 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
339 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
341 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
342 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
343 return minAngle < theMaxCos2;
346 bool IsNeighbour(const _Simplex& other) const
348 return _nPrev == other._nNext || _nNext == other._nPrev;
350 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
351 static void GetSimplices( const SMDS_MeshNode* node,
352 vector<_Simplex>& simplices,
353 const set<TGeomID>& ingnoreShapes,
354 const _SolidData* dataToCheckOri = 0,
355 const bool toSort = false);
356 static void SortSimplices(vector<_Simplex>& simplices);
358 //--------------------------------------------------------------------------------
360 * Structure used to take into account surface curvature while smoothing
365 double _k; // factor to correct node smoothed position
366 double _h2lenRatio; // avgNormProj / (2*avgDist)
367 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
369 static _Curvature* New( double avgNormProj, double avgDist )
372 if ( fabs( avgNormProj / avgDist ) > 1./200 )
375 c->_r = avgDist * avgDist / avgNormProj;
376 c->_k = avgDist * avgDist / c->_r / c->_r;
377 //c->_k = avgNormProj / c->_r;
378 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
379 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
381 c->_uv.SetCoord( 0., 0. );
385 double lenDelta(double len) const { return _k * ( _r + len ); }
386 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
388 //--------------------------------------------------------------------------------
392 struct _EdgesOnShape;
394 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
396 //--------------------------------------------------------------------------------
398 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
399 * and a node of the most internal layer (_nodes.back())
403 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
405 vector< const SMDS_MeshNode*> _nodes;
407 gp_XYZ _normal; // to boundary of solid
408 vector<gp_XYZ> _pos; // points computed during inflation
409 double _len; // length achived with the last inflation step
410 double _maxLen; // maximal possible length
411 double _cosin; // of angle (_normal ^ surface)
412 double _minAngle; // of _simplices
413 double _lenFactor; // to compute _len taking _cosin into account
416 // simplices connected to the source node (_nodes[0]);
417 // used for smoothing and quality check of _LayerEdge's based on the FACE
418 vector<_Simplex> _simplices;
419 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
420 PSmooFun _smooFunction; // smoothing function
421 _Curvature* _curvature;
422 // data for smoothing of _LayerEdge's based on the EDGE
423 _2NearEdges* _2neibors;
425 enum EFlags { TO_SMOOTH = 1,
426 MOVED = 2, // set by _neibors[i]->SetNewLength()
427 SMOOTHED = 4, // set by this->Smooth()
428 DIFFICULT = 8, // near concave VERTEX
429 ON_CONCAVE_FACE = 16,
430 BLOCKED = 32, // not to inflate any more
431 INTERSECTED = 64, // close intersection with a face found
432 NORMAL_UPDATED = 128,
433 MARKED = 256, // local usage
434 MULTI_NORMAL = 512, // a normal is invisible by some of surrounding faces
435 NEAR_BOUNDARY = 1024,// is near FACE boundary forcing smooth
436 SMOOTHED_C1 = 2048,// is on _eosC1
437 DISTORTED = 4096,// was bad before smoothing
438 RISKY_SWOL = 8192 // SWOL is parallel to a source FACE
440 bool Is ( EFlags f ) const { return _flags & f; }
441 void Set ( EFlags f ) { _flags |= f; }
442 void Unset( EFlags f ) { _flags &= ~f; }
444 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
445 bool SetNewLength2d( Handle(Geom_Surface)& surface,
446 const TopoDS_Face& F,
448 SMESH_MesherHelper& helper );
449 void SetDataByNeighbors( const SMDS_MeshNode* n1,
450 const SMDS_MeshNode* n2,
451 const _EdgesOnShape& eos,
452 SMESH_MesherHelper& helper);
453 void Block( _SolidData& data );
454 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
455 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
456 const TNode2Edge& n2eMap);
457 void SmoothPos( const vector< double >& segLen, const double tol );
458 int Smooth(const int step, const bool isConcaveFace, bool findBest);
459 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
460 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
461 void SmoothWoCheck();
462 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
463 const TopoDS_Face& F,
464 SMESH_MesherHelper& helper);
465 void MoveNearConcaVer( const _EdgesOnShape* eov,
466 const _EdgesOnShape* eos,
468 vector< _LayerEdge* > & badSmooEdges);
469 bool FindIntersection( SMESH_ElementSearcher& searcher,
471 const double& epsilon,
473 const SMDS_MeshElement** face = 0);
474 bool SegTriaInter( const gp_Ax1& lastSegment,
479 const double& epsilon) const;
480 bool SegTriaInter( const gp_Ax1& lastSegment,
481 const SMDS_MeshNode* n0,
482 const SMDS_MeshNode* n1,
483 const SMDS_MeshNode* n2,
485 const double& epsilon) const
486 { return SegTriaInter( lastSegment,
487 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
490 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
491 const gp_XYZ& PrevCheckPos() const { return _pos[ Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0 ]; }
492 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
493 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
494 bool IsOnEdge() const { return _2neibors; }
495 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
496 void SetCosin( double cosin );
497 void SetNormal( const gp_XYZ& n ) { _normal = n; }
498 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
499 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
500 void SetSmooLen( double len ) { // set _len at which smoothing is needed
501 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
503 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
505 gp_XYZ smoothLaplacian();
506 gp_XYZ smoothAngular();
507 gp_XYZ smoothLengthWeighted();
508 gp_XYZ smoothCentroidal();
509 gp_XYZ smoothNefPolygon();
511 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
512 static const int theNbSmooFuns = FUN_NB;
513 static PSmooFun _funs[theNbSmooFuns];
514 static const char* _funNames[theNbSmooFuns+1];
515 int smooFunID( PSmooFun fun=0) const;
517 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
518 &_LayerEdge::smoothLengthWeighted,
519 &_LayerEdge::smoothCentroidal,
520 &_LayerEdge::smoothNefPolygon,
521 &_LayerEdge::smoothAngular };
522 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
530 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
532 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
533 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
536 //--------------------------------------------------------------------------------
538 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
542 gp_XY _pos, _dir, _inNorm;
543 bool IsOut( const gp_XY p, const double tol ) const
545 return _inNorm * ( p - _pos ) < -tol;
547 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
549 //const double eps = 1e-10;
550 double D = _dir.Crossed( hp._dir );
551 if ( fabs(D) < std::numeric_limits<double>::min())
553 gp_XY vec21 = _pos - hp._pos;
554 double u = hp._dir.Crossed( vec21 ) / D;
555 intPnt = _pos + _dir * u;
559 //--------------------------------------------------------------------------------
561 * Structure used to smooth a _LayerEdge based on an EDGE.
565 double _wgt [2]; // weights of _nodes
566 _LayerEdge* _edges[2];
568 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
571 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
572 const SMDS_MeshNode* tgtNode(bool is2nd) {
573 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
575 const SMDS_MeshNode* srcNode(bool is2nd) {
576 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
579 std::swap( _wgt [0], _wgt [1] );
580 std::swap( _edges[0], _edges[1] );
582 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
583 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
585 bool include( const _LayerEdge* e ) {
586 return ( _edges[0] == e || _edges[1] == e );
591 //--------------------------------------------------------------------------------
593 * \brief Layers parameters got by averaging several hypotheses
597 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
598 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
602 void Add( const StdMeshers_ViscousLayers* hyp )
607 _nbLayers = hyp->GetNumberLayers();
608 //_thickness += hyp->GetTotalThickness();
609 _thickness = Max( _thickness, hyp->GetTotalThickness() );
610 _stretchFactor += hyp->GetStretchFactor();
611 _method = hyp->GetMethod();
614 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
615 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
616 int GetNumberLayers() const { return _nbLayers; }
617 int GetMethod() const { return _method; }
619 bool UseSurfaceNormal() const
620 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
621 bool ToSmooth() const
622 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
623 bool IsOffsetMethod() const
624 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
627 int _nbLayers, _nbHyps, _method;
628 double _thickness, _stretchFactor;
631 //--------------------------------------------------------------------------------
633 * \brief _LayerEdge's on a shape and other shape data
637 vector< _LayerEdge* > _edges;
641 SMESH_subMesh * _subMesh;
642 // face or edge w/o layer along or near which _edges are inflated
644 bool _isRegularSWOL; // w/o singularities
645 // averaged StdMeshers_ViscousLayers parameters
648 _Smoother1D* _edgeSmoother;
649 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
650 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
652 vector< gp_XYZ > _faceNormals; // if _shape is FACE
653 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
655 Handle(ShapeAnalysis_Surface) _offsetSurf;
656 _LayerEdge* _edgeForOffset;
658 _SolidData* _data; // parent SOLID
660 TopAbs_ShapeEnum ShapeType() const
661 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
662 TopAbs_ShapeEnum SWOLType() const
663 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
664 bool HasC1( const _EdgesOnShape* other ) const
665 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
666 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
667 _SolidData& GetData() const { return *_data; }
669 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
672 //--------------------------------------------------------------------------------
674 * \brief Convex FACE whose radius of curvature is less than the thickness of
675 * layers. It is used to detect distortion of prisms based on a convex
676 * FACE and to update normals to enable further increasing the thickness
682 // edges whose _simplices are used to detect prism distortion
683 vector< _LayerEdge* > _simplexTestEdges;
685 // map a sub-shape to _SolidData::_edgesOnShape
686 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
690 bool GetCenterOfCurvature( _LayerEdge* ledge,
691 BRepLProp_SLProps& surfProp,
692 SMESH_MesherHelper& helper,
693 gp_Pnt & center ) const;
694 bool CheckPrisms() const;
697 //--------------------------------------------------------------------------------
699 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
700 * at inflation up to the full thickness. A detected collision
701 * is fixed in updateNormals()
703 struct _CollisionEdges
706 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
707 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
708 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
711 //--------------------------------------------------------------------------------
713 * \brief Data of a SOLID
717 typedef const StdMeshers_ViscousLayers* THyp;
719 TGeomID _index; // SOLID id
720 _MeshOfSolid* _proxyMesh;
722 list< TopoDS_Shape > _hypShapes;
723 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
724 set< TGeomID > _reversedFaceIds;
725 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
727 double _stepSize, _stepSizeCoeff, _geomSize;
728 const SMDS_MeshNode* _stepSizeNodes[2];
730 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
732 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
733 map< TGeomID, TNode2Edge* > _s2neMap;
734 // _LayerEdge's with underlying shapes
735 vector< _EdgesOnShape > _edgesOnShape;
737 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
738 // layers and a FACE w/o layers
739 // value: the shape (FACE or EDGE) to shrink mesh on.
740 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
741 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
743 // Convex FACEs whose radius of curvature is less than the thickness of layers
744 map< TGeomID, _ConvexFace > _convexFaces;
746 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
747 // the adjacent SOLID
748 set< TGeomID > _noShrinkShapes;
750 int _nbShapesToSmooth;
752 //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
754 vector< _CollisionEdges > _collisionEdges;
755 set< TGeomID > _concaveFaces;
757 double _maxThickness; // of all _hyps
758 double _minThickness; // of all _hyps
760 double _epsilon; // precision for SegTriaInter()
762 SMESH_MesherHelper* _helper;
764 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
766 :_solid(s), _proxyMesh(m), _helper(0) {}
769 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
770 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
772 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
773 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
774 return id2face == _convexFaces.end() ? 0 : & id2face->second;
776 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
777 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
778 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
779 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
781 SMESH_MesherHelper& GetHelper() const { return *_helper; }
784 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
785 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
786 _edgesOnShape[i]._edges[j]->Unset( _LayerEdge::MARKED );
788 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
789 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
791 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
793 //--------------------------------------------------------------------------------
795 * \brief Offset plane used in getNormalByOffset()
801 int _faceIndexNext[2];
802 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
805 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
807 void ComputeIntersectionLine( _OffsetPlane& pln );
808 gp_XYZ GetCommonPoint(bool& isFound) const;
809 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
811 //--------------------------------------------------------------------------------
813 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
815 struct _CentralCurveOnEdge
818 vector< gp_Pnt > _curvaCenters;
819 vector< _LayerEdge* > _ledges;
820 vector< gp_XYZ > _normals; // new normal for each of _ledges
821 vector< double > _segLength2;
824 TopoDS_Face _adjFace;
825 bool _adjFaceToSmooth;
827 void Append( const gp_Pnt& center, _LayerEdge* ledge )
829 if ( _curvaCenters.size() > 0 )
830 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
831 _curvaCenters.push_back( center );
832 _ledges.push_back( ledge );
833 _normals.push_back( ledge->_normal );
835 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
836 void SetShapes( const TopoDS_Edge& edge,
837 const _ConvexFace& convFace,
839 SMESH_MesherHelper& helper);
841 //--------------------------------------------------------------------------------
843 * \brief Data of node on a shrinked FACE
847 const SMDS_MeshNode* _node;
848 vector<_Simplex> _simplices; // for quality check
850 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
852 bool Smooth(int& badNb,
853 Handle(Geom_Surface)& surface,
854 SMESH_MesherHelper& helper,
855 const double refSign,
859 gp_XY computeAngularPos(vector<gp_XY>& uv,
860 const gp_XY& uvToFix,
861 const double refSign );
863 //--------------------------------------------------------------------------------
865 * \brief Builder of viscous layers
867 class _ViscousBuilder
872 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
873 const TopoDS_Shape& shape);
874 // check validity of hypotheses
875 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
876 const TopoDS_Shape& shape );
878 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
879 void RestoreListeners();
881 // computes SMESH_ProxyMesh::SubMesh::_n2n;
882 bool MakeN2NMap( _MeshOfSolid* pm );
886 bool findSolidsWithLayers();
887 bool findFacesWithLayers(const bool onlyWith=false);
888 void getIgnoreFaces(const TopoDS_Shape& solid,
889 const StdMeshers_ViscousLayers* hyp,
890 const TopoDS_Shape& hypShape,
891 set<TGeomID>& ignoreFaces);
892 bool makeLayer(_SolidData& data);
893 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
894 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
895 SMESH_MesherHelper& helper, _SolidData& data);
896 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
897 const TopoDS_Face& face,
898 SMESH_MesherHelper& helper,
900 bool shiftInside=false);
901 bool getFaceNormalAtSingularity(const gp_XY& uv,
902 const TopoDS_Face& face,
903 SMESH_MesherHelper& helper,
905 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
906 gp_XYZ getNormalByOffset( _LayerEdge* edge,
907 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
909 bool findNeiborsOnEdge(const _LayerEdge* edge,
910 const SMDS_MeshNode*& n1,
911 const SMDS_MeshNode*& n2,
914 void findSimplexTestEdges( _SolidData& data,
915 vector< vector<_LayerEdge*> >& edgesByGeom);
916 void computeGeomSize( _SolidData& data );
917 bool findShapesToSmooth( _SolidData& data);
918 void limitStepSizeByCurvature( _SolidData& data );
919 void limitStepSize( _SolidData& data,
920 const SMDS_MeshElement* face,
921 const _LayerEdge* maxCosinEdge );
922 void limitStepSize( _SolidData& data, const double minSize);
923 bool inflate(_SolidData& data);
924 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
925 int invalidateBadSmooth( _SolidData& data,
926 SMESH_MesherHelper& helper,
927 vector< _LayerEdge* >& badSmooEdges,
928 vector< _EdgesOnShape* >& eosC1,
930 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
931 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep, int smooStep=0, bool moveAll=false );
932 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
933 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
934 bool updateNormalsOfConvexFaces( _SolidData& data,
935 SMESH_MesherHelper& helper,
937 void updateNormalsOfC1Vertices( _SolidData& data );
938 bool updateNormalsOfSmoothed( _SolidData& data,
939 SMESH_MesherHelper& helper,
941 const double stepSize );
942 bool isNewNormalOk( _SolidData& data,
944 const gp_XYZ& newNormal);
945 bool refine(_SolidData& data);
947 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
948 SMESH_MesherHelper& helper,
949 const SMESHDS_SubMesh* faceSubMesh );
950 void restoreNoShrink( _LayerEdge& edge ) const;
951 void fixBadFaces(const TopoDS_Face& F,
952 SMESH_MesherHelper& helper,
955 set<const SMDS_MeshNode*> * involvedNodes=NULL);
956 bool addBoundaryElements();
958 bool error( const string& text, int solidID=-1 );
959 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
962 void makeGroupOfLE();
965 SMESH_ComputeErrorPtr _error;
967 vector< _SolidData > _sdVec;
970 //--------------------------------------------------------------------------------
972 * \brief Shrinker of nodes on the EDGE
976 TopoDS_Edge _geomEdge;
977 vector<double> _initU;
978 vector<double> _normPar;
979 vector<const SMDS_MeshNode*> _nodes;
980 const _LayerEdge* _edges[2];
983 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
984 void Compute(bool set3D, SMESH_MesherHelper& helper);
985 void RestoreParams();
986 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
987 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
988 const SMDS_MeshNode* TgtNode( bool is2nd ) const
989 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
990 const SMDS_MeshNode* SrcNode( bool is2nd ) const
991 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
993 //--------------------------------------------------------------------------------
995 * \brief Smoother of _LayerEdge's on EDGE.
999 struct OffPnt // point of the offsetted EDGE
1001 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1002 double _len; // length reached at previous inflation step
1003 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1004 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1006 vector< OffPnt > _offPoints;
1007 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1008 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1009 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1010 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1011 _EdgesOnShape& _eos;
1013 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1015 SMESH_MesherHelper& helper);
1017 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1018 _EdgesOnShape& eos )
1019 : _anaCurve( curveForSmooth ), _eos( eos )
1022 bool Perform(_SolidData& data,
1023 Handle(ShapeAnalysis_Surface)& surface,
1024 const TopoDS_Face& F,
1025 SMESH_MesherHelper& helper )
1027 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1031 return smoothAnalyticEdge( data, surface, F, helper );
1033 return smoothComplexEdge ( data, surface, F, helper );
1035 void prepare(_SolidData& data );
1037 bool smoothAnalyticEdge( _SolidData& data,
1038 Handle(ShapeAnalysis_Surface)& surface,
1039 const TopoDS_Face& F,
1040 SMESH_MesherHelper& helper);
1042 bool smoothComplexEdge( _SolidData& data,
1043 Handle(ShapeAnalysis_Surface)& surface,
1044 const TopoDS_Face& F,
1045 SMESH_MesherHelper& helper);
1047 void setNormalOnV( const bool is2nd,
1048 SMESH_MesherHelper& helper);
1050 _LayerEdge* getLEdgeOnV( bool is2nd )
1052 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1054 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1056 //--------------------------------------------------------------------------------
1058 * \brief Class of temporary mesh face.
1059 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1060 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1062 struct _TmpMeshFace : public SMDS_MeshElement
1064 vector<const SMDS_MeshNode* > _nn;
1065 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1066 int id, int faceID=-1, int idInFace=-1):
1067 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1068 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1069 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1070 virtual vtkIdType GetVtkType() const { return -1; }
1071 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1072 virtual SMDSAbs_GeometryType GetGeomType() const
1073 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1074 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1075 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1077 //--------------------------------------------------------------------------------
1079 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1081 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1083 _LayerEdge *_le1, *_le2;
1084 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1085 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1087 _nn[0]=_le1->_nodes[0];
1088 _nn[1]=_le1->_nodes.back();
1089 _nn[2]=_le2->_nodes.back();
1090 _nn[3]=_le2->_nodes[0];
1092 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1094 SMESH_TNodeXYZ p0s( _nn[0] );
1095 SMESH_TNodeXYZ p0t( _nn[1] );
1096 SMESH_TNodeXYZ p1t( _nn[2] );
1097 SMESH_TNodeXYZ p1s( _nn[3] );
1098 gp_XYZ v0 = p0t - p0s;
1099 gp_XYZ v1 = p1t - p1s;
1100 gp_XYZ v01 = p1s - p0s;
1101 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1106 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1108 _nn[0]=le1->_nodes[0];
1109 _nn[1]=le1->_nodes.back();
1110 _nn[2]=le2->_nodes.back();
1111 _nn[3]=le2->_nodes[0];
1115 //--------------------------------------------------------------------------------
1117 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1118 * \warning Location of a surface is ignored
1120 struct _NodeCoordHelper
1122 SMESH_MesherHelper& _helper;
1123 const TopoDS_Face& _face;
1124 Handle(Geom_Surface) _surface;
1125 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1127 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1128 : _helper( helper ), _face( F )
1132 TopLoc_Location loc;
1133 _surface = BRep_Tool::Surface( _face, loc );
1135 if ( _surface.IsNull() )
1136 _fun = & _NodeCoordHelper::direct;
1138 _fun = & _NodeCoordHelper::byUV;
1140 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1143 gp_XYZ direct(const SMDS_MeshNode* n) const
1145 return SMESH_TNodeXYZ( n );
1147 gp_XYZ byUV (const SMDS_MeshNode* n) const
1149 gp_XY uv = _helper.GetNodeUV( _face, n );
1150 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1154 //================================================================================
1156 * \brief Check angle between vectors
1158 //================================================================================
1160 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1162 double dot = v1 * v2; // cos * |v1| * |v2|
1163 double l1 = v1.SquareMagnitude();
1164 double l2 = v2.SquareMagnitude();
1165 return (( dot * cos >= 0 ) &&
1166 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1169 } // namespace VISCOUS_3D
1173 //================================================================================
1174 // StdMeshers_ViscousLayers hypothesis
1176 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1177 :SMESH_Hypothesis(hypId, studyId, gen),
1178 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1179 _method( SURF_OFFSET_SMOOTH )
1181 _name = StdMeshers_ViscousLayers::GetHypType();
1182 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1183 } // --------------------------------------------------------------------------------
1184 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1186 if ( faceIds != _shapeIds )
1187 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1188 if ( _isToIgnoreShapes != toIgnore )
1189 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1190 } // --------------------------------------------------------------------------------
1191 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1193 if ( thickness != _thickness )
1194 _thickness = thickness, NotifySubMeshesHypothesisModification();
1195 } // --------------------------------------------------------------------------------
1196 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1198 if ( _nbLayers != nb )
1199 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1200 } // --------------------------------------------------------------------------------
1201 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1203 if ( _stretchFactor != factor )
1204 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1205 } // --------------------------------------------------------------------------------
1206 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1208 if ( _method != method )
1209 _method = method, NotifySubMeshesHypothesisModification();
1210 } // --------------------------------------------------------------------------------
1211 SMESH_ProxyMesh::Ptr
1212 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1213 const TopoDS_Shape& theShape,
1214 const bool toMakeN2NMap) const
1216 using namespace VISCOUS_3D;
1217 _ViscousBuilder bulder;
1218 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1219 if ( err && !err->IsOK() )
1220 return SMESH_ProxyMesh::Ptr();
1222 vector<SMESH_ProxyMesh::Ptr> components;
1223 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1224 for ( ; exp.More(); exp.Next() )
1226 if ( _MeshOfSolid* pm =
1227 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1229 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1230 if ( !bulder.MakeN2NMap( pm ))
1231 return SMESH_ProxyMesh::Ptr();
1232 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1233 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1235 if ( pm->_warning && !pm->_warning->IsOK() )
1237 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1238 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1239 if ( !smError || smError->IsOK() )
1240 smError = pm->_warning;
1243 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1245 switch ( components.size() )
1249 case 1: return components[0];
1251 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1253 return SMESH_ProxyMesh::Ptr();
1254 } // --------------------------------------------------------------------------------
1255 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1257 save << " " << _nbLayers
1258 << " " << _thickness
1259 << " " << _stretchFactor
1260 << " " << _shapeIds.size();
1261 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1262 save << " " << _shapeIds[i];
1263 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1264 save << " " << _method;
1266 } // --------------------------------------------------------------------------------
1267 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1269 int nbFaces, faceID, shapeToTreat, method;
1270 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1271 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1272 _shapeIds.push_back( faceID );
1273 if ( load >> shapeToTreat ) {
1274 _isToIgnoreShapes = !shapeToTreat;
1275 if ( load >> method )
1276 _method = (ExtrusionMethod) method;
1279 _isToIgnoreShapes = true; // old behavior
1282 } // --------------------------------------------------------------------------------
1283 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1284 const TopoDS_Shape& theShape)
1288 } // --------------------------------------------------------------------------------
1289 SMESH_ComputeErrorPtr
1290 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1291 const TopoDS_Shape& theShape,
1292 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1294 VISCOUS_3D::_ViscousBuilder bulder;
1295 SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1296 if ( err && !err->IsOK() )
1297 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1299 theStatus = SMESH_Hypothesis::HYP_OK;
1303 // --------------------------------------------------------------------------------
1304 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1307 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1308 return IsToIgnoreShapes() ? !isIn : isIn;
1310 // END StdMeshers_ViscousLayers hypothesis
1311 //================================================================================
1313 namespace VISCOUS_3D
1315 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1319 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1320 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1321 gp_Pnt p = BRep_Tool::Pnt( fromV );
1322 double distF = p.SquareDistance( c->Value( f ));
1323 double distL = p.SquareDistance( c->Value( l ));
1324 c->D1(( distF < distL ? f : l), p, dir );
1325 if ( distL < distF ) dir.Reverse();
1328 //--------------------------------------------------------------------------------
1329 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1330 SMESH_MesherHelper& helper)
1333 double f,l; gp_Pnt p;
1334 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1335 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1336 double u = helper.GetNodeU( E, atNode );
1340 //--------------------------------------------------------------------------------
1341 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1342 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1344 //--------------------------------------------------------------------------------
1345 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1346 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1349 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1352 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1353 return getFaceDir( F, v, node, helper, ok );
1355 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1356 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1357 gp_Pnt p; gp_Vec du, dv, norm;
1358 surface->D1( uv.X(),uv.Y(), p, du,dv );
1361 double u = helper.GetNodeU( fromE, node, 0, &ok );
1363 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1364 if ( o == TopAbs_REVERSED )
1367 gp_Vec dir = norm ^ du;
1369 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1370 helper.IsClosedEdge( fromE ))
1372 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1373 else c->D1( f, p, dv );
1374 if ( o == TopAbs_REVERSED )
1376 gp_Vec dir2 = norm ^ dv;
1377 dir = dir.Normalized() + dir2.Normalized();
1381 //--------------------------------------------------------------------------------
1382 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1383 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1384 bool& ok, double* cosin)
1386 TopoDS_Face faceFrw = F;
1387 faceFrw.Orientation( TopAbs_FORWARD );
1388 //double f,l; TopLoc_Location loc;
1389 TopoDS_Edge edges[2]; // sharing a vertex
1392 TopoDS_Vertex VV[2];
1393 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1394 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1396 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1397 if ( SMESH_Algo::isDegenerated( e )) continue;
1398 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1399 if ( VV[1].IsSame( fromV )) {
1400 nbEdges += edges[ 0 ].IsNull();
1403 else if ( VV[0].IsSame( fromV )) {
1404 nbEdges += edges[ 1 ].IsNull();
1409 gp_XYZ dir(0,0,0), edgeDir[2];
1412 // get dirs of edges going fromV
1414 for ( size_t i = 0; i < nbEdges && ok; ++i )
1416 edgeDir[i] = getEdgeDir( edges[i], fromV );
1417 double size2 = edgeDir[i].SquareModulus();
1418 if (( ok = size2 > numeric_limits<double>::min() ))
1419 edgeDir[i] /= sqrt( size2 );
1421 if ( !ok ) return dir;
1423 // get angle between the 2 edges
1425 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1426 if ( Abs( angle ) < 5 * M_PI/180 )
1428 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1432 dir = edgeDir[0] + edgeDir[1];
1437 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1438 *cosin = Cos( angle );
1441 else if ( nbEdges == 1 )
1443 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1444 if ( cosin ) *cosin = 1.;
1454 //================================================================================
1456 * \brief Finds concave VERTEXes of a FACE
1458 //================================================================================
1460 bool getConcaveVertices( const TopoDS_Face& F,
1461 SMESH_MesherHelper& helper,
1462 set< TGeomID >* vertices = 0)
1464 // check angles at VERTEXes
1466 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1467 for ( size_t iW = 0; iW < wires.size(); ++iW )
1469 const int nbEdges = wires[iW]->NbEdges();
1470 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1472 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1474 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1475 int iE2 = ( iE1 + 1 ) % nbEdges;
1476 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1477 iE2 = ( iE2 + 1 ) % nbEdges;
1478 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1479 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1480 wires[iW]->Edge( iE2 ), F, V );
1481 if ( angle < -5. * M_PI / 180. )
1485 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1489 return vertices ? !vertices->empty() : false;
1492 //================================================================================
1494 * \brief Returns true if a FACE is bound by a concave EDGE
1496 //================================================================================
1498 bool isConcave( const TopoDS_Face& F,
1499 SMESH_MesherHelper& helper,
1500 set< TGeomID >* vertices = 0 )
1502 bool isConcv = false;
1503 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1505 gp_Vec2d drv1, drv2;
1507 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1508 for ( ; eExp.More(); eExp.Next() )
1510 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1511 if ( SMESH_Algo::isDegenerated( E )) continue;
1512 // check if 2D curve is concave
1513 BRepAdaptor_Curve2d curve( E, F );
1514 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1515 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1516 curve.Intervals( intervals, GeomAbs_C2 );
1517 bool isConvex = true;
1518 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1520 double u1 = intervals( i );
1521 double u2 = intervals( i+1 );
1522 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1523 double cross = drv1 ^ drv2;
1524 if ( E.Orientation() == TopAbs_REVERSED )
1526 isConvex = ( cross > -1e-9 ); // 0.1 );
1530 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1539 // check angles at VERTEXes
1540 if ( getConcaveVertices( F, helper, vertices ))
1546 //================================================================================
1548 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1549 * \param [in] face - the mesh face to treat
1550 * \param [in] nodeOnEdge - a node on the EDGE
1551 * \param [out] faceSize - the computed distance
1552 * \return bool - true if faceSize computed
1554 //================================================================================
1556 bool getDistFromEdge( const SMDS_MeshElement* face,
1557 const SMDS_MeshNode* nodeOnEdge,
1560 faceSize = Precision::Infinite();
1563 int nbN = face->NbCornerNodes();
1564 int iOnE = face->GetNodeIndex( nodeOnEdge );
1565 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1566 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1567 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1568 face->GetNode( iNext[1] ) };
1569 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1570 double segLen = -1.;
1571 // look for two neighbor not in-FACE nodes of face
1572 for ( int i = 0; i < 2; ++i )
1574 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1575 nNext[i]->GetID() < nodeOnEdge->GetID() )
1577 // look for an in-FACE node
1578 for ( int iN = 0; iN < nbN; ++iN )
1580 if ( iN == iOnE || iN == iNext[i] )
1582 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1583 gp_XYZ v = pInFace - segEnd;
1586 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1587 segLen = segVec.Modulus();
1589 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1590 faceSize = Min( faceSize, distToSeg );
1598 //================================================================================
1600 * \brief Return direction of axis or revolution of a surface
1602 //================================================================================
1604 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1607 switch ( surface.GetType() ) {
1610 gp_Cone cone = surface.Cone();
1611 axis = cone.Axis().Direction();
1614 case GeomAbs_Sphere:
1616 gp_Sphere sphere = surface.Sphere();
1617 axis = sphere.Position().Direction();
1620 case GeomAbs_SurfaceOfRevolution:
1622 axis = surface.AxeOfRevolution().Direction();
1625 //case GeomAbs_SurfaceOfExtrusion:
1626 case GeomAbs_OffsetSurface:
1628 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1629 return getRovolutionAxis( base->Surface(), axis );
1631 default: return false;
1636 //--------------------------------------------------------------------------------
1637 // DEBUG. Dump intermediate node positions into a python script
1638 // HOWTO use: run python commands written in a console to see
1639 // construction steps of viscous layers
1644 PyDump(SMESH_Mesh& m) {
1645 int tag = 3 + m.GetId();
1646 const char* fname = "/tmp/viscous.py";
1647 cout << "execfile('"<<fname<<"')"<<endl;
1648 py = new ofstream(fname);
1649 *py << "import SMESH" << endl
1650 << "from salome.smesh import smeshBuilder" << endl
1651 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1652 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1653 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1658 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1659 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1660 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1661 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1665 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1667 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1668 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1669 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1670 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1671 void _dumpFunction(const string& fun, int ln)
1672 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1673 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1674 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1675 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1676 void _dumpCmd(const string& txt, int ln)
1677 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1678 void dumpFunctionEnd()
1679 { if (py) *py<< " return"<< endl; }
1680 void dumpChangeNodes( const SMDS_MeshElement* f )
1681 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1682 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1683 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1684 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1688 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1689 #define dumpFunction(f) f
1691 #define dumpMoveComm(n,txt)
1692 #define dumpCmd(txt)
1693 #define dumpFunctionEnd()
1694 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1695 #define debugMsg( txt ) {}
1700 using namespace VISCOUS_3D;
1702 //================================================================================
1704 * \brief Constructor of _ViscousBuilder
1706 //================================================================================
1708 _ViscousBuilder::_ViscousBuilder()
1710 _error = SMESH_ComputeError::New(COMPERR_OK);
1714 //================================================================================
1716 * \brief Stores error description and returns false
1718 //================================================================================
1720 bool _ViscousBuilder::error(const string& text, int solidId )
1722 const string prefix = string("Viscous layers builder: ");
1723 _error->myName = COMPERR_ALGO_FAILED;
1724 _error->myComment = prefix + text;
1727 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1728 if ( !sm && !_sdVec.empty() )
1729 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1730 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1732 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1733 if ( smError && smError->myAlgo )
1734 _error->myAlgo = smError->myAlgo;
1736 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1738 // set KO to all solids
1739 for ( size_t i = 0; i < _sdVec.size(); ++i )
1741 if ( _sdVec[i]._index == solidId )
1743 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1744 if ( !sm->IsEmpty() )
1746 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1747 if ( !smError || smError->IsOK() )
1749 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1750 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1754 makeGroupOfLE(); // debug
1759 //================================================================================
1761 * \brief At study restoration, restore event listeners used to clear an inferior
1762 * dim sub-mesh modified by viscous layers
1764 //================================================================================
1766 void _ViscousBuilder::RestoreListeners()
1771 //================================================================================
1773 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1775 //================================================================================
1777 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1779 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1780 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1781 for ( ; fExp.More(); fExp.Next() )
1783 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1784 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1786 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1788 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1791 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1792 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1794 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1795 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1796 while( prxIt->more() )
1798 const SMDS_MeshElement* fSrc = srcIt->next();
1799 const SMDS_MeshElement* fPrx = prxIt->next();
1800 if ( fSrc->NbNodes() != fPrx->NbNodes())
1801 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1802 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1803 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1806 pm->_n2nMapComputed = true;
1810 //================================================================================
1812 * \brief Does its job
1814 //================================================================================
1816 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1817 const TopoDS_Shape& theShape)
1819 // TODO: set priority of solids during Gen::Compute()
1823 // check if proxy mesh already computed
1824 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1826 return error("No SOLID's in theShape"), _error;
1828 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1829 return SMESH_ComputeErrorPtr(); // everything already computed
1831 PyDump debugDump( theMesh );
1833 // TODO: ignore already computed SOLIDs
1834 if ( !findSolidsWithLayers())
1837 if ( !findFacesWithLayers() )
1840 for ( size_t i = 0; i < _sdVec.size(); ++i )
1842 if ( ! makeLayer(_sdVec[i]) )
1845 if ( _sdVec[i]._n2eMap.size() == 0 )
1848 if ( ! inflate(_sdVec[i]) )
1851 if ( ! refine(_sdVec[i]) )
1857 addBoundaryElements();
1859 makeGroupOfLE(); // debug
1865 //================================================================================
1867 * \brief Check validity of hypotheses
1869 //================================================================================
1871 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1872 const TopoDS_Shape& shape )
1876 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1877 return SMESH_ComputeErrorPtr(); // everything already computed
1880 findSolidsWithLayers();
1881 bool ok = findFacesWithLayers( true );
1883 // remove _MeshOfSolid's of _SolidData's
1884 for ( size_t i = 0; i < _sdVec.size(); ++i )
1885 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1890 return SMESH_ComputeErrorPtr();
1893 //================================================================================
1895 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1897 //================================================================================
1899 bool _ViscousBuilder::findSolidsWithLayers()
1902 TopTools_IndexedMapOfShape allSolids;
1903 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1904 _sdVec.reserve( allSolids.Extent());
1906 SMESH_Gen* gen = _mesh->GetGen();
1907 SMESH_HypoFilter filter;
1908 for ( int i = 1; i <= allSolids.Extent(); ++i )
1910 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1911 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1912 if ( !algo ) continue;
1913 // TODO: check if algo is hidden
1914 const list <const SMESHDS_Hypothesis *> & allHyps =
1915 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1916 _SolidData* soData = 0;
1917 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1918 const StdMeshers_ViscousLayers* viscHyp = 0;
1919 for ( ; hyp != allHyps.end(); ++hyp )
1920 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1922 TopoDS_Shape hypShape;
1923 filter.Init( filter.Is( viscHyp ));
1924 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1928 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1931 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1932 soData = & _sdVec.back();
1933 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1934 soData->_helper = new SMESH_MesherHelper( *_mesh );
1935 soData->_helper->SetSubShape( allSolids(i) );
1937 soData->_hyps.push_back( viscHyp );
1938 soData->_hypShapes.push_back( hypShape );
1941 if ( _sdVec.empty() )
1943 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1948 //================================================================================
1952 //================================================================================
1954 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1956 SMESH_MesherHelper helper( *_mesh );
1957 TopExp_Explorer exp;
1958 TopTools_IndexedMapOfShape solids;
1960 // collect all faces-to-ignore defined by hyp
1961 for ( size_t i = 0; i < _sdVec.size(); ++i )
1963 solids.Add( _sdVec[i]._solid );
1965 // get faces-to-ignore defined by each hyp
1966 typedef const StdMeshers_ViscousLayers* THyp;
1967 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1968 list< TFacesOfHyp > ignoreFacesOfHyps;
1969 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
1970 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1971 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1973 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1974 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1977 // fill _SolidData::_face2hyp and check compatibility of hypotheses
1978 const int nbHyps = _sdVec[i]._hyps.size();
1981 // check if two hypotheses define different parameters for the same FACE
1982 list< TFacesOfHyp >::iterator igFacesOfHyp;
1983 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1985 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1987 igFacesOfHyp = ignoreFacesOfHyps.begin();
1988 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1989 if ( ! igFacesOfHyp->first.count( faceID ))
1992 return error(SMESH_Comment("Several hypotheses define "
1993 "Viscous Layers on the face #") << faceID );
1994 hyp = igFacesOfHyp->second;
1997 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
1999 _sdVec[i]._ignoreFaceIds.insert( faceID );
2002 // check if two hypotheses define different number of viscous layers for
2003 // adjacent faces of a solid
2004 set< int > nbLayersSet;
2005 igFacesOfHyp = ignoreFacesOfHyps.begin();
2006 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2008 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2010 if ( nbLayersSet.size() > 1 )
2012 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2014 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2015 THyp hyp1 = 0, hyp2 = 0;
2016 while( const TopoDS_Shape* face = fIt->next() )
2018 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2019 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2020 if ( f2h != _sdVec[i]._face2hyp.end() )
2022 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2025 if ( hyp1 && hyp2 &&
2026 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2028 return error("Two hypotheses define different number of "
2029 "viscous layers on adjacent faces");
2033 } // if ( nbHyps > 1 )
2036 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2040 if ( onlyWith ) // is called to check hypotheses compatibility only
2043 // fill _SolidData::_reversedFaceIds
2044 for ( size_t i = 0; i < _sdVec.size(); ++i )
2046 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2047 for ( ; exp.More(); exp.Next() )
2049 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2050 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2051 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2052 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2053 helper.IsReversedSubMesh( face ))
2055 _sdVec[i]._reversedFaceIds.insert( faceID );
2060 // Find faces to shrink mesh on (solution 2 in issue 0020832);
2061 TopTools_IndexedMapOfShape shapes;
2062 for ( size_t i = 0; i < _sdVec.size(); ++i )
2065 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2066 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2068 const TopoDS_Shape& edge = shapes(iE);
2069 // find 2 faces sharing an edge
2071 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2072 while ( fIt->more())
2074 const TopoDS_Shape* f = fIt->next();
2075 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2076 FF[ int( !FF[0].IsNull()) ] = *f;
2078 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2079 // check presence of layers on them
2081 for ( int j = 0; j < 2; ++j )
2082 ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2083 if ( ignore[0] == ignore[1] )
2084 continue; // nothing interesting
2085 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2086 // check presence of layers on fWOL within an adjacent SOLID
2087 bool collision = false;
2088 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2089 while ( const TopoDS_Shape* solid = sIt->next() )
2090 if ( !solid->IsSame( _sdVec[i]._solid ))
2092 int iSolid = solids.FindIndex( *solid );
2093 int iFace = getMeshDS()->ShapeToIndex( fWOL );
2094 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2096 //_sdVec[i]._noShrinkShapes.insert( iFace );
2102 if ( !fWOL.IsNull())
2104 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2105 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2108 // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2109 // on the edge but shrink won't be performed
2110 _sdVec[i]._noShrinkShapes.insert( edgeInd );
2115 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2116 // the algo of the SOLID sharing the FACE does not support it
2117 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2118 for ( size_t i = 0; i < _sdVec.size(); ++i )
2120 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2121 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2123 const TopoDS_Shape& fWOL = e2f->second;
2124 const TGeomID edgeID = e2f->first;
2125 bool notShrinkFace = false;
2126 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2127 while ( soIt->more() )
2129 const TopoDS_Shape* solid = soIt->next();
2130 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2131 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2132 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2133 notShrinkFace = true;
2135 for ( ; iSolid < _sdVec.size(); ++iSolid )
2137 if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2138 if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2139 notShrinkFace = false;
2143 if ( notShrinkFace )
2145 _sdVec[i]._noShrinkShapes.insert( edgeID );
2147 // add VERTEXes of the edge in _noShrinkShapes
2148 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2149 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2150 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2152 // check if there is a collision with to-shrink-from EDGEs in iSolid
2153 if ( iSolid == _sdVec.size() )
2154 continue; // no VL in the solid
2156 TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2157 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2159 const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2160 const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2161 if ( eID == edgeID ||
2162 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2163 _sdVec[i]._noShrinkShapes.count( eID ))
2165 for ( int is1st = 0; is1st < 2; ++is1st )
2167 TopoDS_Vertex V = helper.IthVertex( is1st, E );
2168 if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2170 // _sdVec[i]._noShrinkShapes.insert( eID );
2171 // V = helper.IthVertex( !is1st, E );
2172 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2173 //iE = 0; // re-start the loop on EDGEs of fWOL
2174 return error("No way to make a conformal mesh with "
2175 "the given set of faces with layers", _sdVec[i]._index);
2181 } // while ( soIt->more() )
2182 } // loop on _sdVec[i]._shrinkShape2Shape
2183 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2185 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2187 for ( size_t i = 0; i < _sdVec.size(); ++i )
2190 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2191 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2193 const TopoDS_Shape& vertex = shapes(iV);
2194 // find faces WOL sharing the vertex
2195 vector< TopoDS_Shape > facesWOL;
2196 size_t totalNbFaces = 0;
2197 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2198 while ( fIt->more())
2200 const TopoDS_Shape* f = fIt->next();
2201 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2204 const int fID = getMeshDS()->ShapeToIndex( *f );
2205 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2206 !_sdVec[i]._noShrinkShapes.count( fID )*/)
2207 facesWOL.push_back( *f );
2210 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2211 continue; // no layers at this vertex or no WOL
2212 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2213 switch ( facesWOL.size() )
2217 helper.SetSubShape( facesWOL[0] );
2218 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2220 TopoDS_Shape seamEdge;
2221 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2222 while ( eIt->more() && seamEdge.IsNull() )
2224 const TopoDS_Shape* e = eIt->next();
2225 if ( helper.IsRealSeam( *e ) )
2228 if ( !seamEdge.IsNull() )
2230 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2234 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2239 // find an edge shared by 2 faces
2240 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2241 while ( eIt->more())
2243 const TopoDS_Shape* e = eIt->next();
2244 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2245 helper.IsSubShape( *e, facesWOL[1]))
2247 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2253 return error("Not yet supported case", _sdVec[i]._index);
2258 // add FACEs of other SOLIDs to _ignoreFaceIds
2259 for ( size_t i = 0; i < _sdVec.size(); ++i )
2262 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2264 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2266 if ( !shapes.Contains( exp.Current() ))
2267 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2274 //================================================================================
2276 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2278 //================================================================================
2280 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2281 const StdMeshers_ViscousLayers* hyp,
2282 const TopoDS_Shape& hypShape,
2283 set<TGeomID>& ignoreFaceIds)
2285 TopExp_Explorer exp;
2287 vector<TGeomID> ids = hyp->GetBndShapes();
2288 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2290 for ( size_t ii = 0; ii < ids.size(); ++ii )
2292 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2293 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2294 ignoreFaceIds.insert( ids[ii] );
2297 else // FACEs with layers are given
2299 exp.Init( solid, TopAbs_FACE );
2300 for ( ; exp.More(); exp.Next() )
2302 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2303 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2304 ignoreFaceIds.insert( faceInd );
2308 // ignore internal FACEs if inlets and outlets are specified
2309 if ( hyp->IsToIgnoreShapes() )
2311 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2312 TopExp::MapShapesAndAncestors( hypShape,
2313 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2315 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2317 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2318 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2321 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2323 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2328 //================================================================================
2330 * \brief Create the inner surface of the viscous layer and prepare data for infation
2332 //================================================================================
2334 bool _ViscousBuilder::makeLayer(_SolidData& data)
2336 // get all sub-shapes to make layers on
2337 set<TGeomID> subIds, faceIds;
2338 subIds = data._noShrinkShapes;
2339 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2340 for ( ; exp.More(); exp.Next() )
2342 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2343 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2344 faceIds.insert( fSubM->GetId() );
2347 // make a map to find new nodes on sub-shapes shared with other SOLID
2348 map< TGeomID, TNode2Edge* >::iterator s2ne;
2349 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2350 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2352 TGeomID shapeInd = s2s->first;
2353 for ( size_t i = 0; i < _sdVec.size(); ++i )
2355 if ( _sdVec[i]._index == data._index ) continue;
2356 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2357 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2358 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2360 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2366 // Create temporary faces and _LayerEdge's
2368 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2370 data._stepSize = Precision::Infinite();
2371 data._stepSizeNodes[0] = 0;
2373 SMESH_MesherHelper helper( *_mesh );
2374 helper.SetSubShape( data._solid );
2375 helper.SetElementsOnShape( true );
2377 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2378 TNode2Edge::iterator n2e2;
2380 // collect _LayerEdge's of shapes they are based on
2381 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2382 const int nbShapes = getMeshDS()->MaxShapeIndex();
2383 edgesByGeom.resize( nbShapes+1 );
2385 // set data of _EdgesOnShape's
2386 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2388 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2389 while ( smIt->more() )
2392 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2393 !faceIds.count( sm->GetId() ))
2395 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2398 // make _LayerEdge's
2399 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2401 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2402 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2403 SMESH_ProxyMesh::SubMesh* proxySub =
2404 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2406 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2407 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2409 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2410 while ( eIt->more() )
2412 const SMDS_MeshElement* face = eIt->next();
2413 double faceMaxCosin = -1;
2414 _LayerEdge* maxCosinEdge = 0;
2415 int nbDegenNodes = 0;
2417 newNodes.resize( face->NbCornerNodes() );
2418 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2420 const SMDS_MeshNode* n = face->GetNode( i );
2421 const int shapeID = n->getshapeId();
2422 const bool onDegenShap = helper.IsDegenShape( shapeID );
2423 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2428 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2429 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2430 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2431 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2441 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2442 if ( !(*n2e).second )
2445 _LayerEdge* edge = new _LayerEdge();
2446 edge->_nodes.push_back( n );
2448 edgesByGeom[ shapeID ]._edges.push_back( edge );
2449 const bool noShrink = data._noShrinkShapes.count( shapeID );
2451 SMESH_TNodeXYZ xyz( n );
2453 // set edge data or find already refined _LayerEdge and get data from it
2454 if (( !noShrink ) &&
2455 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2456 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2457 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2459 _LayerEdge* foundEdge = (*n2e2).second;
2460 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2461 foundEdge->_pos.push_back( lastPos );
2462 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2463 const_cast< SMDS_MeshNode* >
2464 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2470 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2472 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2475 if ( edge->_nodes.size() < 2 )
2476 edge->Block( data );
2477 //data._noShrinkShapes.insert( shapeID );
2479 dumpMove(edge->_nodes.back());
2481 if ( edge->_cosin > faceMaxCosin )
2483 faceMaxCosin = edge->_cosin;
2484 maxCosinEdge = edge;
2487 newNodes[ i ] = n2e->second->_nodes.back();
2490 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2492 if ( newNodes.size() - nbDegenNodes < 2 )
2495 // create a temporary face
2496 const SMDS_MeshElement* newFace =
2497 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2498 proxySub->AddElement( newFace );
2500 // compute inflation step size by min size of element on a convex surface
2501 if ( faceMaxCosin > theMinSmoothCosin )
2502 limitStepSize( data, face, maxCosinEdge );
2504 } // loop on 2D elements on a FACE
2505 } // loop on FACEs of a SOLID to create _LayerEdge's
2508 // Set _LayerEdge::_neibors
2509 TNode2Edge::iterator n2e;
2510 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2512 _EdgesOnShape& eos = data._edgesOnShape[iS];
2513 for ( size_t i = 0; i < eos._edges.size(); ++i )
2515 _LayerEdge* edge = eos._edges[i];
2516 TIDSortedNodeSet nearNodes;
2517 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2518 while ( fIt->more() )
2520 const SMDS_MeshElement* f = fIt->next();
2521 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2522 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2524 nearNodes.erase( edge->_nodes[0] );
2525 edge->_neibors.reserve( nearNodes.size() );
2526 TIDSortedNodeSet::iterator node = nearNodes.begin();
2527 for ( ; node != nearNodes.end(); ++node )
2528 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2529 edge->_neibors.push_back( n2e->second );
2533 data._epsilon = 1e-7;
2534 if ( data._stepSize < 1. )
2535 data._epsilon *= data._stepSize;
2537 if ( !findShapesToSmooth( data ))
2540 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2541 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2543 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2544 const SMDS_MeshNode* nn[2];
2545 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2547 _EdgesOnShape& eos = data._edgesOnShape[iS];
2548 for ( size_t i = 0; i < eos._edges.size(); ++i )
2550 _LayerEdge* edge = eos._edges[i];
2551 if ( edge->IsOnEdge() )
2553 // get neighbor nodes
2554 bool hasData = ( edge->_2neibors->_edges[0] );
2555 if ( hasData ) // _LayerEdge is a copy of another one
2557 nn[0] = edge->_2neibors->srcNode(0);
2558 nn[1] = edge->_2neibors->srcNode(1);
2560 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2564 // set neighbor _LayerEdge's
2565 for ( int j = 0; j < 2; ++j )
2567 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2568 return error("_LayerEdge not found by src node", data._index);
2569 edge->_2neibors->_edges[j] = n2e->second;
2572 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2575 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2577 _Simplex& s = edge->_simplices[j];
2578 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2579 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2582 // For an _LayerEdge on a degenerated EDGE, copy some data from
2583 // a corresponding _LayerEdge on a VERTEX
2584 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2585 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2587 // Generally we should not get here
2588 if ( eos.ShapeType() != TopAbs_EDGE )
2590 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2591 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2592 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2594 const _LayerEdge* vEdge = n2e->second;
2595 edge->_normal = vEdge->_normal;
2596 edge->_lenFactor = vEdge->_lenFactor;
2597 edge->_cosin = vEdge->_cosin;
2600 } // loop on data._edgesOnShape._edges
2601 } // loop on data._edgesOnShape
2603 // fix _LayerEdge::_2neibors on EDGEs to smooth
2604 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2605 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2606 // if ( !e2c->second.IsNull() )
2608 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2609 // data.Sort2NeiborsOnEdge( eos->_edges );
2616 //================================================================================
2618 * \brief Compute inflation step size by min size of element on a convex surface
2620 //================================================================================
2622 void _ViscousBuilder::limitStepSize( _SolidData& data,
2623 const SMDS_MeshElement* face,
2624 const _LayerEdge* maxCosinEdge )
2627 double minSize = 10 * data._stepSize;
2628 const int nbNodes = face->NbCornerNodes();
2629 for ( int i = 0; i < nbNodes; ++i )
2631 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2632 const SMDS_MeshNode* curN = face->GetNode( i );
2633 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2634 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2636 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2637 if ( dist < minSize )
2638 minSize = dist, iN = i;
2641 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2642 if ( newStep < data._stepSize )
2644 data._stepSize = newStep;
2645 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2646 data._stepSizeNodes[0] = face->GetNode( iN );
2647 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2651 //================================================================================
2653 * \brief Compute inflation step size by min size of element on a convex surface
2655 //================================================================================
2657 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2659 if ( minSize < data._stepSize )
2661 data._stepSize = minSize;
2662 if ( data._stepSizeNodes[0] )
2665 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2666 data._stepSizeCoeff = data._stepSize / dist;
2671 //================================================================================
2673 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2675 //================================================================================
2677 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2679 const int nbTestPnt = 5; // on a FACE sub-shape
2681 BRepLProp_SLProps surfProp( 2, 1e-6 );
2682 SMESH_MesherHelper helper( *_mesh );
2684 data._convexFaces.clear();
2686 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2688 _EdgesOnShape& eof = data._edgesOnShape[iS];
2689 if ( eof.ShapeType() != TopAbs_FACE ||
2690 data._ignoreFaceIds.count( eof._shapeID ))
2693 TopoDS_Face F = TopoDS::Face( eof._shape );
2694 SMESH_subMesh * sm = eof._subMesh;
2695 const TGeomID faceID = eof._shapeID;
2697 BRepAdaptor_Surface surface( F, false );
2698 surfProp.SetSurface( surface );
2700 bool isTooCurved = false;
2702 _ConvexFace cnvFace;
2703 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2704 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2705 while ( smIt->more() )
2708 const TGeomID subID = sm->GetId();
2709 // find _LayerEdge's of a sub-shape
2711 if (( eos = data.GetShapeEdges( subID )))
2712 cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2715 // check concavity and curvature and limit data._stepSize
2716 const double minCurvature =
2717 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2718 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2719 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2721 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2722 surfProp.SetParameters( uv.X(), uv.Y() );
2723 if ( !surfProp.IsCurvatureDefined() )
2725 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2727 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2730 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2732 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2736 } // loop on sub-shapes of the FACE
2738 if ( !isTooCurved ) continue;
2740 _ConvexFace & convFace =
2741 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2744 convFace._normalsFixed = false;
2746 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2747 // prism distortion.
2748 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2749 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2751 // there are _LayerEdge's on the FACE it-self;
2752 // select _LayerEdge's near EDGEs
2753 _EdgesOnShape& eos = * id2eos->second;
2754 for ( size_t i = 0; i < eos._edges.size(); ++i )
2756 _LayerEdge* ledge = eos._edges[ i ];
2757 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2758 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2760 convFace._simplexTestEdges.push_back( ledge );
2767 // where there are no _LayerEdge's on a _ConvexFace,
2768 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2769 // so that collision of viscous internal faces is not detected by check of
2770 // intersection of _LayerEdge's with the viscous internal faces.
2772 set< const SMDS_MeshNode* > usedNodes;
2774 // look for _LayerEdge's with null _sWOL
2775 id2eos = convFace._subIdToEOS.begin();
2776 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2778 _EdgesOnShape& eos = * id2eos->second;
2779 if ( !eos._sWOL.IsNull() )
2781 for ( size_t i = 0; i < eos._edges.size(); ++i )
2783 _LayerEdge* ledge = eos._edges[ i ];
2784 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2785 if ( !usedNodes.insert( srcNode ).second ) continue;
2787 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2789 usedNodes.insert( ledge->_simplices[i]._nPrev );
2790 usedNodes.insert( ledge->_simplices[i]._nNext );
2792 convFace._simplexTestEdges.push_back( ledge );
2796 } // loop on FACEs of data._solid
2799 //================================================================================
2801 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2803 //================================================================================
2805 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2807 // define allowed thickness
2808 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2810 data._maxThickness = 0;
2811 data._minThickness = 1e100;
2812 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2813 for ( ; hyp != data._hyps.end(); ++hyp )
2815 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2816 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2818 //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2820 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2821 // boundry inclined to the shape at a sharp angle
2823 //list< TGeomID > shapesToSmooth;
2824 TopTools_MapOfShape edgesOfSmooFaces;
2826 SMESH_MesherHelper helper( *_mesh );
2829 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2830 data._nbShapesToSmooth = 0;
2832 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2834 _EdgesOnShape& eos = edgesByGeom[iS];
2835 eos._toSmooth = false;
2836 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2839 double tgtThick = eos._hyp.GetTotalThickness();
2840 TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2841 for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2843 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2844 vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2845 if ( eE.empty() ) continue;
2848 for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2849 if ( eE[i]->_cosin > theMinSmoothCosin )
2851 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2852 while ( fIt->more() && !eos._toSmooth )
2854 const SMDS_MeshElement* face = fIt->next();
2855 if ( face->getshapeId() == eos._shapeID &&
2856 getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2858 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2863 if ( eos._toSmooth )
2865 for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2866 edgesOfSmooFaces.Add( eExp.Current() );
2868 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2870 data._nbShapesToSmooth += eos._toSmooth;
2874 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2876 _EdgesOnShape& eos = edgesByGeom[iS];
2877 eos._edgeSmoother = NULL;
2878 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2879 if ( !eos._hyp.ToSmooth() ) continue;
2881 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2882 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2885 double tgtThick = eos._hyp.GetTotalThickness();
2886 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2888 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2889 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2890 if ( eV.empty() ) continue;
2891 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2892 double angle = eDir.Angle( eV[0]->_normal );
2893 double cosin = Cos( angle );
2894 double cosinAbs = Abs( cosin );
2895 if ( cosinAbs > theMinSmoothCosin )
2897 // always smooth analytic EDGEs
2898 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2899 eos._toSmooth = ! curve.IsNull();
2901 // compare tgtThick with the length of an end segment
2902 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2903 while ( eIt->more() && !eos._toSmooth )
2905 const SMDS_MeshElement* endSeg = eIt->next();
2906 if ( endSeg->getshapeId() == (int) iS )
2909 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2910 eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2913 if ( eos._toSmooth )
2915 eos._edgeSmoother = new _Smoother1D( curve, eos );
2917 for ( size_t i = 0; i < eos._edges.size(); ++i )
2918 eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2922 data._nbShapesToSmooth += eos._toSmooth;
2926 // Reset _cosin if no smooth is allowed by the user
2927 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2929 _EdgesOnShape& eos = edgesByGeom[iS];
2930 if ( eos._edges.empty() ) continue;
2932 if ( !eos._hyp.ToSmooth() )
2933 for ( size_t i = 0; i < eos._edges.size(); ++i )
2934 eos._edges[i]->SetCosin( 0 );
2938 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2940 TopTools_MapOfShape c1VV;
2942 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2944 _EdgesOnShape& eos = edgesByGeom[iS];
2945 if ( eos._edges.empty() ||
2946 eos.ShapeType() != TopAbs_FACE ||
2950 // check EDGEs of a FACE
2951 TopTools_MapOfShape checkedEE, allVV;
2952 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
2953 while ( !smQueue.empty() )
2955 SMESH_subMesh* sm = smQueue.front();
2956 smQueue.pop_front();
2957 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2958 while ( smIt->more() )
2961 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
2962 allVV.Add( sm->GetSubShape() );
2963 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
2964 !checkedEE.Add( sm->GetSubShape() ))
2967 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
2968 vector<_LayerEdge*>& eE = eoe->_edges;
2969 if ( eE.empty() || !eoe->_sWOL.IsNull() )
2972 bool isC1 = true; // check continuity along an EDGE
2973 for ( size_t i = 0; i < eE.size() && isC1; ++i )
2974 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
2978 // check that mesh faces are C1 as well
2980 gp_XYZ norm1, norm2;
2981 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
2982 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
2983 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
2985 while ( fIt->more() && isC1 )
2986 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
2987 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
2992 // add the EDGE and an adjacent FACE to _eosC1
2993 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
2994 while ( const TopoDS_Shape* face = fIt->next() )
2996 _EdgesOnShape* eof = data.GetShapeEdges( *face );
2997 if ( !eof ) continue; // other solid
2998 if ( !eos.HasC1( eoe ))
3000 eos._eosC1.push_back( eoe );
3001 eoe->_toSmooth = false;
3002 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3004 if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof ))
3006 eos._eosC1.push_back( eof );
3007 eof->_toSmooth = false;
3008 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3009 smQueue.push_back( eof->_subMesh );
3014 if ( eos._eosC1.empty() )
3017 // check VERTEXes of C1 FACEs
3018 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3019 for ( ; vIt.More(); vIt.Next() )
3021 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3022 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3025 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3026 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3027 while ( const TopoDS_Shape* face = fIt->next() )
3029 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3030 if ( !eof ) continue; // other solid
3031 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3037 eos._eosC1.push_back( eov );
3038 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3039 c1VV.Add( eov->_shape );
3043 } // fill _eosC1 of FACEs
3048 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3050 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3052 _EdgesOnShape& eov = edgesByGeom[iS];
3053 if ( eov._edges.empty() ||
3054 eov.ShapeType() != TopAbs_VERTEX ||
3055 c1VV.Contains( eov._shape ))
3057 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3059 // get directions of surrounding EDGEs
3061 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3062 while ( const TopoDS_Shape* e = fIt->next() )
3064 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3065 if ( !eoe ) continue; // other solid
3066 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3067 if ( !Precision::IsInfinite( eDir.X() ))
3068 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3071 // find EDGEs with C1 directions
3072 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3073 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3074 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3076 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3077 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3080 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3081 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3082 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3083 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3084 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3085 dirOfEdges[i].first = 0;
3086 dirOfEdges[j].first = 0;
3089 } // fill _eosC1 of VERTEXes
3096 //================================================================================
3098 * \brief initialize data of _EdgesOnShape
3100 //================================================================================
3102 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3106 if ( !eos._shape.IsNull() ||
3107 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3110 SMESH_MesherHelper helper( *_mesh );
3113 eos._shapeID = sm->GetId();
3114 eos._shape = sm->GetSubShape();
3115 if ( eos.ShapeType() == TopAbs_FACE )
3116 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3117 eos._toSmooth = false;
3121 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3122 data._shrinkShape2Shape.find( eos._shapeID );
3123 if ( s2s != data._shrinkShape2Shape.end() )
3124 eos._sWOL = s2s->second;
3126 eos._isRegularSWOL = true;
3127 if ( eos.SWOLType() == TopAbs_FACE )
3129 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3130 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3131 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3135 if ( data._hyps.size() == 1 )
3137 eos._hyp = data._hyps.back();
3141 // compute average StdMeshers_ViscousLayers parameters
3142 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3143 if ( eos.ShapeType() == TopAbs_FACE )
3145 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3146 eos._hyp = f2hyp->second;
3150 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3151 while ( const TopoDS_Shape* face = fIt->next() )
3153 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3154 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3155 eos._hyp.Add( f2hyp->second );
3161 if ( ! eos._hyp.UseSurfaceNormal() )
3163 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3165 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3166 eos._faceNormals.resize( smDS->NbElements() );
3168 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3169 for ( int iF = 0; eIt->more(); ++iF )
3171 const SMDS_MeshElement* face = eIt->next();
3172 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3173 eos._faceNormals[iF].SetCoord( 0,0,0 );
3176 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3177 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3178 eos._faceNormals[iF].Reverse();
3180 else // find EOS of adjacent FACEs
3182 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3183 while ( const TopoDS_Shape* face = fIt->next() )
3185 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3186 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3187 if ( eos._faceEOS.back()->_shape.IsNull() )
3188 // avoid using uninitialised _shapeID in GetNormal()
3189 eos._faceEOS.back()->_shapeID = faceID;
3195 //================================================================================
3197 * \brief Returns normal of a face
3199 //================================================================================
3201 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3204 const _EdgesOnShape* eos = 0;
3206 if ( face->getshapeId() == _shapeID )
3212 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3213 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3214 eos = _faceEOS[ iF ];
3218 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3220 norm = eos->_faceNormals[ face->getIdInShape() ];
3224 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3225 << " on _shape #" << _shapeID );
3231 //================================================================================
3233 * \brief Set data of _LayerEdge needed for smoothing
3235 //================================================================================
3237 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3239 SMESH_MesherHelper& helper,
3242 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3245 edge._maxLen = Precision::Infinite();
3248 edge._curvature = 0;
3251 // --------------------------
3252 // Compute _normal and _cosin
3253 // --------------------------
3256 edge._lenFactor = 1.;
3257 edge._normal.SetCoord(0,0,0);
3258 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3260 int totalNbFaces = 0;
3262 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3266 const bool onShrinkShape = !eos._sWOL.IsNull();
3267 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3268 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3270 // get geom FACEs the node lies on
3271 //if ( useGeometry )
3273 set<TGeomID> faceIds;
3274 if ( eos.ShapeType() == TopAbs_FACE )
3276 faceIds.insert( eos._shapeID );
3280 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3281 while ( fIt->more() )
3282 faceIds.insert( fIt->next()->getshapeId() );
3284 set<TGeomID>::iterator id = faceIds.begin();
3285 for ( ; id != faceIds.end(); ++id )
3287 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3288 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3290 F = TopoDS::Face( s );
3291 face2Norm[ totalNbFaces ].first = F;
3299 if ( onShrinkShape ) // one of faces the node is on has no layers
3301 if ( eos.SWOLType() == TopAbs_EDGE )
3303 // inflate from VERTEX along EDGE
3304 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3306 else if ( eos.ShapeType() == TopAbs_VERTEX )
3308 // inflate from VERTEX along FACE
3309 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3310 node, helper, normOK, &edge._cosin);
3314 // inflate from EDGE along FACE
3315 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3316 node, helper, normOK);
3319 else // layers are on all FACEs of SOLID the node is on
3322 for ( int iF = 0; iF < totalNbFaces; ++iF )
3324 F = TopoDS::Face( face2Norm[ iF ].first );
3325 geomNorm = getFaceNormal( node, F, helper, normOK );
3326 if ( !normOK ) continue;
3329 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3331 face2Norm[ iF ].second = geomNorm.XYZ();
3332 edge._normal += geomNorm.XYZ();
3334 if ( nbOkNorms == 0 )
3335 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3337 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3339 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3340 edge._normal.SetCoord( 0,0,0 );
3341 for ( int iF = 0; iF < totalNbFaces; ++iF )
3343 const TopoDS_Face& F = face2Norm[iF].first;
3344 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3345 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3348 face2Norm[ iF ].second = geomNorm.XYZ();
3349 edge._normal += face2Norm[ iF ].second;
3353 if ( totalNbFaces >= 3 )
3355 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces );
3359 else // !useGeometry - get _normal using surrounding mesh faces
3361 edge._normal = getWeigthedNormal( &edge );
3363 // set<TGeomID> faceIds;
3365 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3366 // while ( fIt->more() )
3368 // const SMDS_MeshElement* face = fIt->next();
3369 // if ( eos.GetNormal( face, geomNorm ))
3371 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3372 // continue; // use only one mesh face on FACE
3373 // edge._normal += geomNorm.XYZ();
3380 //if ( eos._hyp.UseSurfaceNormal() )
3382 switch ( eos.ShapeType() )
3389 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3390 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3391 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3392 edge._cosin = Cos( angle );
3395 case TopAbs_VERTEX: {
3396 if ( eos.SWOLType() != TopAbs_FACE ) { // else _cosin is set by getFaceDir()
3397 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3398 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3399 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3400 edge._cosin = Cos( angle );
3401 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3402 for ( int iF = totalNbFaces-2; iF >=0; --iF )
3404 F = face2Norm[ iF ].first;
3405 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3407 double angle = inFaceDir.Angle( edge._normal );
3408 double cosin = Cos( angle );
3409 if ( Abs( cosin ) > edge._cosin )
3410 edge._cosin = cosin;
3417 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3421 double normSize = edge._normal.SquareModulus();
3422 if ( normSize < numeric_limits<double>::min() )
3423 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3425 edge._normal /= sqrt( normSize );
3427 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3429 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3430 edge._nodes.resize( 1 );
3431 edge._normal.SetCoord( 0,0,0 );
3435 // Set the rest data
3436 // --------------------
3438 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3440 if ( onShrinkShape )
3442 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3443 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3444 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3446 // set initial position which is parameters on _sWOL in this case
3447 if ( eos.SWOLType() == TopAbs_EDGE )
3449 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3450 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3451 if ( edge._nodes.size() > 1 )
3452 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3454 else // eos.SWOLType() == TopAbs_FACE
3456 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3457 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3458 if ( edge._nodes.size() > 1 )
3459 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3462 if ( edge._nodes.size() > 1 )
3464 // check if an angle between a FACE with layers and SWOL is sharp,
3465 // else the edge should not inflate
3467 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3468 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3469 F = face2Norm[iF].first;
3472 geomNorm = getFaceNormal( node, F, helper, normOK );
3473 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3474 geomNorm.Reverse(); // inside the SOLID
3475 if ( geomNorm * edge._normal < -0.001 )
3477 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3478 edge._nodes.resize( 1 );
3480 else if ( edge._lenFactor > 3 )
3482 edge._lenFactor = 2;
3483 edge.Set( _LayerEdge::RISKY_SWOL );
3490 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3492 if ( eos.ShapeType() == TopAbs_FACE )
3495 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3497 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3498 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3503 // Set neighbor nodes for a _LayerEdge based on EDGE
3505 if ( eos.ShapeType() == TopAbs_EDGE /*||
3506 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3508 edge._2neibors = new _2NearEdges;
3509 // target nodes instead of source ones will be set later
3515 //================================================================================
3517 * \brief Return normal to a FACE at a node
3518 * \param [in] n - node
3519 * \param [in] face - FACE
3520 * \param [in] helper - helper
3521 * \param [out] isOK - true or false
3522 * \param [in] shiftInside - to find normal at a position shifted inside the face
3523 * \return gp_XYZ - normal
3525 //================================================================================
3527 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3528 const TopoDS_Face& face,
3529 SMESH_MesherHelper& helper,
3536 // get a shifted position
3537 gp_Pnt p = SMESH_TNodeXYZ( node );
3538 gp_XYZ shift( 0,0,0 );
3539 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3540 switch ( S.ShapeType() ) {
3543 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3548 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3556 p.Translate( shift * 1e-5 );
3558 TopLoc_Location loc;
3559 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3561 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3563 projector.Perform( p );
3564 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3569 Quantity_Parameter U,V;
3570 projector.LowerDistanceParameters(U,V);
3575 uv = helper.GetNodeUV( face, node, 0, &isOK );
3581 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3583 if ( !shiftInside &&
3584 helper.IsDegenShape( node->getshapeId() ) &&
3585 getFaceNormalAtSingularity( uv, face, helper, normal ))
3588 return normal.XYZ();
3591 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3592 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3594 if ( pointKind == IMPOSSIBLE &&
3595 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3597 // probably NormEstim() failed due to a too high tolerance
3598 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3599 isOK = ( pointKind < IMPOSSIBLE );
3601 if ( pointKind < IMPOSSIBLE )
3603 if ( pointKind != REGULAR &&
3605 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3607 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3608 if ( normShift * normal.XYZ() < 0. )
3614 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3616 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3618 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3619 while ( fIt->more() )
3621 const SMDS_MeshElement* f = fIt->next();
3622 if ( f->getshapeId() == faceID )
3624 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3627 TopoDS_Face ff = face;
3628 ff.Orientation( TopAbs_FORWARD );
3629 if ( helper.IsReversedSubMesh( ff ))
3636 return normal.XYZ();
3639 //================================================================================
3641 * \brief Try to get normal at a singularity of a surface basing on it's nature
3643 //================================================================================
3645 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3646 const TopoDS_Face& face,
3647 SMESH_MesherHelper& helper,
3650 BRepAdaptor_Surface surface( face );
3652 if ( !getRovolutionAxis( surface, axis ))
3655 double f,l, d, du, dv;
3656 f = surface.FirstUParameter();
3657 l = surface.LastUParameter();
3658 d = ( uv.X() - f ) / ( l - f );
3659 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3660 f = surface.FirstVParameter();
3661 l = surface.LastVParameter();
3662 d = ( uv.Y() - f ) / ( l - f );
3663 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3666 gp_Pnt2d testUV = uv;
3667 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3669 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3670 for ( int iLoop = 0; true ; ++iLoop )
3672 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3673 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3680 if ( axis * refDir < 0. )
3688 //================================================================================
3690 * \brief Return a normal at a node weighted with angles taken by faces
3692 //================================================================================
3694 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3696 const SMDS_MeshNode* n = edge->_nodes[0];
3698 gp_XYZ resNorm(0,0,0);
3699 SMESH_TNodeXYZ p0( n ), pP, pN;
3700 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3702 pP.Set( edge->_simplices[i]._nPrev );
3703 pN.Set( edge->_simplices[i]._nNext );
3704 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3705 double l0P = v0P.SquareMagnitude();
3706 double l0N = v0N.SquareMagnitude();
3707 double lPN = vPN.SquareMagnitude();
3708 if ( l0P < std::numeric_limits<double>::min() ||
3709 l0N < std::numeric_limits<double>::min() ||
3710 lPN < std::numeric_limits<double>::min() )
3712 double lNorm = norm.SquareMagnitude();
3713 double sin2 = lNorm / l0P / l0N;
3714 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3716 double weight = sin2 * angle / lPN;
3717 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3723 //================================================================================
3725 * \brief Return a normal at a node by getting a common point of offset planes
3726 * defined by the FACE normals
3728 //================================================================================
3730 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3731 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3734 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3736 gp_XYZ resNorm(0,0,0);
3737 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3738 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3740 for ( int i = 0; i < nbFaces; ++i )
3741 resNorm += f2Normal[i].second;
3745 // prepare _OffsetPlane's
3746 vector< _OffsetPlane > pln( nbFaces );
3747 for ( int i = 0; i < nbFaces; ++i )
3749 pln[i]._faceIndex = i;
3750 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3753 // intersect neighboring OffsetPlane's
3754 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3755 while ( const TopoDS_Shape* edge = edgeIt->next() )
3757 int f1 = -1, f2 = -1;
3758 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3759 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3760 (( f1 < 0 ) ? f1 : f2 ) = i;
3763 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ]);
3766 // get a common point
3767 gp_XYZ commonPnt( 0, 0, 0 );
3770 for ( int i = 0; i < nbFaces; ++i )
3772 commonPnt += pln[ i ].GetCommonPoint( isPointFound );
3773 nbPoints += isPointFound;
3775 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3776 if ( nbPoints == 0 )
3779 commonPnt /= nbPoints;
3780 resNorm = commonPnt - p0;
3782 // choose the best among resNorm and wgtNorm
3783 resNorm.Normalize();
3784 wgtNorm.Normalize();
3785 double resMinDot = std::numeric_limits<double>::max();
3786 double wgtMinDot = std::numeric_limits<double>::max();
3787 for ( int i = 0; i < nbFaces; ++i )
3789 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3790 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3793 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3795 edge->Set( _LayerEdge::MULTI_NORMAL );
3798 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3801 //================================================================================
3803 * \brief Compute line of intersection of 2 planes
3805 //================================================================================
3807 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln )
3809 int iNext = bool( _faceIndexNext[0] >= 0 );
3810 _faceIndexNext[ iNext ] = pln._faceIndex;
3812 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3813 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3815 gp_XYZ lineDir = n1 ^ n2;
3817 double x = Abs( lineDir.X() );
3818 double y = Abs( lineDir.Y() );
3819 double z = Abs( lineDir.Z() );
3821 int cooMax; // max coordinate
3823 if (x > z) cooMax = 1;
3827 if (y > z) cooMax = 2;
3831 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3835 // the constants in the 2 plane equations
3836 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
3837 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3842 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3843 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3846 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3848 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3851 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3852 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3856 gp_Lin& line = _lines[ iNext ];
3857 line.SetDirection( lineDir );
3858 line.SetLocation ( linePos );
3860 _isLineOK[ iNext ] = true;
3863 iNext = bool( pln._faceIndexNext[0] >= 0 );
3864 pln._lines [ iNext ] = line;
3865 pln._faceIndexNext[ iNext ] = this->_faceIndex;
3866 pln._isLineOK [ iNext ] = true;
3869 //================================================================================
3871 * \brief Computes intersection point of two _lines
3873 //================================================================================
3875 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound) const
3880 if ( NbLines() == 2 )
3882 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3883 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3884 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
3885 if ( Abs( dot01 ) > std::numeric_limits<double>::min() )
3887 double u1 = - ( lPerp0 * l0l1 ) / dot01;
3888 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3896 //================================================================================
3898 * \brief Find 2 neigbor nodes of a node on EDGE
3900 //================================================================================
3902 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
3903 const SMDS_MeshNode*& n1,
3904 const SMDS_MeshNode*& n2,
3908 const SMDS_MeshNode* node = edge->_nodes[0];
3909 const int shapeInd = eos._shapeID;
3910 SMESHDS_SubMesh* edgeSM = 0;
3911 if ( eos.ShapeType() == TopAbs_EDGE )
3913 edgeSM = eos._subMesh->GetSubMeshDS();
3914 if ( !edgeSM || edgeSM->NbElements() == 0 )
3915 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3919 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3920 while ( eIt->more() && !n2 )
3922 const SMDS_MeshElement* e = eIt->next();
3923 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
3924 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3927 if (!edgeSM->Contains(e)) continue;
3931 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
3932 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
3934 ( iN++ ? n2 : n1 ) = nNeibor;
3937 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3941 //================================================================================
3943 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3945 //================================================================================
3947 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3948 const SMDS_MeshNode* n2,
3949 const _EdgesOnShape& eos,
3950 SMESH_MesherHelper& helper)
3952 if ( eos.ShapeType() != TopAbs_EDGE )
3955 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
3956 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3957 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3961 double sumLen = vec1.Modulus() + vec2.Modulus();
3962 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3963 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3964 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3965 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3966 if ( _curvature ) delete _curvature;
3967 _curvature = _Curvature::New( avgNormProj, avgLen );
3968 // if ( _curvature )
3969 // debugMsg( _nodes[0]->GetID()
3970 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3971 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3972 // << _curvature->lenDelta(0) );
3976 if ( eos._sWOL.IsNull() )
3978 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3979 // if ( SMESH_Algo::isDegenerated( E ))
3981 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
3982 gp_XYZ plnNorm = dirE ^ _normal;
3983 double proj0 = plnNorm * vec1;
3984 double proj1 = plnNorm * vec2;
3985 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3987 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3988 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3993 //================================================================================
3995 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3996 * this and other _LayerEdge's are inflated along a FACE or an EDGE
3998 //================================================================================
4000 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4002 SMESH_MesherHelper& helper )
4004 _nodes = other._nodes;
4005 _normal = other._normal;
4007 _lenFactor = other._lenFactor;
4008 _cosin = other._cosin;
4009 _2neibors = other._2neibors;
4010 _curvature = 0; std::swap( _curvature, other._curvature );
4011 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4013 gp_XYZ lastPos( 0,0,0 );
4014 if ( eos.SWOLType() == TopAbs_EDGE )
4016 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4017 _pos.push_back( gp_XYZ( u, 0, 0));
4019 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4024 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4025 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4027 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4028 lastPos.SetX( uv.X() );
4029 lastPos.SetY( uv.Y() );
4034 //================================================================================
4036 * \brief Set _cosin and _lenFactor
4038 //================================================================================
4040 void _LayerEdge::SetCosin( double cosin )
4043 cosin = Abs( _cosin );
4044 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4045 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4048 //================================================================================
4050 * \brief Check if another _LayerEdge is a neighbor on EDGE
4052 //================================================================================
4054 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4056 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4057 ( edge->_2neibors && edge->_2neibors->include( this )));
4060 //================================================================================
4062 * \brief Fills a vector<_Simplex >
4064 //================================================================================
4066 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4067 vector<_Simplex>& simplices,
4068 const set<TGeomID>& ingnoreShapes,
4069 const _SolidData* dataToCheckOri,
4073 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4074 while ( fIt->more() )
4076 const SMDS_MeshElement* f = fIt->next();
4077 const TGeomID shapeInd = f->getshapeId();
4078 if ( ingnoreShapes.count( shapeInd )) continue;
4079 const int nbNodes = f->NbCornerNodes();
4080 const int srcInd = f->GetNodeIndex( node );
4081 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4082 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4083 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4084 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4085 std::swap( nPrev, nNext );
4086 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4090 SortSimplices( simplices );
4093 //================================================================================
4095 * \brief Set neighbor simplices side by side
4097 //================================================================================
4099 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4101 vector<_Simplex> sortedSimplices( simplices.size() );
4102 sortedSimplices[0] = simplices[0];
4104 for ( size_t i = 1; i < simplices.size(); ++i )
4106 for ( size_t j = 1; j < simplices.size(); ++j )
4107 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4109 sortedSimplices[i] = simplices[j];
4114 if ( nbFound == simplices.size() - 1 )
4115 simplices.swap( sortedSimplices );
4118 //================================================================================
4120 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4122 //================================================================================
4124 void _ViscousBuilder::makeGroupOfLE()
4127 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4129 if ( _sdVec[i]._n2eMap.empty() ) continue;
4131 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4132 TNode2Edge::iterator n2e;
4133 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4135 _LayerEdge* le = n2e->second;
4136 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4137 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4138 // << ", " << le->_nodes[iN]->GetID() <<"])");
4140 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4141 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4146 dumpFunction( SMESH_Comment("makeNormals") << i );
4147 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4149 _LayerEdge* edge = n2e->second;
4150 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4151 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4152 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4153 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4157 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4158 dumpCmd( "faceId1 = mesh.NbElements()" );
4159 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4160 for ( ; fExp.More(); fExp.Next() )
4162 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4164 if ( sm->NbElements() == 0 ) continue;
4165 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4166 while ( fIt->more())
4168 const SMDS_MeshElement* e = fIt->next();
4169 SMESH_Comment cmd("mesh.AddFace([");
4170 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4171 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4176 dumpCmd( "faceId2 = mesh.NbElements()" );
4177 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4178 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4179 << "'%s-%s' % (faceId1+1, faceId2))");
4185 //================================================================================
4187 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4189 //================================================================================
4191 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4193 data._geomSize = Precision::Infinite();
4194 double intersecDist;
4195 const SMDS_MeshElement* face;
4196 SMESH_MesherHelper helper( *_mesh );
4198 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4199 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4200 data._proxyMesh->GetFaces( data._solid )));
4202 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4204 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4205 if ( eos._edges.empty() )
4207 // get neighbor faces intersection with which should not be considered since
4208 // collisions are avoided by means of smoothing
4209 set< TGeomID > neighborFaces;
4210 if ( eos._hyp.ToSmooth() )
4212 SMESH_subMeshIteratorPtr subIt =
4213 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4214 while ( subIt->more() )
4216 SMESH_subMesh* sm = subIt->next();
4217 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4218 while ( const TopoDS_Shape* face = fIt->next() )
4219 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4222 // find intersections
4223 double thinkness = eos._hyp.GetTotalThickness();
4224 for ( size_t i = 0; i < eos._edges.size(); ++i )
4226 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4227 eos._edges[i]->_maxLen = thinkness;
4228 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4229 if ( intersecDist > 0 && face )
4231 data._geomSize = Min( data._geomSize, intersecDist );
4232 if ( !neighborFaces.count( face->getshapeId() ))
4233 eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4239 //================================================================================
4241 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4243 //================================================================================
4245 bool _ViscousBuilder::inflate(_SolidData& data)
4247 SMESH_MesherHelper helper( *_mesh );
4249 // Limit inflation step size by geometry size found by itersecting
4250 // normals of _LayerEdge's with mesh faces
4251 if ( data._stepSize > 0.3 * data._geomSize )
4252 limitStepSize( data, 0.3 * data._geomSize );
4254 const double tgtThick = data._maxThickness;
4255 if ( data._stepSize > data._minThickness )
4256 limitStepSize( data, data._minThickness );
4258 if ( data._stepSize < 1. )
4259 data._epsilon = data._stepSize * 1e-7;
4261 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4263 findCollisionEdges( data, helper );
4265 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4266 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4267 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4268 data._edgesOnShape[i]._edges.size() > 0 &&
4269 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4271 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4272 data._edgesOnShape[i]._edges[0]->Block( data );
4275 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4277 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4278 int nbSteps = 0, nbRepeats = 0;
4279 while ( avgThick < 0.99 )
4281 // new target length
4282 double prevThick = curThick;
4283 curThick += data._stepSize;
4284 if ( curThick > tgtThick )
4286 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4290 double stepSize = curThick - prevThick;
4291 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4293 // Elongate _LayerEdge's
4294 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4295 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4297 _EdgesOnShape& eos = data._edgesOnShape[iS];
4298 if ( eos._edges.empty() ) continue;
4300 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4301 for ( size_t i = 0; i < eos._edges.size(); ++i )
4303 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4308 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4311 // Improve and check quality
4312 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4316 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4317 debugMsg("NOT INVALIDATED STEP!");
4318 return error("Smoothing failed", data._index);
4320 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4321 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4323 _EdgesOnShape& eos = data._edgesOnShape[iS];
4324 for ( size_t i = 0; i < eos._edges.size(); ++i )
4325 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4329 break; // no more inflating possible
4333 // Evaluate achieved thickness
4335 int nbActiveEdges = 0;
4336 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4338 _EdgesOnShape& eos = data._edgesOnShape[iS];
4339 if ( eos._edges.empty() ) continue;
4341 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4342 for ( size_t i = 0; i < eos._edges.size(); ++i )
4344 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4345 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4348 avgThick /= data._n2eMap.size();
4349 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4351 #ifdef BLOCK_INFLATION
4352 if ( nbActiveEdges == 0 )
4354 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4358 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4360 debugMsg( "-- Stop inflation since "
4361 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4362 << tgtThick * avgThick << " ) * " << safeFactor );
4367 limitStepSize( data, 0.25 * distToIntersection );
4368 if ( data._stepSizeNodes[0] )
4369 data._stepSize = data._stepSizeCoeff *
4370 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4372 } // while ( avgThick < 0.99 )
4375 return error("failed at the very first inflation step", data._index);
4377 if ( avgThick < 0.99 )
4379 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4381 data._proxyMesh->_warning.reset
4382 ( new SMESH_ComputeError (COMPERR_WARNING,
4383 SMESH_Comment("Thickness ") << tgtThick <<
4384 " of viscous layers not reached,"
4385 " average reached thickness is " << avgThick*tgtThick));
4389 // Restore position of src nodes moved by inflation on _noShrinkShapes
4390 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4391 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4393 _EdgesOnShape& eos = data._edgesOnShape[iS];
4394 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4395 for ( size_t i = 0; i < eos._edges.size(); ++i )
4397 restoreNoShrink( *eos._edges[ i ] );
4402 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4405 //================================================================================
4407 * \brief Improve quality of layer inner surface and check intersection
4409 //================================================================================
4411 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4413 double & distToIntersection)
4415 if ( data._nbShapesToSmooth == 0 )
4416 return true; // no shapes needing smoothing
4418 bool moved, improved;
4420 vector< _LayerEdge* > movedEdges, badSmooEdges;
4421 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4422 vector< bool > isConcaveFace;
4424 SMESH_MesherHelper helper(*_mesh);
4425 Handle(ShapeAnalysis_Surface) surface;
4428 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4430 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4432 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4434 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4435 if ( !eos._toSmooth ||
4436 eos.ShapeType() != shapeType ||
4437 eos._edges.empty() )
4440 // already smoothed?
4441 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4442 // if ( !toSmooth ) continue;
4444 if ( !eos._hyp.ToSmooth() )
4446 // smooth disabled by the user; check validy only
4447 if ( !isFace ) continue;
4448 for ( size_t i = 0; i < eos._edges.size(); ++i )
4450 _LayerEdge* edge = eos._edges[i];
4451 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4452 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4454 debugMsg( "-- Stop inflation. Bad simplex ("
4455 << " "<< edge->_nodes[0]->GetID()
4456 << " "<< edge->_nodes.back()->GetID()
4457 << " "<< edge->_simplices[iF]._nPrev->GetID()
4458 << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4462 continue; // goto the next EDGE or FACE
4466 if ( eos.SWOLType() == TopAbs_FACE )
4468 if ( !F.IsSame( eos._sWOL )) {
4469 F = TopoDS::Face( eos._sWOL );
4470 helper.SetSubShape( F );
4471 surface = helper.GetSurface( F );
4476 F.Nullify(); surface.Nullify();
4478 const TGeomID sInd = eos._shapeID;
4480 // perform smoothing
4482 if ( eos.ShapeType() == TopAbs_EDGE )
4484 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4486 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4488 // smooth on EDGE's (normally we should not get here)
4492 for ( size_t i = 0; i < eos._edges.size(); ++i )
4494 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4496 dumpCmd( SMESH_Comment("# end step ")<<step);
4498 while ( moved && step++ < 5 );
4503 else // smooth on FACE
4506 eosC1.push_back( & eos );
4507 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4510 isConcaveFace.resize( eosC1.size() );
4511 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4513 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4514 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4515 for ( size_t i = 0; i < edges.size(); ++i )
4516 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4517 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4518 movedEdges.push_back( edges[i] );
4520 makeOffsetSurface( *eosC1[ iEOS ], helper );
4523 int step = 0, stepLimit = 5, badNb = 0;
4524 while (( ++step <= stepLimit ) || improved )
4526 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4527 <<"_InfStep"<<infStep<<"_"<<step); // debug
4528 int oldBadNb = badNb;
4529 badSmooEdges.clear();
4531 #ifdef INCREMENTAL_SMOOTH
4532 bool findBest = false; // ( step == stepLimit );
4533 for ( size_t i = 0; i < movedEdges.size(); ++i )
4535 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4536 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4537 badSmooEdges.push_back( movedEdges[i] );
4540 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4541 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4543 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4544 for ( size_t i = 0; i < edges.size(); ++i )
4546 edges[i]->Unset( _LayerEdge::SMOOTHED );
4547 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4548 badSmooEdges.push_back( eos._edges[i] );
4552 badNb = badSmooEdges.size();
4555 debugMsg(SMESH_Comment("badNb = ") << badNb );
4557 if ( !badSmooEdges.empty() && step >= stepLimit / 2 )
4559 if ( badSmooEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4562 // resolve hard smoothing situation around concave VERTEXes
4563 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4565 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4566 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4567 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4568 step, badSmooEdges );
4570 // look for the best smooth of _LayerEdge's neighboring badSmooEdges
4572 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
4574 _LayerEdge* ledge = badSmooEdges[i];
4575 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4577 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4578 badNb += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4580 ledge->Unset( _LayerEdge::SMOOTHED );
4581 badNb += ledge->Smooth( step, true, /*findBest=*/true );
4583 debugMsg(SMESH_Comment("badNb = ") << badNb );
4586 if ( badNb == oldBadNb &&
4588 step < stepLimit ) // smooth w/o chech of validity
4591 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4592 <<"_InfStep"<<infStep<<"_"<<step); // debug
4593 for ( size_t i = 0; i < movedEdges.size(); ++i )
4595 movedEdges[i]->SmoothWoCheck();
4597 if ( stepLimit < 9 )
4601 improved = ( badNb < oldBadNb );
4605 if (( step % 3 == 1 ) || ( badNb > 0 && step >= stepLimit / 2 ))
4606 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4608 putOnOffsetSurface( *eosC1[ iEOS ], infStep, step, /*moveAll=*/step == 1 );
4611 } // smoothing steps
4613 // project -- to prevent intersections or fix bad simplices
4614 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4616 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || badNb > 0 )
4617 putOnOffsetSurface( *eosC1[ iEOS ], infStep );
4620 if ( !badSmooEdges.empty() )
4622 badSmooEdges.clear();
4623 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4625 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4627 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4629 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4630 edge->CheckNeiborsOnBoundary( & badSmooEdges );
4633 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4634 const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4635 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4636 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4638 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4639 << " "<< tgtXYZ._node->GetID()
4640 << " "<< edge->_simplices[j]._nPrev->GetID()
4641 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4642 badSmooEdges.push_back( edge );
4649 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4650 badNb = invalidateBadSmooth( data, helper, badSmooEdges, eosC1, infStep );
4656 } // // smooth on FACE's
4658 } // smooth on [ EDGEs, FACEs ]
4660 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4662 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4664 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4665 if ( eos.ShapeType() == TopAbs_FACE ||
4666 eos._edges.empty() ||
4667 !eos._sWOL.IsNull() )
4670 badSmooEdges.clear();
4671 for ( size_t i = 0; i < eos._edges.size(); ++i )
4673 _LayerEdge* edge = eos._edges[i];
4674 if ( edge->_nodes.size() < 2 ) continue;
4675 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4676 const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4677 //const gp_XYZ& prevXYZ = edge->PrevPos();
4678 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4679 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4681 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4682 << " "<< tgtXYZ._node->GetID()
4683 << " "<< edge->_simplices[j]._nPrev->GetID()
4684 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4685 badSmooEdges.push_back( edge );
4690 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4692 int badNb = invalidateBadSmooth( data, helper, badSmooEdges, eosC1, infStep );
4698 // Check if the last segments of _LayerEdge intersects 2D elements;
4699 // checked elements are either temporary faces or faces on surfaces w/o the layers
4701 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4702 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4703 data._proxyMesh->GetFaces( data._solid )) );
4705 #ifdef BLOCK_INFLATION
4706 const bool toBlockInfaltion = true;
4708 const bool toBlockInfaltion = false;
4710 distToIntersection = Precision::Infinite();
4712 const SMDS_MeshElement* intFace = 0;
4713 const SMDS_MeshElement* closestFace = 0;
4715 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4717 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4718 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4720 for ( size_t i = 0; i < eos._edges.size(); ++i )
4722 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4723 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4725 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4729 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4734 const bool isShorterDist = ( distToIntersection > dist );
4735 if ( toBlockInfaltion || isShorterDist )
4737 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4738 // lying on this _ConvexFace
4739 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4740 if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4743 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4744 // ( avoid limiting the thickness on the case of issue 22576)
4745 if ( intFace->getshapeId() == eos._shapeID )
4748 // ignore intersection with intFace of an adjacent FACE
4751 bool toIgnore = false;
4752 if ( eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4754 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4755 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4757 TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4758 for ( ; !toIgnore && edge.More(); edge.Next() )
4759 // is adjacent - has a common EDGE
4760 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4762 if ( toIgnore ) // check angle between normals
4765 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4766 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
4770 if ( !toIgnore ) // check if the edge is a neighbor of intFace
4772 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
4774 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4775 toIgnore = ( nInd >= 0 );
4782 // intersection not ignored
4784 if ( toBlockInfaltion &&
4785 dist < ( eos._edges[i]->_len * theThickToIntersection ))
4787 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4788 eos._edges[i]->Block( data ); // not to inflate
4790 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4792 // block _LayerEdge's, on top of which intFace is
4793 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4795 const SMDS_MeshElement* srcFace =
4796 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4797 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4798 while ( nIt->more() )
4800 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4801 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4802 if ( n2e != data._n2eMap.end() )
4803 n2e->second->Block( data );
4809 if ( isShorterDist )
4811 distToIntersection = dist;
4813 closestFace = intFace;
4816 } // if ( toBlockInfaltion || isShorterDist )
4817 } // loop on eos._edges
4818 } // loop on data._edgesOnShape
4823 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4824 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4825 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4826 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4827 << ") distance = " << distToIntersection<< endl;
4834 //================================================================================
4836 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4837 * \param [in,out] badSmooEdges - _LayerEdge's to fix
4838 * \return int - resulting nb of bad _LayerEdge's
4840 //================================================================================
4842 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
4843 SMESH_MesherHelper& helper,
4844 vector< _LayerEdge* >& badSmooEdges,
4845 vector< _EdgesOnShape* >& eosC1,
4848 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4850 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4855 //size_t iniNbBad = badSmooEdges.size();
4856 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
4858 _LayerEdge* edge = badSmooEdges[i];
4859 if ( edge->NbSteps() < 2 /*|| edge->Is( _LayerEdge::MARKED )*/)
4862 _EdgesOnShape* eos = data.GetShapeEdges( edge );
4863 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
4864 edge->Block( data );
4865 edge->Set( _LayerEdge::MARKED );
4867 // look for _LayerEdge's of bad _simplices
4868 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4869 const gp_XYZ& prevXYZ1 = edge->PrevCheckPos();
4870 const gp_XYZ& prevXYZ2 = edge->PrevPos();
4871 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4873 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) &&
4874 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol )))
4876 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
4877 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
4878 badSmooEdges.push_back( edge->_neibors[iN] );
4881 if ( eos->ShapeType() == TopAbs_VERTEX )
4883 // re-smooth on analytical EDGEs
4884 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
4885 while ( const TopoDS_Shape* e = eIt->next() )
4886 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
4887 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
4889 TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
4890 if ( eoe->SWOLType() == TopAbs_FACE ) {
4891 F = TopoDS::Face( eoe->_sWOL );
4892 surface = helper.GetSurface( F );
4894 eoe->_edgeSmoother->Perform( data, surface, F, helper );
4898 } // loop on badSmooEdges
4901 // check result of invalidation
4904 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4906 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4908 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4909 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4910 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4911 const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4912 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4913 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4916 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
4917 << " "<< tgtXYZ._node->GetID()
4918 << " "<< edge->_simplices[j]._nPrev->GetID()
4919 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4928 //================================================================================
4930 * \brief Create an offset surface
4932 //================================================================================
4934 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
4936 if ( eos._offsetSurf.IsNull() ||
4937 eos._edgeForOffset == 0 ||
4938 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
4941 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
4944 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
4945 gp_Pnt2d uv = baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
4946 double offset = baseSurface->Gap();
4948 eos._offsetSurf.Nullify();
4952 BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
4953 if ( !offsetMaker.IsDone() ) return;
4955 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
4956 if ( !fExp.More() ) return;
4958 TopoDS_Face F = TopoDS::Face( fExp.Current() );
4959 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
4960 if ( surf.IsNull() ) return;
4962 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
4964 catch ( Standard_Failure )
4969 //================================================================================
4971 * \brief Put nodes of a curved FACE to its offset surface
4973 //================================================================================
4975 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
4980 if ( eos._offsetSurf.IsNull() ||
4981 eos.ShapeType() != TopAbs_FACE ||
4982 eos._edgeForOffset == 0 ||
4983 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
4986 double preci = BRep_Tool::Tolerance( TopoDS::Face( eos._shape )), vol;
4987 for ( size_t i = 0; i < eos._edges.size(); ++i )
4989 _LayerEdge* edge = eos._edges[i];
4990 edge->Unset( _LayerEdge::MARKED );
4991 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
4993 if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
4996 int nbBlockedAround = 0;
4997 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
4998 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
4999 if ( nbBlockedAround > 1 )
5002 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5003 gp_Pnt2d uv = eos._offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5004 if ( eos._offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5005 edge->_curvature->_uv = uv;
5006 if ( eos._offsetSurf->Gap() < 10 * preci ) continue; // same pos
5008 gp_XYZ newP = eos._offsetSurf->Value( uv ).XYZ();
5009 gp_XYZ prevP = edge->PrevCheckPos();
5012 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5014 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5018 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5019 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5020 edge->_pos.back() = newP;
5022 edge->Set( _LayerEdge::MARKED );
5027 // dumpMove() for debug
5029 for ( ; i < eos._edges.size(); ++i )
5030 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5032 if ( i < eos._edges.size() )
5034 dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5035 << "_InfStep" << infStep << "_" << smooStep );
5036 for ( ; i < eos._edges.size(); ++i )
5038 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5039 dumpMove( eos._edges[i]->_nodes.back() );
5046 //================================================================================
5048 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5049 * _LayerEdge's to be in a consequent order
5051 //================================================================================
5053 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5055 SMESH_MesherHelper& helper)
5057 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5059 TopLoc_Location loc; double f,l;
5061 Handle(Geom_Line) line;
5062 Handle(Geom_Circle) circle;
5063 bool isLine, isCirc;
5064 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5066 // check if the EDGE is a line
5067 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5068 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5069 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5071 line = Handle(Geom_Line)::DownCast( curve );
5072 circle = Handle(Geom_Circle)::DownCast( curve );
5073 isLine = (!line.IsNull());
5074 isCirc = (!circle.IsNull());
5076 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5078 isLine = SMESH_Algo::IsStraight( E );
5081 line = new Geom_Line( gp::OX() ); // only type does matter
5083 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5088 else //////////////////////////////////////////////////////////////////////// 2D case
5090 if ( !eos._isRegularSWOL ) // 23190
5093 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5095 // check if the EDGE is a line
5096 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5097 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5098 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5100 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5101 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5102 isLine = (!line2d.IsNull());
5103 isCirc = (!circle2d.IsNull());
5105 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5108 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5109 while ( nIt->more() )
5110 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5111 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5113 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5114 for ( int i = 0; i < 2 && !isLine; ++i )
5115 isLine = ( size.Coord( i+1 ) <= lineTol );
5117 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5123 line = new Geom_Line( gp::OX() ); // only type does matter
5127 gp_Pnt2d p = circle2d->Location();
5128 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5129 circle = new Geom_Circle( ax, 1.); // only center position does matter
5138 return Handle(Geom_Curve)();
5141 //================================================================================
5143 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5145 //================================================================================
5147 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5148 Handle(ShapeAnalysis_Surface)& surface,
5149 const TopoDS_Face& F,
5150 SMESH_MesherHelper& helper)
5152 if ( !isAnalytic() ) return false;
5154 const size_t iFrom = 0, iTo = _eos._edges.size();
5156 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5158 if ( F.IsNull() ) // 3D
5160 SMESH_TNodeXYZ p0 ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5161 SMESH_TNodeXYZ p1 ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5162 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5163 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5165 for ( size_t i = iFrom; i < iTo; ++i )
5167 _LayerEdge* edge = _eos._edges[i];
5168 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5169 newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5171 if ( _eos._edges[i]->Is( _LayerEdge::NORMAL_UPDATED ))
5173 gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5174 gp_XYZ lineDir = pSrc1 - pSrc0;
5175 double shift = ( lineDir * ( newPos - pSrc0 ) -
5176 lineDir * ( curPos - pSrc0 ));
5177 newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5179 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED ))
5181 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5182 double curThick = pSrc.SquareDistance( tgtNode );
5183 double newThink = ( pSrc - newPos ).SquareModulus();
5184 if ( newThink > curThick )
5187 edge->_pos.back() = newPos;
5188 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5189 dumpMove( tgtNode );
5194 _LayerEdge* e0 = getLEdgeOnV( 0 );
5195 _LayerEdge* e1 = getLEdgeOnV( 1 );
5196 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5197 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5198 if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5200 int iPeriodic = helper.GetPeriodicIndex();
5201 if ( iPeriodic == 1 || iPeriodic == 2 )
5203 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5204 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5205 std::swap( uv0, uv1 );
5208 const gp_XY rangeUV = uv1 - uv0;
5209 for ( size_t i = iFrom; i < iTo; ++i )
5211 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5212 gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5213 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5215 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5216 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5217 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5218 dumpMove( tgtNode );
5220 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5221 pos->SetUParameter( newUV.X() );
5222 pos->SetVParameter( newUV.Y() );
5228 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5230 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5231 gp_Pnt center3D = circle->Location();
5233 if ( F.IsNull() ) // 3D
5235 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5236 return true; // closed EDGE - nothing to do
5238 // circle is a real curve of EDGE
5239 gp_Circ circ = circle->Circ();
5241 // new center is shifted along its axis
5242 const gp_Dir& axis = circ.Axis().Direction();
5243 _LayerEdge* e0 = getLEdgeOnV(0);
5244 _LayerEdge* e1 = getLEdgeOnV(1);
5245 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5246 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5247 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5248 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5249 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5251 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5253 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5254 gp_Circ newCirc( newAxis, newRadius );
5255 gp_Vec vecC1 ( newCenter, p1 );
5257 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5261 for ( size_t i = iFrom; i < iTo; ++i )
5263 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5264 double u = uLast * _leParams[i];
5265 gp_Pnt p = ElCLib::Value( u, newCirc );
5266 _eos._edges[i]->_pos.back() = p.XYZ();
5268 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5269 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5270 dumpMove( tgtNode );
5276 const gp_XY center( center3D.X(), center3D.Y() );
5278 _LayerEdge* e0 = getLEdgeOnV(0);
5279 _LayerEdge* eM = _eos._edges[ 0 ];
5280 _LayerEdge* e1 = getLEdgeOnV(1);
5281 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5282 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5283 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5284 gp_Vec2d vec0( center, uv0 );
5285 gp_Vec2d vecM( center, uvM );
5286 gp_Vec2d vec1( center, uv1 );
5287 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5288 double uMidl = vec0.Angle( vecM );
5289 if ( uLast * uMidl <= 0. )
5290 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5291 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5293 gp_Ax2d axis( center, vec0 );
5294 gp_Circ2d circ( axis, radius );
5295 for ( size_t i = iFrom; i < iTo; ++i )
5297 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5298 double newU = uLast * _leParams[i];
5299 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5300 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5302 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5303 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5304 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5305 dumpMove( tgtNode );
5307 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5308 pos->SetUParameter( newUV.X() );
5309 pos->SetVParameter( newUV.Y() );
5318 //================================================================================
5320 * \brief smooth _LayerEdge's on a an EDGE
5322 //================================================================================
5324 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5325 Handle(ShapeAnalysis_Surface)& surface,
5326 const TopoDS_Face& F,
5327 SMESH_MesherHelper& helper)
5329 if ( _offPoints.empty() )
5332 // move _offPoints to a new position
5334 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5335 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 0, helper );
5336 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 1, helper );
5337 _leOnV[0]._len = e[0]->_len;
5338 _leOnV[1]._len = e[1]->_len;
5339 for ( size_t i = 0; i < _offPoints.size(); i++ )
5341 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5342 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5343 const double w0 = _offPoints[i]._2edges._wgt[0];
5344 const double w1 = _offPoints[i]._2edges._wgt[1];
5345 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5346 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5347 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5349 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5350 _offPoints[i]._len = avgLen;
5354 if ( !surface.IsNull() ) // project _offPoints to the FACE
5356 fTol = 100 * BRep_Tool::Tolerance( F );
5357 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5359 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5360 //if ( surface->Gap() < 0.5 * segLen )
5361 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5363 for ( size_t i = 1; i < _offPoints.size(); ++i )
5365 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5366 //if ( surface->Gap() < 0.5 * segLen )
5367 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5371 // project tgt nodes of extreme _LayerEdge's to the offset segments
5373 gp_Pnt pExtreme[2], pProj[2];
5374 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5376 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5377 int i = _iSeg[ is2nd ];
5378 int di = is2nd ? -1 : +1;
5379 bool projected = false;
5380 double uOnSeg, uOnSegDiff, uOnSegBestDiff = Precision::Infinite();
5382 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5383 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5384 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude();
5385 uOnSegDiff = Abs( uOnSeg - 0.5 );
5386 projected = ( uOnSegDiff <= 0.5 );
5387 if ( uOnSegDiff < uOnSegBestDiff )
5390 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5391 uOnSegBestDiff = uOnSegDiff;
5395 while ( !projected &&
5396 i >= 0 && i+1 < (int)_offPoints.size() );
5400 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5403 _iSeg[1] = _offPoints.size()-2;
5404 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5409 if ( _iSeg[0] > _iSeg[1] )
5411 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5415 // compute normalized length of the offset segments located between the projections
5417 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5418 vector< double > len( nbSeg + 1 );
5420 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
5421 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5423 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5425 len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
5427 double d0 = pProj[0].Distance( pExtreme[0]);
5428 double d1 = pProj[1].Distance( pExtreme[1]);
5429 double fullLen = len.back() - d0 - d1;
5430 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5431 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5433 // temporary replace extreme _offPoints by pExtreme
5434 gp_XYZ op[2] = { _offPoints[ _iSeg[0] ]._xyz,
5435 _offPoints[ _iSeg[1]+1 ]._xyz };
5436 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
5437 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5439 // distribute tgt nodes of _LayerEdge's between the projections
5442 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5444 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5445 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5447 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5448 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
5449 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5451 if ( surface.IsNull() )
5453 _eos._edges[i]->_pos.back() = p;
5455 else // project a new node position to a FACE
5457 gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5458 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5460 p = surface->Value( uv2 ).XYZ();
5461 _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5463 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5464 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5465 dumpMove( tgtNode );
5468 _offPoints[ _iSeg[0] ]._xyz = op[0];
5469 _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5474 //================================================================================
5476 * \brief Prepare for smoothing
5478 //================================================================================
5480 void _Smoother1D::prepare(_SolidData& data)
5482 // sort _LayerEdge's by position on the EDGE
5483 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5484 data.SortOnEdge( E, _eos._edges );
5486 // compute normalized param of _eos._edges on EDGE
5487 _leParams.resize( _eos._edges.size() + 1 );
5489 double curLen, prevLen = _leParams[0] = 1.0;
5490 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5492 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5494 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5495 //curLen = prevLen * _eos._edges[i]->_2neibors->_wgt[1] / _eos._edges[i]->_2neibors->_wgt[0];
5496 curLen = p.Distance( pPrev );
5497 _leParams[i+1] = _leParams[i] + curLen;
5501 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5502 for ( size_t i = 0; i < _leParams.size(); ++i )
5503 _leParams[i] = _leParams[i+1] / fullLen;
5509 // divide E to have offset segments with low deflection
5510 BRepAdaptor_Curve c3dAdaptor( E );
5511 const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5512 const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5513 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5514 if ( discret.NbPoints() <= 2 )
5516 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5520 const double edgeLen = SMESH_Algo::EdgeLength( E );
5521 const double u0 = c3dAdaptor.FirstParameter();
5522 _offPoints.resize( discret.NbPoints() );
5523 for ( size_t i = 0; i < _offPoints.size(); i++ )
5525 _offPoints[i]._xyz = discret.Value( i+1 ).XYZ();
5526 // use OffPnt::_len to TEMPORARY store normalized param of an offset point
5527 double u = discret.Parameter( i+1 );
5528 _offPoints[i]._len = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / edgeLen;
5531 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5534 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5535 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5536 _2NearEdges tmp2edges;
5537 tmp2edges._edges[1] = _eos._edges[0];
5538 _leOnV[0]._2neibors = & tmp2edges;
5539 _leOnV[0]._nodes = leOnV[0]->_nodes;
5540 _leOnV[1]._nodes = leOnV[1]->_nodes;
5541 _LayerEdge* eNext, *ePrev = & _leOnV[0];
5542 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5544 // find _LayerEdge's located before and after an offset point
5545 // (_eos._edges[ iLE ] is next after ePrev)
5546 while ( iLE < _eos._edges.size() && _offPoints[i]._len > _leParams[ iLE ] )
5547 ePrev = _eos._edges[ iLE++ ];
5548 eNext = ePrev->_2neibors->_edges[1];
5550 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5551 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5552 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5553 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5556 int iLBO = _offPoints.size() - 2; // last but one
5557 _offPoints[iLBO]._2edges._edges[1] = & _leOnV[1];
5560 // TopoDS_Face face[2]; // FACEs sharing the EDGE
5561 // PShapeIteratorPtr fIt = helper.GetAncestors( _eos._shape, *helper.GetMesh(), TopAbs_FACE );
5562 // while ( const TopoDS_Shape* F = fIt->next() )
5564 // TGeomID fID = helper.GetMeshDS()->ShapeToIndex( *F );
5565 // if ( ! data._ignoreFaceIds.count( fID ))
5566 // face[ !face[0].IsNull() ] = *F;
5568 // if ( face[0].IsNull() ) return;
5569 // if ( face[1].IsNull() ) face[1] = face[0];
5573 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5575 setNormalOnV( 0, data.GetHelper() );
5576 setNormalOnV( 1, data.GetHelper() );
5577 _leOnV[ 0 ]._len = 0;
5578 _leOnV[ 1 ]._len = 0;
5579 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
5580 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5583 _iSeg[1] = _offPoints.size()-2;
5585 // initialize OffPnt::_len
5586 for ( size_t i = 0; i < _offPoints.size(); ++i )
5587 _offPoints[i]._len = 0;
5589 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5591 _leOnV[0]._len = leOnV[0]->_len;
5592 _leOnV[1]._len = leOnV[1]->_len;
5593 for ( size_t i = 0; i < _offPoints.size(); i++ )
5595 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5596 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5597 const double w0 = _offPoints[i]._2edges._wgt[0];
5598 const double w1 = _offPoints[i]._2edges._wgt[1];
5599 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5600 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5601 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5602 _offPoints[i]._xyz = avgXYZ;
5603 _offPoints[i]._len = avgLen;
5608 //================================================================================
5610 * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5612 //================================================================================
5614 void _Smoother1D::setNormalOnV( const bool is2nd,
5615 SMESH_MesherHelper& helper)
5617 _LayerEdge* leOnV = getLEdgeOnV( is2nd );
5618 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5619 TopoDS_Shape V = helper.GetSubShapeByNode( leOnV->_nodes[0], helper.GetMeshDS() );
5620 gp_XYZ eDir = getEdgeDir( E, TopoDS::Vertex( V ));
5621 gp_XYZ cross = leOnV->_normal ^ eDir;
5622 gp_XYZ norm = eDir ^ cross;
5623 double size = norm.Modulus();
5625 _leOnV[ is2nd ]._normal = norm / size;
5628 //================================================================================
5630 * \brief Sort _LayerEdge's by a parameter on a given EDGE
5632 //================================================================================
5634 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
5635 vector< _LayerEdge* >& edges)
5637 map< double, _LayerEdge* > u2edge;
5638 for ( size_t i = 0; i < edges.size(); ++i )
5639 u2edge.insert( u2edge.end(),
5640 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5642 ASSERT( u2edge.size() == edges.size() );
5643 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5644 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5645 edges[i] = u2e->second;
5647 Sort2NeiborsOnEdge( edges );
5650 //================================================================================
5652 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5654 //================================================================================
5656 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5658 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5660 for ( size_t i = 0; i < edges.size()-1; ++i )
5661 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5662 edges[i]->_2neibors->reverse();
5664 const size_t iLast = edges.size() - 1;
5665 if ( edges.size() > 1 &&
5666 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5667 edges[iLast]->_2neibors->reverse();
5670 //================================================================================
5672 * \brief Return _EdgesOnShape* corresponding to the shape
5674 //================================================================================
5676 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5678 if ( shapeID < (int)_edgesOnShape.size() &&
5679 _edgesOnShape[ shapeID ]._shapeID == shapeID )
5680 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5682 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5683 if ( _edgesOnShape[i]._shapeID == shapeID )
5684 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5689 //================================================================================
5691 * \brief Return _EdgesOnShape* corresponding to the shape
5693 //================================================================================
5695 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5697 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5698 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5701 //================================================================================
5703 * \brief Prepare data of the _LayerEdge for smoothing on FACE
5705 //================================================================================
5707 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5709 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5711 set< TGeomID > vertices;
5713 if ( eos->ShapeType() == TopAbs_FACE )
5715 // check FACE concavity and get concave VERTEXes
5716 F = TopoDS::Face( eos->_shape );
5717 if ( isConcave( F, helper, &vertices ))
5718 _concaveFaces.insert( eos->_shapeID );
5720 // set eos._eosConcaVer
5721 eos->_eosConcaVer.clear();
5722 eos->_eosConcaVer.reserve( vertices.size() );
5723 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5725 _EdgesOnShape* eov = GetShapeEdges( *v );
5726 if ( eov && eov->_edges.size() == 1 )
5728 eos->_eosConcaVer.push_back( eov );
5729 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5730 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5734 // SetSmooLen() to _LayerEdge's on FACE
5735 for ( size_t i = 0; i < eos->_edges.size(); ++i )
5737 eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5739 SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5740 while ( smIt->more() ) // loop on sub-shapes of the FACE
5742 _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5743 if ( !eoe ) continue;
5745 vector<_LayerEdge*>& eE = eoe->_edges;
5746 for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5748 if ( eE[iE]->_cosin <= theMinSmoothCosin )
5751 SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5752 while ( segIt->more() )
5754 const SMDS_MeshElement* seg = segIt->next();
5755 if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
5757 if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
5758 continue; // not to check a seg twice
5759 for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
5761 _LayerEdge* eN = eE[iE]->_neibors[iN];
5762 if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
5764 double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
5765 double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
5766 eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
5767 eN->Set( _LayerEdge::NEAR_BOUNDARY );
5772 } // if ( eos->ShapeType() == TopAbs_FACE )
5774 for ( size_t i = 0; i < eos->_edges.size(); ++i )
5776 eos->_edges[i]->_smooFunction = 0;
5777 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
5779 bool isCurved = false;
5780 for ( size_t i = 0; i < eos->_edges.size(); ++i )
5782 _LayerEdge* edge = eos->_edges[i];
5784 // get simplices sorted
5785 _Simplex::SortSimplices( edge->_simplices );
5787 // smoothing function
5788 edge->ChooseSmooFunction( vertices, _n2eMap );
5791 double avgNormProj = 0, avgLen = 0;
5792 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
5794 _Simplex& s = edge->_simplices[iS];
5796 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
5797 avgNormProj += edge->_normal * vec;
5798 avgLen += vec.Modulus();
5799 if ( substituteSrcNodes )
5801 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
5802 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
5805 avgNormProj /= edge->_simplices.size();
5806 avgLen /= edge->_simplices.size();
5807 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
5810 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
5812 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
5813 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
5815 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
5819 // prepare for putOnOffsetSurface()
5820 if (( eos->ShapeType() == TopAbs_FACE ) &&
5821 ( isCurved || !eos->_eosConcaVer.empty() ))
5823 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
5824 eos->_edgeForOffset = 0;
5826 double maxCosin = -1;
5827 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
5829 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
5830 if ( !eoe || eoe->_edges.empty() ) continue;
5832 vector<_LayerEdge*>& eE = eoe->_edges;
5833 _LayerEdge* e = eE[ eE.size() / 2 ];
5834 if ( e->_cosin > maxCosin )
5836 eos->_edgeForOffset = e;
5837 maxCosin = e->_cosin;
5843 //================================================================================
5845 * \brief Add faces for smoothing
5847 //================================================================================
5849 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
5850 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
5852 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
5853 for ( ; eos != eosToSmooth.end(); ++eos )
5855 if ( !*eos || (*eos)->_toSmooth ) continue;
5857 (*eos)->_toSmooth = true;
5859 if ( (*eos)->ShapeType() == TopAbs_FACE )
5861 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
5862 (*eos)->_toSmooth = true;
5866 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
5867 if ( edgesNoAnaSmooth )
5868 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
5870 if ( (*eos)->_edgeSmoother )
5871 (*eos)->_edgeSmoother->_anaCurve.Nullify();
5875 //================================================================================
5877 * \brief Fill data._collisionEdges
5879 //================================================================================
5881 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
5883 data._collisionEdges.clear();
5885 // set the full thickness of the layers to LEs
5886 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5888 _EdgesOnShape& eos = data._edgesOnShape[iS];
5889 if ( eos._edges.empty() ) continue;
5890 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
5892 for ( size_t i = 0; i < eos._edges.size(); ++i )
5894 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5895 double maxLen = eos._edges[i]->_maxLen;
5896 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
5897 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
5898 eos._edges[i]->_maxLen = maxLen;
5902 // make temporary quadrangles got by extrusion of
5903 // mesh edges along _LayerEdge._normal's
5905 vector< const SMDS_MeshElement* > tmpFaces;
5907 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5909 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5910 if ( eos.ShapeType() != TopAbs_EDGE )
5912 if ( eos._edges.empty() )
5914 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
5915 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5916 while ( smIt->more() )
5917 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
5918 if ( eov->_edges.size() == 1 )
5919 edge[ bool( edge[0]) ] = eov->_edges[0];
5923 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
5924 tmpFaces.push_back( f );
5927 for ( size_t i = 0; i < eos._edges.size(); ++i )
5929 _LayerEdge* edge = eos._edges[i];
5930 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
5932 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
5933 if ( src2->GetPosition()->GetDim() > 0 &&
5934 src2->GetID() < edge->_nodes[0]->GetID() )
5935 continue; // avoid using same segment twice
5937 // a _LayerEdge containg tgt2
5938 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
5940 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
5941 tmpFaces.push_back( f );
5946 // Find _LayerEdge's intersecting tmpFaces.
5948 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
5950 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5951 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
5953 double dist1, dist2, segLen, eps;
5954 _CollisionEdges collEdges;
5955 vector< const SMDS_MeshElement* > suspectFaces;
5956 const double angle30 = Cos( 30. * M_PI / 180. );
5958 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5960 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5961 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
5963 // find sub-shapes whose VL can influence VL on eos
5964 set< TGeomID > neighborShapes;
5965 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
5966 while ( const TopoDS_Shape* face = fIt->next() )
5968 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
5969 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
5971 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5972 while ( subIt->more() )
5973 neighborShapes.insert( subIt->next()->GetId() );
5976 if ( eos.ShapeType() == TopAbs_VERTEX )
5978 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
5979 while ( const TopoDS_Shape* edge = eIt->next() )
5980 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
5982 // find intersecting _LayerEdge's
5983 for ( size_t i = 0; i < eos._edges.size(); ++i )
5985 _LayerEdge* edge = eos._edges[i];
5986 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
5987 eps = 0.5 * edge->_len;
5990 gp_Vec eSegDir0, eSegDir1;
5991 if ( edge->IsOnEdge() )
5993 SMESH_TNodeXYZ eP( edge->_nodes[0] );
5994 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
5995 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
5997 suspectFaces.clear();
5998 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len,
5999 SMDSAbs_Face, suspectFaces );
6000 collEdges._intEdges.clear();
6001 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6003 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6004 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6005 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6006 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6007 if ( edge->IsOnEdge() ) {
6008 if ( edge->_2neibors->include( f->_le1 ) ||
6009 edge->_2neibors->include( f->_le2 )) continue;
6012 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6013 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6015 dist1 = dist2 = Precision::Infinite();
6016 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6017 dist1 = Precision::Infinite();
6018 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6019 dist2 = Precision::Infinite();
6020 if (( dist1 > segLen ) && ( dist2 > segLen ))
6023 if ( edge->IsOnEdge() )
6025 // skip perpendicular EDGEs
6026 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6027 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle30 ) ||
6028 isLessAngle( eSegDir1, fSegDir, angle30 ) ||
6029 isLessAngle( eSegDir0, fSegDir.Reversed(), angle30 ) ||
6030 isLessAngle( eSegDir1, fSegDir.Reversed(), angle30 ));
6035 // either limit inflation of edges or remember them for updating _normal
6036 // double dot = edge->_normal * f->GetDir();
6039 collEdges._intEdges.push_back( f->_le1 );
6040 collEdges._intEdges.push_back( f->_le2 );
6044 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6045 // edge->_maxLen = Min( shortLen, edge->_maxLen );
6049 if ( !collEdges._intEdges.empty() )
6051 collEdges._edge = edge;
6052 data._collisionEdges.push_back( collEdges );
6057 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6060 // restore the zero thickness
6061 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6063 _EdgesOnShape& eos = data._edgesOnShape[iS];
6064 if ( eos._edges.empty() ) continue;
6065 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6067 for ( size_t i = 0; i < eos._edges.size(); ++i )
6069 eos._edges[i]->InvalidateStep( 1, eos );
6070 eos._edges[i]->_len = 0;
6075 //================================================================================
6077 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6078 * _LayerEdge's on neighbor EDGE's
6080 //================================================================================
6082 bool _ViscousBuilder::updateNormals( _SolidData& data,
6083 SMESH_MesherHelper& helper,
6087 updateNormalsOfC1Vertices( data );
6089 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6092 // map to store new _normal and _cosin for each intersected edge
6093 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6094 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6095 _LayerEdge zeroEdge;
6096 zeroEdge._normal.SetCoord( 0,0,0 );
6097 zeroEdge._maxLen = Precision::Infinite();
6098 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6100 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6102 double segLen, dist1, dist2;
6103 vector< pair< _LayerEdge*, double > > intEdgesDist;
6104 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6106 for ( int iter = 0; iter < 5; ++iter )
6108 edge2newEdge.clear();
6110 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6112 _CollisionEdges& ce = data._collisionEdges[iE];
6113 _LayerEdge* edge1 = ce._edge;
6114 if ( !edge1 || edge1->Is( _LayerEdge::BLOCKED )) continue;
6115 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6116 if ( !eos1 ) continue;
6118 // detect intersections
6119 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6120 double testLen = 1.5 * edge1->_maxLen; //2 + edge1->_len * edge1->_lenFactor;
6121 double eps = 0.5 * edge1->_len;
6122 intEdgesDist.clear();
6123 double minIntDist = Precision::Infinite();
6124 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6126 if ( ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) ||
6127 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6129 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6130 double fact = ( 1.1 + dot * dot );
6131 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6132 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6133 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6134 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6135 dist1 = dist2 = Precision::Infinite();
6136 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pTgt0, pSrc1, dist1, eps ) &&
6137 !edge1->SegTriaInter( lastSeg, pSrc1, pTgt1, pTgt0, dist2, eps ))
6139 if (( dist1 > testLen || dist1 < 0 ) &&
6140 ( dist2 > testLen || dist2 < 0 ))
6143 // choose a closest edge
6144 gp_Pnt intP( lastSeg.Location().XYZ() +
6145 lastSeg.Direction().XYZ() * ( Min( dist1, dist2 ) + segLen ));
6146 double d1 = intP.SquareDistance( pSrc0 );
6147 double d2 = intP.SquareDistance( pSrc1 );
6148 int iClose = i + ( d2 < d1 );
6149 _LayerEdge* edge2 = ce._intEdges[iClose];
6150 edge2->Unset( _LayerEdge::MARKED );
6152 // choose a closest edge among neighbors
6153 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6154 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6155 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6157 _LayerEdge * edgeJ = intEdgesDist[j].first;
6158 if ( edge2->IsNeiborOnEdge( edgeJ ))
6160 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6161 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6164 intEdgesDist.push_back( make_pair( edge2, Min( dist1, dist2 )));
6165 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6167 // iClose = i + !( d2 < d1 );
6168 // intEdges.push_back( ce._intEdges[iClose] );
6169 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6171 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist1, minIntDist );
6172 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist2, minIntDist );
6177 // compute new _normals
6178 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6180 _LayerEdge* edge2 = intEdgesDist[i].first;
6181 double distWgt = edge1->_len / intEdgesDist[i].second;
6182 if ( edge2->Is( _LayerEdge::MARKED )) continue;
6183 edge2->Set( _LayerEdge::MARKED );
6186 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6188 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6189 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6190 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6191 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6192 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6193 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6194 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6195 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6196 newNormal.Normalize();
6200 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6201 if ( cos1 < theMinSmoothCosin )
6203 newCos = cos2 * sgn1;
6205 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6207 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6211 newCos = edge1->_cosin;
6214 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6215 e2neIt->second._normal += distWgt * newNormal;
6216 e2neIt->second._cosin = newCos;
6217 e2neIt->second._maxLen = 0.7 * minIntDist / edge1->_lenFactor;
6218 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6219 e2neIt->second._normal += dir2;
6220 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6221 e2neIt->second._normal += distWgt * newNormal;
6222 e2neIt->second._cosin = edge2->_cosin;
6223 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6224 e2neIt->second._normal += dir1;
6228 if ( edge2newEdge.empty() )
6229 break; //return true;
6231 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6233 // Update data of edges depending on a new _normal
6236 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6238 _LayerEdge* edge = e2neIt->first;
6239 _LayerEdge& newEdge = e2neIt->second;
6240 _EdgesOnShape* eos = data.GetShapeEdges( edge );
6242 // Check if a new _normal is OK:
6243 newEdge._normal.Normalize();
6244 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6246 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6248 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6249 edge->_maxLen = newEdge._maxLen;
6250 edge->SetNewLength( newEdge._maxLen, *eos, helper );
6252 continue; // the new _normal is bad
6254 // the new _normal is OK
6256 // find shapes that need smoothing due to change of _normal
6257 if ( edge->_cosin < theMinSmoothCosin &&
6258 newEdge._cosin > theMinSmoothCosin )
6260 if ( eos->_sWOL.IsNull() )
6262 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6263 while ( fIt->more() )
6264 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6266 else // edge inflates along a FACE
6268 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6269 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6270 while ( const TopoDS_Shape* E = eIt->next() )
6272 if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6274 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6275 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6276 if ( angle < M_PI / 2 )
6277 shapesToSmooth.insert( data.GetShapeEdges( *E ));
6282 double len = edge->_len;
6283 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6284 edge->SetNormal( newEdge._normal );
6285 edge->SetCosin( newEdge._cosin );
6286 edge->SetNewLength( len, *eos, helper );
6287 edge->Set( _LayerEdge::MARKED );
6288 edge->Set( _LayerEdge::NORMAL_UPDATED );
6289 edgesNoAnaSmooth.insert( eos );
6292 // Update normals and other dependent data of not intersecting _LayerEdge's
6293 // neighboring the intersecting ones
6295 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6297 _LayerEdge* edge1 = e2neIt->first;
6298 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6299 if ( !edge1->Is( _LayerEdge::MARKED ))
6302 if ( edge1->IsOnEdge() )
6304 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6305 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6306 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6309 if ( !edge1->_2neibors )
6311 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6313 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6314 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6315 continue; // j-th neighbor is also intersected
6316 _LayerEdge* prevEdge = edge1;
6317 const int nbSteps = 10;
6318 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6320 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6321 neighbor->Is( _LayerEdge::MARKED ))
6323 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6324 if ( !eos ) continue;
6325 _LayerEdge* nextEdge = neighbor;
6326 if ( neighbor->_2neibors )
6329 nextEdge = neighbor->_2neibors->_edges[iNext];
6330 if ( nextEdge == prevEdge )
6331 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6333 double r = double(step-1)/nbSteps;
6334 if ( !nextEdge->_2neibors )
6337 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6338 newNorm.Normalize();
6339 if ( !isNewNormalOk( data, *neighbor, newNorm ))
6342 double len = neighbor->_len;
6343 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6344 neighbor->SetNormal( newNorm );
6345 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6346 if ( neighbor->_2neibors )
6347 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6348 neighbor->SetNewLength( len, *eos, helper );
6349 neighbor->Set( _LayerEdge::MARKED );
6350 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6351 edgesNoAnaSmooth.insert( eos );
6353 if ( !neighbor->_2neibors )
6354 break; // neighbor is on VERTEX
6356 // goto the next neighbor
6357 prevEdge = neighbor;
6358 neighbor = nextEdge;
6365 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6370 //================================================================================
6372 * \brief Check if a new normal is OK
6374 //================================================================================
6376 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
6378 const gp_XYZ& newNormal)
6380 // check a min angle between the newNormal and surrounding faces
6381 vector<_Simplex> simplices;
6382 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6383 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6384 double newMinDot = 1, curMinDot = 1;
6385 for ( size_t i = 0; i < simplices.size(); ++i )
6387 n1.Set( simplices[i]._nPrev );
6388 n2.Set( simplices[i]._nNext );
6389 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6390 double normLen2 = normFace.SquareModulus();
6391 if ( normLen2 < std::numeric_limits<double>::min() )
6393 normFace /= Sqrt( normLen2 );
6394 newMinDot = Min( newNormal * normFace, newMinDot );
6395 curMinDot = Min( edge._normal * normFace, curMinDot );
6397 if ( newMinDot < 0.5 )
6399 return ( newMinDot >= curMinDot * 0.9 );
6400 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6401 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6402 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6407 //================================================================================
6409 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6411 //================================================================================
6413 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
6414 SMESH_MesherHelper& helper,
6416 const double stepSize )
6418 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6419 return true; // no shapes needing smoothing
6421 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6423 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6424 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
6425 !eos._hyp.ToSmooth() ||
6426 eos.ShapeType() != TopAbs_FACE ||
6427 eos._edges.empty() )
6430 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6431 if ( !toSmooth ) continue;
6433 for ( size_t i = 0; i < eos._edges.size(); ++i )
6435 _LayerEdge* edge = eos._edges[i];
6436 if ( !edge->Is( _LayerEdge::SMOOTHED ))
6438 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6441 const gp_XYZ& pPrev = edge->PrevPos();
6442 const gp_XYZ& pLast = edge->_pos.back();
6443 gp_XYZ stepVec = pLast - pPrev;
6444 double realStepSize = stepVec.Modulus();
6445 if ( realStepSize < numeric_limits<double>::min() )
6448 edge->_lenFactor = realStepSize / stepSize;
6449 edge->_normal = stepVec / realStepSize;
6450 edge->Set( _LayerEdge::NORMAL_UPDATED );
6457 //================================================================================
6459 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6461 //================================================================================
6463 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6465 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6467 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6468 if ( eov._eosC1.empty() ||
6469 eov.ShapeType() != TopAbs_VERTEX ||
6470 eov._edges.empty() )
6473 gp_XYZ newNorm = eov._edges[0]->_normal;
6474 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6475 bool normChanged = false;
6477 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6479 _EdgesOnShape* eoe = eov._eosC1[i];
6480 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6481 const double eLen = SMESH_Algo::EdgeLength( e );
6482 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
6483 if ( oppV.IsSame( eov._shape ))
6484 oppV = SMESH_MesherHelper::IthVertex( 1, e );
6485 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6486 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6488 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6489 if ( curThickOpp + curThick < eLen )
6492 double wgt = 2. * curThick / eLen;
6493 newNorm += wgt * eovOpp->_edges[0]->_normal;
6498 eov._edges[0]->SetNormal( newNorm.Normalized() );
6499 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6504 //================================================================================
6506 * \brief Modify normals of _LayerEdge's on _ConvexFace's
6508 //================================================================================
6510 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
6511 SMESH_MesherHelper& helper,
6514 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6517 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6518 for ( ; id2face != data._convexFaces.end(); ++id2face )
6520 _ConvexFace & convFace = (*id2face).second;
6521 if ( convFace._normalsFixed )
6522 continue; // already fixed
6523 if ( convFace.CheckPrisms() )
6524 continue; // nothing to fix
6526 convFace._normalsFixed = true;
6528 BRepAdaptor_Surface surface ( convFace._face, false );
6529 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
6531 // check if the convex FACE is of spherical shape
6533 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6537 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6538 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6540 _EdgesOnShape& eos = *(id2eos->second);
6541 if ( eos.ShapeType() == TopAbs_VERTEX )
6543 _LayerEdge* ledge = eos._edges[ 0 ];
6544 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6545 centersBox.Add( center );
6547 for ( size_t i = 0; i < eos._edges.size(); ++i )
6548 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6550 if ( centersBox.IsVoid() )
6552 debugMsg( "Error: centersBox.IsVoid()" );
6555 const bool isSpherical =
6556 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6558 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6559 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6563 // set _LayerEdge::_normal as average of all normals
6565 // WARNING: different density of nodes on EDGEs is not taken into account that
6566 // can lead to an improper new normal
6568 gp_XYZ avgNormal( 0,0,0 );
6570 id2eos = convFace._subIdToEOS.begin();
6571 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6573 _EdgesOnShape& eos = *(id2eos->second);
6574 // set data of _CentralCurveOnEdge
6575 if ( eos.ShapeType() == TopAbs_EDGE )
6577 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6578 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6579 if ( !eos._sWOL.IsNull() )
6580 ceCurve._adjFace.Nullify();
6582 ceCurve._ledges.insert( ceCurve._ledges.end(),
6583 eos._edges.begin(), eos._edges.end());
6585 // summarize normals
6586 for ( size_t i = 0; i < eos._edges.size(); ++i )
6587 avgNormal += eos._edges[ i ]->_normal;
6589 double normSize = avgNormal.SquareModulus();
6590 if ( normSize < 1e-200 )
6592 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6595 avgNormal /= Sqrt( normSize );
6597 // compute new _LayerEdge::_cosin on EDGEs
6598 double avgCosin = 0;
6601 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6603 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6604 if ( ceCurve._adjFace.IsNull() )
6606 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6608 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6609 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6612 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6613 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6614 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6620 avgCosin /= nbCosin;
6622 // set _LayerEdge::_normal = avgNormal
6623 id2eos = convFace._subIdToEOS.begin();
6624 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6626 _EdgesOnShape& eos = *(id2eos->second);
6627 if ( eos.ShapeType() != TopAbs_EDGE )
6628 for ( size_t i = 0; i < eos._edges.size(); ++i )
6629 eos._edges[ i ]->_cosin = avgCosin;
6631 for ( size_t i = 0; i < eos._edges.size(); ++i )
6633 eos._edges[ i ]->SetNormal( avgNormal );
6634 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6638 else // if ( isSpherical )
6640 // We suppose that centers of curvature at all points of the FACE
6641 // lie on some curve, let's call it "central curve". For all _LayerEdge's
6642 // having a common center of curvature we define the same new normal
6643 // as a sum of normals of _LayerEdge's on EDGEs among them.
6645 // get all centers of curvature for each EDGE
6647 helper.SetSubShape( convFace._face );
6648 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6650 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6651 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6653 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6655 // set adjacent FACE
6656 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
6658 // get _LayerEdge's of the EDGE
6659 TGeomID edgeID = meshDS->ShapeToIndex( edge );
6660 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
6661 if ( !eos || eos->_edges.empty() )
6663 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
6664 for ( int iV = 0; iV < 2; ++iV )
6666 TopoDS_Vertex v = helper.IthVertex( iV, edge );
6667 TGeomID vID = meshDS->ShapeToIndex( v );
6668 eos = data.GetShapeEdges( vID );
6669 vertexLEdges[ iV ] = eos->_edges[ 0 ];
6671 edgeLEdge = &vertexLEdges[0];
6672 edgeLEdgeEnd = edgeLEdge + 2;
6674 centerCurves[ iE ]._adjFace.Nullify();
6678 if ( ! eos->_toSmooth )
6679 data.SortOnEdge( edge, eos->_edges );
6680 edgeLEdge = &eos->_edges[ 0 ];
6681 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
6682 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
6683 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
6685 if ( ! eos->_sWOL.IsNull() )
6686 centerCurves[ iE ]._adjFace.Nullify();
6689 // Get curvature centers
6693 if ( edgeLEdge[0]->IsOnEdge() &&
6694 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
6696 centerCurves[ iE ].Append( center, vertexLEdges[0] );
6697 centersBox.Add( center );
6699 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
6700 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
6701 { // EDGE or VERTEXes
6702 centerCurves[ iE ].Append( center, *edgeLEdge );
6703 centersBox.Add( center );
6705 if ( edgeLEdge[-1]->IsOnEdge() &&
6706 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
6708 centerCurves[ iE ].Append( center, vertexLEdges[1] );
6709 centersBox.Add( center );
6711 centerCurves[ iE ]._isDegenerated =
6712 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6714 } // loop on EDGES of convFace._face to set up data of centerCurves
6716 // Compute new normals for _LayerEdge's on EDGEs
6718 double avgCosin = 0;
6721 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
6723 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
6724 if ( ceCurve._isDegenerated )
6726 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
6727 vector< gp_XYZ > & newNormals = ceCurve._normals;
6728 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
6731 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
6734 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
6736 if ( isOK && !ceCurve._adjFace.IsNull() )
6738 // compute new _LayerEdge::_cosin
6739 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
6740 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6743 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
6744 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
6745 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
6751 // set new normals to _LayerEdge's of NOT degenerated central curves
6752 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6754 if ( centerCurves[ iE ]._isDegenerated )
6756 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6758 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
6759 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6762 // set new normals to _LayerEdge's of degenerated central curves
6763 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6765 if ( !centerCurves[ iE ]._isDegenerated ||
6766 centerCurves[ iE ]._ledges.size() < 3 )
6768 // new normal is an average of new normals at VERTEXes that
6769 // was computed on non-degenerated _CentralCurveOnEdge's
6770 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
6771 centerCurves[ iE ]._ledges.back ()->_normal );
6772 double sz = newNorm.Modulus();
6776 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
6777 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
6778 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
6780 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
6781 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
6782 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6786 // Find new normals for _LayerEdge's based on FACE
6789 avgCosin /= nbCosin;
6790 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
6791 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
6792 if ( id2eos != convFace._subIdToEOS.end() )
6796 _EdgesOnShape& eos = * ( id2eos->second );
6797 for ( size_t i = 0; i < eos._edges.size(); ++i )
6799 _LayerEdge* ledge = eos._edges[ i ];
6800 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6802 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
6804 iE = iE % centerCurves.size();
6805 if ( centerCurves[ iE ]._isDegenerated )
6807 newNorm.SetCoord( 0,0,0 );
6808 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
6810 ledge->SetNormal( newNorm );
6811 ledge->_cosin = avgCosin;
6812 ledge->Set( _LayerEdge::NORMAL_UPDATED );
6819 } // not a quasi-spherical FACE
6821 // Update _LayerEdge's data according to a new normal
6823 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
6824 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
6826 id2eos = convFace._subIdToEOS.begin();
6827 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6829 _EdgesOnShape& eos = * ( id2eos->second );
6830 for ( size_t i = 0; i < eos._edges.size(); ++i )
6832 _LayerEdge* & ledge = eos._edges[ i ];
6833 double len = ledge->_len;
6834 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
6835 ledge->SetCosin( ledge->_cosin );
6836 ledge->SetNewLength( len, eos, helper );
6838 if ( eos.ShapeType() != TopAbs_FACE )
6839 for ( size_t i = 0; i < eos._edges.size(); ++i )
6841 _LayerEdge* ledge = eos._edges[ i ];
6842 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
6844 _LayerEdge* neibor = ledge->_neibors[iN];
6845 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
6847 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
6848 neibor->Set( _LayerEdge::MOVED );
6849 neibor->SetSmooLen( neibor->_len );
6853 } // loop on sub-shapes of convFace._face
6855 // Find FACEs adjacent to convFace._face that got necessity to smooth
6856 // as a result of normals modification
6858 set< _EdgesOnShape* > adjFacesToSmooth;
6859 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6861 if ( centerCurves[ iE ]._adjFace.IsNull() ||
6862 centerCurves[ iE ]._adjFaceToSmooth )
6864 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6866 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
6868 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
6873 data.AddShapesToSmooth( adjFacesToSmooth );
6878 } // loop on data._convexFaces
6883 //================================================================================
6885 * \brief Finds a center of curvature of a surface at a _LayerEdge
6887 //================================================================================
6889 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
6890 BRepLProp_SLProps& surfProp,
6891 SMESH_MesherHelper& helper,
6892 gp_Pnt & center ) const
6894 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
6895 surfProp.SetParameters( uv.X(), uv.Y() );
6896 if ( !surfProp.IsCurvatureDefined() )
6899 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
6900 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
6901 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
6902 if ( surfCurvatureMin > surfCurvatureMax )
6903 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
6905 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
6910 //================================================================================
6912 * \brief Check that prisms are not distorted
6914 //================================================================================
6916 bool _ConvexFace::CheckPrisms() const
6919 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
6921 const _LayerEdge* edge = _simplexTestEdges[i];
6922 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
6923 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
6924 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
6926 debugMsg( "Bad simplex of _simplexTestEdges ("
6927 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
6928 << " "<< edge->_simplices[j]._nPrev->GetID()
6929 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
6936 //================================================================================
6938 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
6939 * stored in this _CentralCurveOnEdge.
6940 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
6941 * \param [in,out] newNormal - current normal at this point, to be redefined
6942 * \return bool - true if succeeded.
6944 //================================================================================
6946 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
6948 if ( this->_isDegenerated )
6951 // find two centers the given one lies between
6953 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
6955 double sl2 = 1.001 * _segLength2[ i ];
6957 double d1 = center.SquareDistance( _curvaCenters[ i ]);
6961 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
6962 if ( d2 > sl2 || d2 + d1 < 1e-100 )
6967 double r = d1 / ( d1 + d2 );
6968 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
6969 ( r ) * _ledges[ i+1 ]->_normal );
6973 double sz = newNormal.Modulus();
6982 //================================================================================
6984 * \brief Set shape members
6986 //================================================================================
6988 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
6989 const _ConvexFace& convFace,
6991 SMESH_MesherHelper& helper)
6995 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
6996 while ( const TopoDS_Shape* F = fIt->next())
6997 if ( !convFace._face.IsSame( *F ))
6999 _adjFace = TopoDS::Face( *F );
7000 _adjFaceToSmooth = false;
7001 // _adjFace already in a smoothing queue ?
7002 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7003 _adjFaceToSmooth = eos->_toSmooth;
7008 //================================================================================
7010 * \brief Looks for intersection of it's last segment with faces
7011 * \param distance - returns shortest distance from the last node to intersection
7013 //================================================================================
7015 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7017 const double& epsilon,
7019 const SMDS_MeshElement** intFace)
7021 vector< const SMDS_MeshElement* > suspectFaces;
7023 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7024 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7026 bool segmentIntersected = false;
7027 distance = Precision::Infinite();
7028 int iFace = -1; // intersected face
7029 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7031 const SMDS_MeshElement* face = suspectFaces[j];
7032 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7033 face->GetNodeIndex( _nodes[0] ) >= 0 )
7034 continue; // face sharing _LayerEdge node
7035 const int nbNodes = face->NbCornerNodes();
7036 bool intFound = false;
7038 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7041 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7045 const SMDS_MeshNode* tria[3];
7048 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7051 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7057 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7058 segmentIntersected = true;
7059 if ( distance > dist )
7060 distance = dist, iFace = j;
7063 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7067 if ( segmentIntersected )
7070 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7071 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7072 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7073 << ", intersection with face ("
7074 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7075 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7076 << ") distance = " << distance << endl;
7080 return segmentIntersected;
7083 //================================================================================
7085 * \brief Returns size and direction of the last segment
7087 //================================================================================
7089 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7091 // find two non-coincident positions
7092 gp_XYZ orig = _pos.back();
7094 int iPrev = _pos.size() - 2;
7095 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7096 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7097 while ( iPrev >= 0 )
7099 vec = orig - _pos[iPrev];
7100 if ( vec.SquareModulus() > tol*tol )
7110 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7111 segDir.SetDirection( _normal );
7116 gp_Pnt pPrev = _pos[ iPrev ];
7117 if ( !eos._sWOL.IsNull() )
7119 TopLoc_Location loc;
7120 if ( eos.SWOLType() == TopAbs_EDGE )
7123 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7124 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7128 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7129 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7131 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7133 segDir.SetLocation( pPrev );
7134 segDir.SetDirection( vec );
7135 segLen = vec.Modulus();
7141 //================================================================================
7143 * \brief Return the last position of the target node on a FACE.
7144 * \param [in] F - the FACE this _LayerEdge is inflated along
7145 * \return gp_XY - result UV
7147 //================================================================================
7149 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7151 if ( F.IsSame( eos._sWOL )) // F is my FACE
7152 return gp_XY( _pos.back().X(), _pos.back().Y() );
7154 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7155 return gp_XY( 1e100, 1e100 );
7157 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7158 double f, l, u = _pos.back().X();
7159 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7160 if ( !C2d.IsNull() && f <= u && u <= l )
7161 return C2d->Value( u ).XY();
7163 return gp_XY( 1e100, 1e100 );
7166 //================================================================================
7168 * \brief Test intersection of the last segment with a given triangle
7169 * using Moller-Trumbore algorithm
7170 * Intersection is detected if distance to intersection is less than _LayerEdge._len
7172 //================================================================================
7174 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7175 const gp_XYZ& vert0,
7176 const gp_XYZ& vert1,
7177 const gp_XYZ& vert2,
7179 const double& EPSILON) const
7181 const gp_Pnt& orig = lastSegment.Location();
7182 const gp_Dir& dir = lastSegment.Direction();
7184 /* calculate distance from vert0 to ray origin */
7185 gp_XYZ tvec = orig.XYZ() - vert0;
7187 //if ( tvec * dir > EPSILON )
7188 // intersected face is at back side of the temporary face this _LayerEdge belongs to
7191 gp_XYZ edge1 = vert1 - vert0;
7192 gp_XYZ edge2 = vert2 - vert0;
7194 /* begin calculating determinant - also used to calculate U parameter */
7195 gp_XYZ pvec = dir.XYZ() ^ edge2;
7197 /* if determinant is near zero, ray lies in plane of triangle */
7198 double det = edge1 * pvec;
7200 const double ANGL_EPSILON = 1e-12;
7201 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7204 /* calculate U parameter and test bounds */
7205 double u = ( tvec * pvec ) / det;
7206 //if (u < 0.0 || u > 1.0)
7207 if ( u < -EPSILON || u > 1.0 + EPSILON )
7210 /* prepare to test V parameter */
7211 gp_XYZ qvec = tvec ^ edge1;
7213 /* calculate V parameter and test bounds */
7214 double v = (dir.XYZ() * qvec) / det;
7215 //if ( v < 0.0 || u + v > 1.0 )
7216 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7219 /* calculate t, ray intersects triangle */
7220 t = (edge2 * qvec) / det;
7226 //================================================================================
7228 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7229 * neighbor _LayerEdge's by it's own inflation vector.
7230 * \param [in] eov - EOS of the VERTEX
7231 * \param [in] eos - EOS of the FACE
7232 * \param [in] step - inflation step
7233 * \param [in,out] badSmooEdges - not untangled _LayerEdge's
7235 //================================================================================
7237 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
7238 const _EdgesOnShape* eos,
7240 vector< _LayerEdge* > & badSmooEdges )
7242 // check if any of _neibors is in badSmooEdges
7243 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7244 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7247 // get all edges to move
7249 set< _LayerEdge* > edges;
7251 // find a distance between _LayerEdge on VERTEX and its neighbors
7252 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
7254 for ( size_t i = 0; i < _neibors.size(); ++i )
7256 _LayerEdge* nEdge = _neibors[i];
7257 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7259 edges.insert( nEdge );
7260 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7263 // add _LayerEdge's close to curPosV
7267 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7269 _LayerEdge* edgeF = *e;
7270 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7272 _LayerEdge* nEdge = edgeF->_neibors[i];
7273 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7274 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7275 edges.insert( nEdge );
7279 while ( nbE < edges.size() );
7281 // move the target node of the got edges
7283 gp_XYZ prevPosV = PrevPos();
7284 if ( eov->SWOLType() == TopAbs_EDGE )
7286 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7287 prevPosV = curve.Value( prevPosV.X() ).XYZ();
7289 else if ( eov->SWOLType() == TopAbs_FACE )
7291 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7292 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7295 SMDS_FacePosition* fPos;
7296 //double r = 1. - Min( 0.9, step / 10. );
7297 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7299 _LayerEdge* edgeF = *e;
7300 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
7301 const gp_XYZ newPosF = curPosV + prevVF;
7302 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7303 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7304 edgeF->_pos.back() = newPosF;
7305 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7307 // set _curvature to make edgeF updated by putOnOffsetSurface()
7308 if ( !edgeF->_curvature )
7309 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7311 edgeF->_curvature = new _Curvature;
7312 edgeF->_curvature->_r = 0;
7313 edgeF->_curvature->_k = 0;
7314 edgeF->_curvature->_h2lenRatio = 0;
7315 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7318 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7319 // SMESH_TNodeXYZ( _nodes[0] ));
7320 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7322 // _LayerEdge* edgeF = *e;
7323 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7324 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7325 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7326 // edgeF->_pos.back() = newPosF;
7327 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7330 // smooth _LayerEdge's around moved nodes
7331 //size_t nbBadBefore = badSmooEdges.size();
7332 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7334 _LayerEdge* edgeF = *e;
7335 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7336 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7337 //&& !edges.count( edgeF->_neibors[j] ))
7339 _LayerEdge* edgeFN = edgeF->_neibors[j];
7340 edgeFN->Unset( SMOOTHED );
7341 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7344 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7345 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7346 // int nbBadAfter = edgeFN->_simplices.size();
7348 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7350 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7352 // if ( nbBadAfter <= nbBad )
7354 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7355 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7356 // edgeF->_pos.back() = newPosF;
7357 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7358 // nbBad = nbBadAfter;
7362 badSmooEdges.push_back( edgeFN );
7365 // move a bit not smoothed around moved nodes
7366 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7368 // _LayerEdge* edgeF = badSmooEdges[i];
7369 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7370 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7371 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7372 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7373 // edgeF->_pos.back() = newPosF;
7374 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7378 //================================================================================
7380 * \brief Perform smooth of _LayerEdge's based on EDGE's
7381 * \retval bool - true if node has been moved
7383 //================================================================================
7385 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7386 const TopoDS_Face& F,
7387 SMESH_MesherHelper& helper)
7389 ASSERT( IsOnEdge() );
7391 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7392 SMESH_TNodeXYZ oldPos( tgtNode );
7393 double dist01, distNewOld;
7395 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7396 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7397 dist01 = p0.Distance( _2neibors->tgtNode(1) );
7399 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7400 double lenDelta = 0;
7403 //lenDelta = _curvature->lenDelta( _len );
7404 lenDelta = _curvature->lenDeltaByDist( dist01 );
7405 newPos.ChangeCoord() += _normal * lenDelta;
7408 distNewOld = newPos.Distance( oldPos );
7412 if ( _2neibors->_plnNorm )
7414 // put newPos on the plane defined by source node and _plnNorm
7415 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7416 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7417 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7419 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7420 _pos.back() = newPos.XYZ();
7424 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7425 gp_XY uv( Precision::Infinite(), 0 );
7426 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7427 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7429 newPos = surface->Value( uv );
7430 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7433 // commented for IPAL0052478
7434 // if ( _curvature && lenDelta < 0 )
7436 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7437 // _len -= prevPos.Distance( oldPos );
7438 // _len += prevPos.Distance( newPos );
7440 bool moved = distNewOld > dist01/50;
7442 dumpMove( tgtNode ); // debug
7447 //================================================================================
7449 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7451 //================================================================================
7453 void _LayerEdge::SmoothWoCheck()
7455 if ( Is( DIFFICULT ))
7458 bool moved = Is( SMOOTHED );
7459 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
7460 moved = _neibors[i]->Is( SMOOTHED );
7464 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7466 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7467 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7468 _pos.back() = newPos;
7470 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7473 //================================================================================
7475 * \brief Checks validity of _neibors on EDGEs and VERTEXes
7477 //================================================================================
7479 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7481 if ( ! Is( NEAR_BOUNDARY ))
7486 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7488 _LayerEdge* eN = _neibors[iN];
7489 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7492 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) || eN->Is( _LayerEdge::NORMAL_UPDATED ));
7494 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7495 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7496 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7497 if ( eN->_nodes.size() > 1 &&
7498 eN->_simplices[i].Includes( _nodes.back() ) &&
7499 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7504 badNeibors->push_back( eN );
7505 debugMsg("Bad boundary simplex ( "
7506 << " "<< eN->_nodes[0]->GetID()
7507 << " "<< eN->_nodes.back()->GetID()
7508 << " "<< eN->_simplices[i]._nPrev->GetID()
7509 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7520 //================================================================================
7522 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7523 * \retval int - nb of bad simplices around this _LayerEdge
7525 //================================================================================
7527 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7529 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7530 return 0; // shape of simplices not changed
7531 if ( _simplices.size() < 2 )
7532 return 0; // _LayerEdge inflated along EDGE or FACE
7534 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7537 const gp_XYZ& curPos = _pos.back();
7538 const gp_XYZ& prevPos = PrevCheckPos();
7540 // quality metrics (orientation) of tetras around _tgtNode
7542 double vol, minVolBefore = 1e100;
7543 for ( size_t i = 0; i < _simplices.size(); ++i )
7545 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7546 minVolBefore = Min( minVolBefore, vol );
7548 int nbBad = _simplices.size() - nbOkBefore;
7550 bool bndNeedSmooth = false;
7552 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7556 // evaluate min angle
7557 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7559 size_t nbGoodAngles = _simplices.size();
7561 for ( size_t i = 0; i < _simplices.size(); ++i )
7563 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7566 if ( nbGoodAngles == _simplices.size() )
7572 if ( Is( ON_CONCAVE_FACE ))
7575 if ( step % 2 == 0 )
7578 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7580 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7581 _smooFunction = _funs[ FUN_CENTROIDAL ];
7583 _smooFunction = _funs[ FUN_LAPLACIAN ];
7586 // compute new position for the last _pos using different _funs
7589 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7592 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7593 else if ( _funs[ iFun ] == _smooFunction )
7594 continue; // _smooFunction again
7595 else if ( step > 1 )
7596 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7598 break; // let "easy" functions improve elements around distorted ones
7602 double delta = _curvature->lenDelta( _len );
7604 newPos += _normal * delta;
7607 double segLen = _normal * ( newPos - prevPos );
7608 if ( segLen + delta > 0 )
7609 newPos += _normal * delta;
7611 // double segLenChange = _normal * ( curPos - newPos );
7612 // newPos += 0.5 * _normal * segLenChange;
7616 double minVolAfter = 1e100;
7617 for ( size_t i = 0; i < _simplices.size(); ++i )
7619 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7620 minVolAfter = Min( minVolAfter, vol );
7623 if ( nbOkAfter < nbOkBefore )
7627 ( nbOkAfter == nbOkBefore ) &&
7628 ( minVolAfter <= minVolBefore ))
7631 nbBad = _simplices.size() - nbOkAfter;
7632 minVolBefore = minVolAfter;
7633 nbOkBefore = nbOkAfter;
7636 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7637 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7638 _pos.back() = newPos;
7640 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7641 << (nbBad ? " --BAD" : ""));
7645 continue; // look for a better function
7651 } // loop on smoothing functions
7653 if ( moved ) // notify _neibors
7656 for ( size_t i = 0; i < _neibors.size(); ++i )
7657 if ( !_neibors[i]->Is( MOVED ))
7659 _neibors[i]->Set( MOVED );
7660 toSmooth.push_back( _neibors[i] );
7667 //================================================================================
7669 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7670 * \retval int - nb of bad simplices around this _LayerEdge
7672 //================================================================================
7674 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
7676 if ( !_smooFunction )
7677 return 0; // _LayerEdge inflated along EDGE or FACE
7679 return 0; // not inflated
7681 const gp_XYZ& curPos = _pos.back();
7682 const gp_XYZ& prevPos = PrevCheckPos();
7684 // quality metrics (orientation) of tetras around _tgtNode
7686 double vol, minVolBefore = 1e100;
7687 for ( size_t i = 0; i < _simplices.size(); ++i )
7689 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7690 minVolBefore = Min( minVolBefore, vol );
7692 int nbBad = _simplices.size() - nbOkBefore;
7694 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7696 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
7697 _smooFunction = _funs[ FUN_LAPLACIAN ];
7698 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
7699 _smooFunction = _funs[ FUN_CENTROIDAL ];
7702 // compute new position for the last _pos using different _funs
7704 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7707 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7708 else if ( _funs[ iFun ] == _smooFunction )
7709 continue; // _smooFunction again
7710 else if ( step > 1 )
7711 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7713 break; // let "easy" functions improve elements around distorted ones
7717 double delta = _curvature->lenDelta( _len );
7719 newPos += _normal * delta;
7722 double segLen = _normal * ( newPos - prevPos );
7723 if ( segLen + delta > 0 )
7724 newPos += _normal * delta;
7726 // double segLenChange = _normal * ( curPos - newPos );
7727 // newPos += 0.5 * _normal * segLenChange;
7731 double minVolAfter = 1e100;
7732 for ( size_t i = 0; i < _simplices.size(); ++i )
7734 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7735 minVolAfter = Min( minVolAfter, vol );
7738 if ( nbOkAfter < nbOkBefore )
7740 if (( isConcaveFace || findBest ) &&
7741 ( nbOkAfter == nbOkBefore ) &&
7742 ( minVolAfter <= minVolBefore )
7746 nbBad = _simplices.size() - nbOkAfter;
7747 minVolBefore = minVolAfter;
7748 nbOkBefore = nbOkAfter;
7750 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7751 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7752 _pos.back() = newPos;
7754 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7755 << ( nbBad ? "--BAD" : ""));
7757 // commented for IPAL0052478
7758 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
7759 // _len += prevPos.Distance(newPos);
7761 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
7763 //_smooFunction = _funs[ iFun ];
7764 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
7765 // << "\t nbBad: " << _simplices.size() - nbOkAfter
7766 // << " minVol: " << minVolAfter
7767 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
7769 continue; // look for a better function
7775 } // loop on smoothing functions
7780 //================================================================================
7782 * \brief Chooses a smoothing technic giving a position most close to an initial one.
7783 * For a correct result, _simplices must contain nodes lying on geometry.
7785 //================================================================================
7787 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
7788 const TNode2Edge& n2eMap)
7790 if ( _smooFunction ) return;
7792 // use smoothNefPolygon() near concaveVertices
7793 if ( !concaveVertices.empty() )
7795 _smooFunction = _funs[ FUN_CENTROIDAL ];
7797 Set( ON_CONCAVE_FACE );
7799 for ( size_t i = 0; i < _simplices.size(); ++i )
7801 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
7803 _smooFunction = _funs[ FUN_NEFPOLY ];
7805 // set FUN_CENTROIDAL to neighbor edges
7806 for ( i = 0; i < _neibors.size(); ++i )
7808 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
7810 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
7817 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
7818 // // where the nodes are smoothed too far along a sphere thus creating
7819 // // inverted _simplices
7820 // double dist[theNbSmooFuns];
7821 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
7822 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
7824 // double minDist = Precision::Infinite();
7825 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
7826 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
7828 // gp_Pnt newP = (this->*_funs[i])();
7829 // dist[i] = p.SquareDistance( newP );
7830 // if ( dist[i]*coef[i] < minDist )
7832 // _smooFunction = _funs[i];
7833 // minDist = dist[i]*coef[i];
7839 _smooFunction = _funs[ FUN_LAPLACIAN ];
7842 // for ( size_t i = 0; i < _simplices.size(); ++i )
7843 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
7844 // if ( minDim == 0 )
7845 // _smooFunction = _funs[ FUN_CENTROIDAL ];
7846 // else if ( minDim == 1 )
7847 // _smooFunction = _funs[ FUN_CENTROIDAL ];
7851 // for ( int i = 0; i < FUN_NB; ++i )
7853 // //cout << dist[i] << " ";
7854 // if ( _smooFunction == _funs[i] ) {
7856 // //debugMsg( fNames[i] );
7860 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
7863 //================================================================================
7865 * \brief Returns a name of _SmooFunction
7867 //================================================================================
7869 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
7872 fun = _smooFunction;
7873 for ( int i = 0; i < theNbSmooFuns; ++i )
7874 if ( fun == _funs[i] )
7877 return theNbSmooFuns;
7880 //================================================================================
7882 * \brief Computes a new node position using Laplacian smoothing
7884 //================================================================================
7886 gp_XYZ _LayerEdge::smoothLaplacian()
7888 gp_XYZ newPos (0,0,0);
7889 for ( size_t i = 0; i < _simplices.size(); ++i )
7890 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
7891 newPos /= _simplices.size();
7896 //================================================================================
7898 * \brief Computes a new node position using angular-based smoothing
7900 //================================================================================
7902 gp_XYZ _LayerEdge::smoothAngular()
7904 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
7905 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
7906 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
7908 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
7910 for ( size_t i = 0; i < _simplices.size(); ++i )
7912 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
7913 edgeDir.push_back( p - pPrev );
7914 edgeSize.push_back( edgeDir.back().Magnitude() );
7915 if ( edgeSize.back() < numeric_limits<double>::min() )
7918 edgeSize.pop_back();
7922 edgeDir.back() /= edgeSize.back();
7923 points.push_back( p );
7928 edgeDir.push_back ( edgeDir[0] );
7929 edgeSize.push_back( edgeSize[0] );
7930 pN /= points.size();
7932 gp_XYZ newPos(0,0,0);
7934 for ( size_t i = 0; i < points.size(); ++i )
7936 gp_Vec toN = pN - points[i];
7937 double toNLen = toN.Magnitude();
7938 if ( toNLen < numeric_limits<double>::min() )
7943 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
7944 double bisecLen = bisec.SquareMagnitude();
7945 if ( bisecLen < numeric_limits<double>::min() )
7947 gp_Vec norm = edgeDir[i] ^ toN;
7948 bisec = norm ^ edgeDir[i];
7949 bisecLen = bisec.SquareMagnitude();
7951 bisecLen = Sqrt( bisecLen );
7955 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
7956 sumSize += bisecLen;
7958 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
7959 sumSize += ( edgeSize[i] + edgeSize[i+1] );
7965 // project newPos to an average plane
7967 gp_XYZ norm(0,0,0); // plane normal
7968 points.push_back( points[0] );
7969 for ( size_t i = 1; i < points.size(); ++i )
7971 gp_XYZ vec1 = points[ i-1 ] - pN;
7972 gp_XYZ vec2 = points[ i ] - pN;
7973 gp_XYZ cross = vec1 ^ vec2;
7976 if ( cross * norm < numeric_limits<double>::min() )
7977 norm += cross.Reversed();
7981 catch (Standard_Failure) { // if |cross| == 0.
7984 gp_XYZ vec = newPos - pN;
7985 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
7986 newPos = newPos - r * norm;
7991 //================================================================================
7993 * \brief Computes a new node position using weigthed node positions
7995 //================================================================================
7997 gp_XYZ _LayerEdge::smoothLengthWeighted()
7999 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8000 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8002 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8003 for ( size_t i = 0; i < _simplices.size(); ++i )
8005 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8006 edgeSize.push_back( ( p - pPrev ).Modulus() );
8007 if ( edgeSize.back() < numeric_limits<double>::min() )
8009 edgeSize.pop_back();
8013 points.push_back( p );
8017 edgeSize.push_back( edgeSize[0] );
8019 gp_XYZ newPos(0,0,0);
8021 for ( size_t i = 0; i < points.size(); ++i )
8023 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8024 sumSize += edgeSize[i] + edgeSize[i+1];
8030 //================================================================================
8032 * \brief Computes a new node position using angular-based smoothing
8034 //================================================================================
8036 gp_XYZ _LayerEdge::smoothCentroidal()
8038 gp_XYZ newPos(0,0,0);
8039 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8041 for ( size_t i = 0; i < _simplices.size(); ++i )
8043 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8044 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8045 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8046 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8049 newPos += gc * size;
8056 //================================================================================
8058 * \brief Computes a new node position located inside a Nef polygon
8060 //================================================================================
8062 gp_XYZ _LayerEdge::smoothNefPolygon()
8063 #ifdef OLD_NEF_POLYGON
8065 gp_XYZ newPos(0,0,0);
8067 // get a plane to seach a solution on
8069 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8071 const double tol = numeric_limits<double>::min();
8072 gp_XYZ center(0,0,0);
8073 for ( i = 0; i < _simplices.size(); ++i )
8075 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8076 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8077 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8079 vecs.back() = vecs[0];
8080 center /= _simplices.size();
8082 gp_XYZ zAxis(0,0,0);
8083 for ( i = 0; i < _simplices.size(); ++i )
8084 zAxis += vecs[i] ^ vecs[i+1];
8087 for ( i = 0; i < _simplices.size(); ++i )
8090 if ( yAxis.SquareModulus() > tol )
8093 gp_XYZ xAxis = yAxis ^ zAxis;
8094 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8095 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8096 // p0.Distance( _simplices[2]._nPrev ));
8097 // gp_XYZ center = smoothLaplacian();
8098 // gp_XYZ xAxis, yAxis, zAxis;
8099 // for ( i = 0; i < _simplices.size(); ++i )
8101 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8102 // if ( xAxis.SquareModulus() > tol*tol )
8105 // for ( i = 1; i < _simplices.size(); ++i )
8107 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8108 // zAxis = xAxis ^ yAxis;
8109 // if ( zAxis.SquareModulus() > tol*tol )
8112 // if ( i == _simplices.size() ) return newPos;
8114 yAxis = zAxis ^ xAxis;
8115 xAxis /= xAxis.Modulus();
8116 yAxis /= yAxis.Modulus();
8118 // get half-planes of _simplices
8120 vector< _halfPlane > halfPlns( _simplices.size() );
8122 for ( size_t i = 0; i < _simplices.size(); ++i )
8124 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8125 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8126 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8127 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8128 gp_XY vec12 = p2 - p1;
8129 double dist12 = vec12.Modulus();
8133 halfPlns[ nbHP ]._pos = p1;
8134 halfPlns[ nbHP ]._dir = vec12;
8135 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8139 // intersect boundaries of half-planes, define state of intersection points
8140 // in relation to all half-planes and calculate internal point of a 2D polygon
8143 gp_XY newPos2D (0,0);
8145 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8146 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8147 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8149 vector< vector< TIntPntState > > allIntPnts( nbHP );
8150 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8152 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8153 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8155 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8156 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8159 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8161 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8163 if ( iHP1 == iHP2 ) continue;
8165 TIntPntState & ips1 = intPnts1[ iHP2 ];
8166 if ( ips1.second == UNDEF )
8168 // find an intersection point of boundaries of iHP1 and iHP2
8170 if ( iHP2 == iPrev ) // intersection with neighbors is known
8171 ips1.first = halfPlns[ iHP1 ]._pos;
8172 else if ( iHP2 == iNext )
8173 ips1.first = halfPlns[ iHP2 ]._pos;
8174 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8175 ips1.second = NO_INT;
8177 // classify the found intersection point
8178 if ( ips1.second != NO_INT )
8180 ips1.second = NOT_OUT;
8181 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8182 if ( i != iHP1 && i != iHP2 &&
8183 halfPlns[ i ].IsOut( ips1.first, tol ))
8184 ips1.second = IS_OUT;
8186 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8187 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8188 TIntPntState & ips2 = intPnts2[ iHP1 ];
8191 if ( ips1.second == NOT_OUT )
8194 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8198 // find a NOT_OUT segment of boundary which is located between
8199 // two NOT_OUT int points
8202 continue; // no such a segment
8206 // sort points along the boundary
8207 map< double, TIntPntState* > ipsByParam;
8208 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8210 TIntPntState & ips1 = intPnts1[ iHP2 ];
8211 if ( ips1.second != NO_INT )
8213 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8214 double param = op * halfPlns[ iHP1 ]._dir;
8215 ipsByParam.insert( make_pair( param, & ips1 ));
8218 // look for two neighboring NOT_OUT points
8220 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8221 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8223 TIntPntState & ips1 = *(u2ips->second);
8224 if ( ips1.second == NOT_OUT )
8225 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8226 else if ( nbNotOut >= 2 )
8233 if ( nbNotOut >= 2 )
8235 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8238 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8245 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8254 #else // OLD_NEF_POLYGON
8255 { ////////////////////////////////// NEW
8256 gp_XYZ newPos(0,0,0);
8258 // get a plane to seach a solution on
8261 gp_XYZ center(0,0,0);
8262 for ( i = 0; i < _simplices.size(); ++i )
8263 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8264 center /= _simplices.size();
8266 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8267 for ( i = 0; i < _simplices.size(); ++i )
8268 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8269 vecs.back() = vecs[0];
8271 const double tol = numeric_limits<double>::min();
8272 gp_XYZ zAxis(0,0,0);
8273 for ( i = 0; i < _simplices.size(); ++i )
8275 gp_XYZ cross = vecs[i] ^ vecs[i+1];
8278 if ( cross * zAxis < tol )
8279 zAxis += cross.Reversed();
8283 catch (Standard_Failure) { // if |cross| == 0.
8288 for ( i = 0; i < _simplices.size(); ++i )
8291 if ( yAxis.SquareModulus() > tol )
8294 gp_XYZ xAxis = yAxis ^ zAxis;
8295 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8296 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8297 // p0.Distance( _simplices[2]._nPrev ));
8298 // gp_XYZ center = smoothLaplacian();
8299 // gp_XYZ xAxis, yAxis, zAxis;
8300 // for ( i = 0; i < _simplices.size(); ++i )
8302 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8303 // if ( xAxis.SquareModulus() > tol*tol )
8306 // for ( i = 1; i < _simplices.size(); ++i )
8308 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8309 // zAxis = xAxis ^ yAxis;
8310 // if ( zAxis.SquareModulus() > tol*tol )
8313 // if ( i == _simplices.size() ) return newPos;
8315 yAxis = zAxis ^ xAxis;
8316 xAxis /= xAxis.Modulus();
8317 yAxis /= yAxis.Modulus();
8319 // get half-planes of _simplices
8321 vector< _halfPlane > halfPlns( _simplices.size() );
8323 for ( size_t i = 0; i < _simplices.size(); ++i )
8325 const gp_XYZ& OP1 = vecs[ i ];
8326 const gp_XYZ& OP2 = vecs[ i+1 ];
8327 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8328 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8329 gp_XY vec12 = p2 - p1;
8330 double dist12 = vec12.Modulus();
8334 halfPlns[ nbHP ]._pos = p1;
8335 halfPlns[ nbHP ]._dir = vec12;
8336 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8340 // intersect boundaries of half-planes, define state of intersection points
8341 // in relation to all half-planes and calculate internal point of a 2D polygon
8344 gp_XY newPos2D (0,0);
8346 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8347 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8348 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8350 vector< vector< TIntPntState > > allIntPnts( nbHP );
8351 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8353 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8354 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8356 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8357 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8360 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8362 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8364 if ( iHP1 == iHP2 ) continue;
8366 TIntPntState & ips1 = intPnts1[ iHP2 ];
8367 if ( ips1.second == UNDEF )
8369 // find an intersection point of boundaries of iHP1 and iHP2
8371 if ( iHP2 == iPrev ) // intersection with neighbors is known
8372 ips1.first = halfPlns[ iHP1 ]._pos;
8373 else if ( iHP2 == iNext )
8374 ips1.first = halfPlns[ iHP2 ]._pos;
8375 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8376 ips1.second = NO_INT;
8378 // classify the found intersection point
8379 if ( ips1.second != NO_INT )
8381 ips1.second = NOT_OUT;
8382 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8383 if ( i != iHP1 && i != iHP2 &&
8384 halfPlns[ i ].IsOut( ips1.first, tol ))
8385 ips1.second = IS_OUT;
8387 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8388 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8389 TIntPntState & ips2 = intPnts2[ iHP1 ];
8392 if ( ips1.second == NOT_OUT )
8395 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8399 // find a NOT_OUT segment of boundary which is located between
8400 // two NOT_OUT int points
8403 continue; // no such a segment
8407 // sort points along the boundary
8408 map< double, TIntPntState* > ipsByParam;
8409 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8411 TIntPntState & ips1 = intPnts1[ iHP2 ];
8412 if ( ips1.second != NO_INT )
8414 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8415 double param = op * halfPlns[ iHP1 ]._dir;
8416 ipsByParam.insert( make_pair( param, & ips1 ));
8419 // look for two neighboring NOT_OUT points
8421 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8422 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8424 TIntPntState & ips1 = *(u2ips->second);
8425 if ( ips1.second == NOT_OUT )
8426 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8427 else if ( nbNotOut >= 2 )
8434 if ( nbNotOut >= 2 )
8436 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8439 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8446 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8455 #endif // OLD_NEF_POLYGON
8457 //================================================================================
8459 * \brief Add a new segment to _LayerEdge during inflation
8461 //================================================================================
8463 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8468 if ( len > _maxLen )
8471 Block( eos.GetData() );
8473 const double lenDelta = len - _len;
8474 if ( lenDelta < len * 1e-3 )
8476 Block( eos.GetData() );
8480 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8481 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8483 if ( eos._hyp.IsOffsetMethod() )
8487 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8488 while ( faceIt->more() )
8490 const SMDS_MeshElement* face = faceIt->next();
8491 if ( !eos.GetNormal( face, faceNorm ))
8494 // translate plane of a face
8495 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8497 // find point of intersection of the face plane located at baryCenter
8498 // and _normal located at newXYZ
8499 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8500 double dot = ( faceNorm.XYZ() * _normal );
8501 if ( dot < std::numeric_limits<double>::min() )
8502 dot = lenDelta * 1e-3;
8503 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8504 newXYZ += step * _normal;
8509 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8512 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8513 _pos.push_back( newXYZ );
8515 if ( !eos._sWOL.IsNull() )
8519 if ( eos.SWOLType() == TopAbs_EDGE )
8521 double u = Precision::Infinite(); // to force projection w/o distance check
8522 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8523 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8524 _pos.back().SetCoord( u, 0, 0 );
8525 if ( _nodes.size() > 1 && uvOK )
8527 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8528 pos->SetUParameter( u );
8533 gp_XY uv( Precision::Infinite(), 0 );
8534 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8535 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8536 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8537 if ( _nodes.size() > 1 && uvOK )
8539 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8540 pos->SetUParameter( uv.X() );
8541 pos->SetVParameter( uv.Y() );
8546 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8550 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8552 Block( eos.GetData() );
8560 if ( eos.ShapeType() != TopAbs_FACE )
8562 for ( size_t i = 0; i < _neibors.size(); ++i )
8563 //if ( _len > _neibors[i]->GetSmooLen() )
8564 _neibors[i]->Set( MOVED );
8568 dumpMove( n ); //debug
8571 //================================================================================
8573 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8575 //================================================================================
8577 void _LayerEdge::Block( _SolidData& data )
8579 if ( Is( BLOCKED )) return;
8583 std::queue<_LayerEdge*> queue;
8586 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8587 while ( !queue.empty() )
8589 _LayerEdge* edge = queue.front(); queue.pop();
8590 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8591 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8592 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8594 _LayerEdge* neibor = edge->_neibors[iN];
8595 if ( neibor->Is( BLOCKED ) ||
8596 neibor->_maxLen < edge->_maxLen )
8598 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8599 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8600 double minDist = pSrc.SquareDistance( pSrcN );
8601 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
8602 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
8603 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
8604 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8605 if ( neibor->_maxLen > newMaxLen )
8607 neibor->_maxLen = newMaxLen;
8608 if ( neibor->_maxLen < neibor->_len )
8610 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8611 while ( neibor->_len > neibor->_maxLen &&
8612 neibor->NbSteps() > 1 )
8613 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8614 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8616 queue.push( neibor );
8622 //================================================================================
8624 * \brief Remove last inflation step
8626 //================================================================================
8628 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
8630 if ( _pos.size() > curStep && _nodes.size() > 1 )
8632 _pos.resize( curStep );
8634 gp_Pnt nXYZ = _pos.back();
8635 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8636 SMESH_TNodeXYZ curXYZ( n );
8637 if ( !eos._sWOL.IsNull() )
8639 TopLoc_Location loc;
8640 if ( eos.SWOLType() == TopAbs_EDGE )
8642 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8643 pos->SetUParameter( nXYZ.X() );
8645 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8646 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
8650 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8651 pos->SetUParameter( nXYZ.X() );
8652 pos->SetVParameter( nXYZ.Y() );
8653 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
8654 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
8657 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
8660 if ( restoreLength )
8662 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
8667 //================================================================================
8669 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
8671 //================================================================================
8673 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
8676 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
8679 // find the 1st smoothed _pos
8681 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
8683 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
8684 if ( normDist > tol * tol )
8687 if ( !iSmoothed ) return;
8689 if ( 1 || Is( DISTORTED ))
8691 // if ( segLen[ iSmoothed ] / segLen.back() < 0.5 )
8693 gp_XYZ normal = _normal;
8694 if ( Is( NORMAL_UPDATED ))
8695 for ( size_t i = 1; i < _pos.size(); ++i )
8697 normal = _pos[i] - _pos[0];
8698 double size = normal.Modulus();
8699 if ( size > RealSmall() )
8705 const double r = 0.2;
8706 for ( int iter = 0; iter < 3; ++iter )
8709 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
8711 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
8712 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
8714 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
8715 double newLen = ( 1-r ) * midLen + r * segLen[i];
8716 const_cast< double& >( segLen[i] ) = newLen;
8717 // check angle between normal and (_pos[i+1], _pos[i] )
8718 gp_XYZ posDir = _pos[i+1] - _pos[i];
8719 double size = posDir.Modulus();
8720 if ( size > RealSmall() )
8721 minDot = Min( minDot, ( normal * posDir ) / size );
8729 // for ( size_t i = 1; i < _pos.size()-1; ++i )
8731 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
8734 // double wgt = segLen[i] / segLen.back();
8735 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
8736 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
8737 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
8738 // _pos[i] = newPos;
8743 //================================================================================
8745 * \brief Create layers of prisms
8747 //================================================================================
8749 bool _ViscousBuilder::refine(_SolidData& data)
8751 SMESH_MesherHelper& helper = data.GetHelper();
8752 helper.SetElementsOnShape(false);
8754 Handle(Geom_Curve) curve;
8755 Handle(ShapeAnalysis_Surface) surface;
8756 TopoDS_Edge geomEdge;
8757 TopoDS_Face geomFace;
8758 TopLoc_Location loc;
8761 vector< gp_XYZ > pos3D;
8763 TGeomID prevBaseId = -1;
8764 TNode2Edge* n2eMap = 0;
8765 TNode2Edge::iterator n2e;
8767 // Create intermediate nodes on each _LayerEdge
8769 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
8771 _EdgesOnShape& eos = data._edgesOnShape[iS];
8772 if ( eos._edges.empty() ) continue;
8774 if ( eos._edges[0]->_nodes.size() < 2 )
8775 continue; // on _noShrinkShapes
8777 // get data of a shrink shape
8779 geomEdge.Nullify(); geomFace.Nullify();
8780 curve.Nullify(); surface.Nullify();
8781 if ( !eos._sWOL.IsNull() )
8783 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
8786 geomEdge = TopoDS::Edge( eos._sWOL );
8787 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
8791 geomFace = TopoDS::Face( eos._sWOL );
8792 surface = helper.GetSurface( geomFace );
8795 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
8797 geomFace = TopoDS::Face( eos._shape );
8798 surface = helper.GetSurface( geomFace );
8799 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
8800 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
8802 eos._eosC1[ i ]->_toSmooth = true;
8803 for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
8804 eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
8808 vector< double > segLen;
8809 for ( size_t i = 0; i < eos._edges.size(); ++i )
8811 _LayerEdge& edge = *eos._edges[i];
8812 if ( edge._pos.size() < 2 )
8815 // get accumulated length of segments
8816 segLen.resize( edge._pos.size() );
8818 if ( eos._sWOL.IsNull() )
8820 bool useNormal = true;
8821 bool usePos = false;
8822 bool smoothed = false;
8823 const double preci = 0.1 * edge._len;
8824 if ( eos._toSmooth )
8826 gp_Pnt tgtExpected = edge._pos[0] + edge._normal * edge._len;
8827 smoothed = tgtExpected.SquareDistance( edge._pos.back() ) > preci * preci;
8831 if ( !surface.IsNull() &&
8832 !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
8834 useNormal = usePos = false;
8835 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
8836 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
8838 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
8839 if ( surface->Gap() < 2. * edge._len )
8840 segLen[j] = surface->Gap();
8848 useNormal = usePos = false;
8849 edge._pos[1] = edge._pos.back();
8850 edge._pos.resize( 2 );
8852 segLen[ 1 ] = edge._len;
8854 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
8856 useNormal = usePos = false;
8857 _LayerEdge tmpEdge; // get original _normal
8858 tmpEdge._nodes.push_back( edge._nodes[0] );
8859 if ( !setEdgeData( tmpEdge, eos, helper, data ))
8862 for ( size_t j = 1; j < edge._pos.size(); ++j )
8863 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
8867 for ( size_t j = 1; j < edge._pos.size(); ++j )
8868 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
8872 for ( size_t j = 1; j < edge._pos.size(); ++j )
8873 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
8877 bool swapped = ( edge._pos.size() > 2 );
8881 for ( size_t j = 1; j < edge._pos.size(); ++j )
8882 if ( segLen[j] > segLen.back() )
8884 segLen.erase( segLen.begin() + j );
8885 edge._pos.erase( edge._pos.begin() + j );
8887 else if ( segLen[j] < segLen[j-1] )
8889 std::swap( segLen[j], segLen[j-1] );
8890 std::swap( edge._pos[j], edge._pos[j-1] );
8895 // smooth a path formed by edge._pos
8896 if (( smoothed ) /*&&
8897 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
8898 edge.SmoothPos( segLen, preci );
8900 else if ( eos._isRegularSWOL ) // usual SWOL
8902 for ( size_t j = 1; j < edge._pos.size(); ++j )
8903 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
8905 else if ( !surface.IsNull() ) // SWOL surface with singularities
8907 pos3D.resize( edge._pos.size() );
8908 for ( size_t j = 0; j < edge._pos.size(); ++j )
8909 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
8911 for ( size_t j = 1; j < edge._pos.size(); ++j )
8912 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
8915 // allocate memory for new nodes if it is not yet refined
8916 const SMDS_MeshNode* tgtNode = edge._nodes.back();
8917 if ( edge._nodes.size() == 2 )
8919 edge._nodes.resize( eos._hyp.GetNumberLayers() + 1, 0 );
8921 edge._nodes.back() = tgtNode;
8923 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
8924 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
8925 if ( baseShapeId != prevBaseId )
8927 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
8928 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
8929 prevBaseId = baseShapeId;
8931 _LayerEdge* edgeOnSameNode = 0;
8932 bool useExistingPos = false;
8933 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
8935 edgeOnSameNode = n2e->second;
8936 useExistingPos = ( edgeOnSameNode->_len < edge._len );
8937 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
8938 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
8941 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
8942 epos->SetUParameter( otherTgtPos.X() );
8946 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
8947 fpos->SetUParameter( otherTgtPos.X() );
8948 fpos->SetVParameter( otherTgtPos.Y() );
8951 // calculate height of the first layer
8953 const double T = segLen.back(); //data._hyp.GetTotalThickness();
8954 const double f = eos._hyp.GetStretchFactor();
8955 const int N = eos._hyp.GetNumberLayers();
8956 const double fPowN = pow( f, N );
8957 if ( fPowN - 1 <= numeric_limits<double>::min() )
8960 h0 = T * ( f - 1 )/( fPowN - 1 );
8962 const double zeroLen = std::numeric_limits<double>::min();
8964 // create intermediate nodes
8965 double hSum = 0, hi = h0/f;
8967 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
8969 // compute an intermediate position
8972 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
8974 int iPrevSeg = iSeg-1;
8975 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
8977 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
8978 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
8980 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
8981 if ( !eos._sWOL.IsNull() )
8983 // compute XYZ by parameters <pos>
8988 pos = curve->Value( u ).Transformed(loc);
8990 else if ( eos._isRegularSWOL )
8992 uv.SetCoord( pos.X(), pos.Y() );
8994 pos = surface->Value( pos.X(), pos.Y() );
8998 uv.SetCoord( pos.X(), pos.Y() );
8999 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9000 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9002 pos = surface->Value( uv );
9005 // create or update the node
9008 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9009 if ( !eos._sWOL.IsNull() )
9012 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9014 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9018 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9023 if ( !eos._sWOL.IsNull() )
9025 // make average pos from new and current parameters
9028 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9029 if ( useExistingPos )
9030 u = helper.GetNodeU( geomEdge, node );
9031 pos = curve->Value( u ).Transformed(loc);
9033 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9034 epos->SetUParameter( u );
9038 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9039 if ( useExistingPos )
9040 uv = helper.GetNodeUV( geomFace, node );
9041 pos = surface->Value( uv );
9043 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9044 fpos->SetUParameter( uv.X() );
9045 fpos->SetVParameter( uv.Y() );
9048 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9050 } // loop on edge._nodes
9052 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9055 edge._pos.back().SetCoord( u, 0,0);
9057 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9059 if ( edgeOnSameNode )
9060 edgeOnSameNode->_pos.back() = edge._pos.back();
9063 } // loop on eos._edges to create nodes
9066 if ( !getMeshDS()->IsEmbeddedMode() )
9067 // Log node movement
9068 for ( size_t i = 0; i < eos._edges.size(); ++i )
9070 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9071 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9078 helper.SetElementsOnShape(true);
9080 vector< vector<const SMDS_MeshNode*>* > nnVec;
9081 set< vector<const SMDS_MeshNode*>* > nnSet;
9082 set< int > degenEdgeInd;
9083 vector<const SMDS_MeshElement*> degenVols;
9084 vector<int> isRiskySWOL;
9086 TopExp_Explorer exp( data._solid, TopAbs_FACE );
9087 for ( ; exp.More(); exp.Next() )
9089 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9090 if ( data._ignoreFaceIds.count( faceID ))
9092 const bool isReversedFace = data._reversedFaceIds.count( faceID );
9093 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
9094 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
9095 while ( fIt->more() )
9097 const SMDS_MeshElement* face = fIt->next();
9098 const int nbNodes = face->NbCornerNodes();
9099 nnVec.resize( nbNodes );
9101 degenEdgeInd.clear();
9102 isRiskySWOL.resize( nbNodes );
9103 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9104 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9105 for ( int iN = 0; iN < nbNodes; ++iN )
9107 const SMDS_MeshNode* n = nIt->next();
9108 _LayerEdge* edge = data._n2eMap[ n ];
9109 const int i = isReversedFace ? nbNodes-1-iN : iN;
9110 nnVec[ i ] = & edge->_nodes;
9111 maxZ = std::max( maxZ, nnVec[ i ]->size() );
9112 minZ = std::min( minZ, nnVec[ i ]->size() );
9113 //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9115 if ( helper.HasDegeneratedEdges() )
9116 nnSet.insert( nnVec[ i ]);
9121 if ( 0 < nnSet.size() && nnSet.size() < 3 )
9129 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9130 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9131 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
9133 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9135 for ( int iN = 0; iN < nbNodes; ++iN )
9136 if ( nnVec[ iN ]->size() < iZ+1 )
9137 degenEdgeInd.insert( iN );
9139 if ( degenEdgeInd.size() == 1 ) // PYRAM
9141 int i2 = *degenEdgeInd.begin();
9142 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9143 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9144 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9145 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
9149 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9150 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9151 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9152 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9153 (*nnVec[ i3 ])[ iZ ]);
9161 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9162 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9163 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9164 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
9165 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
9167 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9169 for ( int iN = 0; iN < nbNodes; ++iN )
9170 if ( nnVec[ iN ]->size() < iZ+1 )
9171 degenEdgeInd.insert( iN );
9173 switch ( degenEdgeInd.size() )
9177 int i2 = *degenEdgeInd.begin();
9178 int i3 = *degenEdgeInd.rbegin();
9179 bool ok = ( i3 - i2 == 1 );
9180 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9181 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9182 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9184 const SMDS_MeshElement* vol =
9185 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9186 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9188 degenVols.push_back( vol );
9192 default: // degen HEX
9194 const SMDS_MeshElement* vol =
9195 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9196 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9197 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9198 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9199 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
9200 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
9201 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
9202 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
9203 degenVols.push_back( vol );
9210 return error("Not supported type of element", data._index);
9212 } // switch ( nbNodes )
9213 } // while ( fIt->more() )
9216 if ( !degenVols.empty() )
9218 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9219 if ( !err || err->IsOK() )
9221 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9222 "Degenerated volumes created" ));
9223 err->myBadElements.insert( err->myBadElements.end(),
9224 degenVols.begin(),degenVols.end() );
9231 //================================================================================
9233 * \brief Shrink 2D mesh on faces to let space for inflated layers
9235 //================================================================================
9237 bool _ViscousBuilder::shrink()
9239 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9240 // inflated along FACE or EDGE)
9241 map< TGeomID, _SolidData* > f2sdMap;
9242 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9244 _SolidData& data = _sdVec[i];
9245 TopTools_MapOfShape FFMap;
9246 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9247 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9248 if ( s2s->second.ShapeType() == TopAbs_FACE )
9250 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9252 if ( FFMap.Add( (*s2s).second ))
9253 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9254 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9255 // by StdMeshers_QuadToTriaAdaptor
9256 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9258 SMESH_ProxyMesh::SubMesh* proxySub =
9259 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9260 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9261 while ( fIt->more() )
9262 proxySub->AddElement( fIt->next() );
9263 // as a result 3D algo will use elements from proxySub and not from smDS
9268 SMESH_MesherHelper helper( *_mesh );
9269 helper.ToFixNodeParameters( true );
9272 map< TGeomID, _Shrinker1D > e2shrMap;
9273 vector< _EdgesOnShape* > subEOS;
9274 vector< _LayerEdge* > lEdges;
9276 // loop on FACES to srink mesh on
9277 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9278 for ( ; f2sd != f2sdMap.end(); ++f2sd )
9280 _SolidData& data = *f2sd->second;
9281 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9282 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
9283 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9285 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9287 helper.SetSubShape(F);
9289 // ===========================
9290 // Prepare data for shrinking
9291 // ===========================
9293 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9294 // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9295 vector < const SMDS_MeshNode* > smoothNodes;
9297 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9298 while ( nIt->more() )
9300 const SMDS_MeshNode* n = nIt->next();
9301 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9302 smoothNodes.push_back( n );
9305 // Find out face orientation
9307 const set<TGeomID> ignoreShapes;
9309 if ( !smoothNodes.empty() )
9311 vector<_Simplex> simplices;
9312 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9313 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9314 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9315 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9316 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9320 // Find _LayerEdge's inflated along F
9324 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9325 /*complexFirst=*/true); //!!!
9326 while ( subIt->more() )
9328 const TGeomID subID = subIt->next()->GetId();
9329 if ( data._noShrinkShapes.count( subID ))
9331 _EdgesOnShape* eos = data.GetShapeEdges( subID );
9332 if ( !eos || eos->_sWOL.IsNull() ) continue;
9334 subEOS.push_back( eos );
9336 for ( size_t i = 0; i < eos->_edges.size(); ++i )
9338 lEdges.push_back( eos->_edges[ i ] );
9339 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9344 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9345 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9346 while ( fIt->more() )
9347 if ( const SMDS_MeshElement* f = fIt->next() )
9348 dumpChangeNodes( f );
9351 // Replace source nodes by target nodes in mesh faces to shrink
9352 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9353 const SMDS_MeshNode* nodes[20];
9354 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9356 _EdgesOnShape& eos = * subEOS[ iS ];
9357 for ( size_t i = 0; i < eos._edges.size(); ++i )
9359 _LayerEdge& edge = *eos._edges[i];
9360 const SMDS_MeshNode* srcNode = edge._nodes[0];
9361 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9362 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9363 while ( fIt->more() )
9365 const SMDS_MeshElement* f = fIt->next();
9366 if ( !smDS->Contains( f ))
9368 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9369 for ( int iN = 0; nIt->more(); ++iN )
9371 const SMDS_MeshNode* n = nIt->next();
9372 nodes[iN] = ( n == srcNode ? tgtNode : n );
9374 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9375 dumpChangeNodes( f );
9381 // find out if a FACE is concave
9382 const bool isConcaveFace = isConcave( F, helper );
9384 // Create _SmoothNode's on face F
9385 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9387 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9388 const bool sortSimplices = isConcaveFace;
9389 for ( size_t i = 0; i < smoothNodes.size(); ++i )
9391 const SMDS_MeshNode* n = smoothNodes[i];
9392 nodesToSmooth[ i ]._node = n;
9393 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9394 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9395 // fix up incorrect uv of nodes on the FACE
9396 helper.GetNodeUV( F, n, 0, &isOkUV);
9401 //if ( nodesToSmooth.empty() ) continue;
9403 // Find EDGE's to shrink and set simpices to LayerEdge's
9404 set< _Shrinker1D* > eShri1D;
9406 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9408 _EdgesOnShape& eos = * subEOS[ iS ];
9409 if ( eos.SWOLType() == TopAbs_EDGE )
9411 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9412 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
9413 eShri1D.insert( & srinker );
9414 srinker.AddEdge( eos._edges[0], eos, helper );
9415 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9416 // restore params of nodes on EGDE if the EDGE has been already
9417 // srinked while srinking other FACE
9418 srinker.RestoreParams();
9420 for ( size_t i = 0; i < eos._edges.size(); ++i )
9422 _LayerEdge& edge = * eos._edges[i];
9423 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9428 bool toFixTria = false; // to improve quality of trias by diagonal swap
9429 if ( isConcaveFace )
9431 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9432 if ( hasTria != hasQuad ) {
9433 toFixTria = hasTria;
9436 set<int> nbNodesSet;
9437 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9438 while ( fIt->more() && nbNodesSet.size() < 2 )
9439 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9440 toFixTria = ( *nbNodesSet.begin() == 3 );
9444 // ==================
9445 // Perform shrinking
9446 // ==================
9448 bool shrinked = true;
9449 int badNb, shriStep=0, smooStep=0;
9450 _SmoothNode::SmoothType smoothType
9451 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9452 SMESH_Comment errMsg;
9456 // Move boundary nodes (actually just set new UV)
9457 // -----------------------------------------------
9458 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9460 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9462 _EdgesOnShape& eos = * subEOS[ iS ];
9463 for ( size_t i = 0; i < eos._edges.size(); ++i )
9465 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9470 // Move nodes on EDGE's
9471 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9472 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9473 for ( ; shr != eShri1D.end(); ++shr )
9474 (*shr)->Compute( /*set3D=*/false, helper );
9477 // -----------------
9478 int nbNoImpSteps = 0;
9481 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
9483 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9485 int oldBadNb = badNb;
9488 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9489 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9490 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9492 moved |= nodesToSmooth[i].Smooth( badNb, surface, helper, refSign,
9493 smooTy, /*set3D=*/isConcaveFace);
9495 if ( badNb < oldBadNb )
9505 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9506 if ( shriStep > 200 )
9507 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9508 if ( !errMsg.empty() )
9511 // Fix narrow triangles by swapping diagonals
9512 // ---------------------------------------
9515 set<const SMDS_MeshNode*> usedNodes;
9516 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9518 // update working data
9519 set<const SMDS_MeshNode*>::iterator n;
9520 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9522 n = usedNodes.find( nodesToSmooth[ i ]._node );
9523 if ( n != usedNodes.end())
9525 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9526 nodesToSmooth[ i ]._simplices,
9528 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9529 usedNodes.erase( n );
9532 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9534 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9535 if ( n != usedNodes.end())
9537 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9538 lEdges[i]->_simplices,
9540 usedNodes.erase( n );
9544 // TODO: check effect of this additional smooth
9545 // additional laplacian smooth to increase allowed shrink step
9546 // for ( int st = 1; st; --st )
9548 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9549 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9551 // nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
9552 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
9556 } // while ( shrinked )
9558 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9561 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9563 vector< const SMDS_MeshElement* > facesToRm;
9566 facesToRm.reserve( psm->NbElements() );
9567 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9568 facesToRm.push_back( ite->next() );
9570 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9571 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9574 for ( size_t i = 0; i < facesToRm.size(); ++i )
9575 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9579 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9580 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9581 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9582 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9583 subEOS[iS]->_edges[i]->_nodes.end() );
9585 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9586 while ( itn->more() ) {
9587 const SMDS_MeshNode* n = itn->next();
9588 if ( !nodesToKeep.count( n ))
9589 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9592 // restore position and UV of target nodes
9594 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9595 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9597 _LayerEdge* edge = subEOS[iS]->_edges[i];
9598 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9599 if ( edge->_pos.empty() ) continue;
9600 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9602 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9603 pos->SetUParameter( edge->_pos[0].X() );
9604 pos->SetVParameter( edge->_pos[0].Y() );
9605 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
9609 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9610 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
9611 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
9613 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
9614 dumpMove( tgtNode );
9616 // shrink EDGE sub-meshes and set proxy sub-meshes
9617 UVPtStructVec uvPtVec;
9618 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
9619 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
9621 _Shrinker1D* shr = (*shrIt);
9622 shr->Compute( /*set3D=*/true, helper );
9624 // set proxy mesh of EDGEs w/o layers
9625 map< double, const SMDS_MeshNode* > nodes;
9626 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
9627 // remove refinement nodes
9628 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
9629 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
9630 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
9631 if ( u2n->second == sn0 || u2n->second == sn1 )
9633 while ( u2n->second != tn0 && u2n->second != tn1 )
9635 nodes.erase( nodes.begin(), u2n );
9637 u2n = --nodes.end();
9638 if ( u2n->second == sn0 || u2n->second == sn1 )
9640 while ( u2n->second != tn0 && u2n->second != tn1 )
9642 nodes.erase( ++u2n, nodes.end() );
9644 // set proxy sub-mesh
9645 uvPtVec.resize( nodes.size() );
9646 u2n = nodes.begin();
9647 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
9648 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
9650 uvPtVec[ i ].node = u2n->second;
9651 uvPtVec[ i ].param = u2n->first;
9652 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
9654 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
9655 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9658 // set proxy mesh of EDGEs with layers
9659 vector< _LayerEdge* > edges;
9660 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9662 _EdgesOnShape& eos = * subEOS[ iS ];
9663 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
9665 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
9666 data.SortOnEdge( E, eos._edges );
9669 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
9670 if ( !eov->_edges.empty() )
9671 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
9673 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
9675 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
9676 if ( !eov->_edges.empty() )
9677 edges.push_back( eov->_edges[0] ); // on last VERTEX
9679 uvPtVec.resize( edges.size() );
9680 for ( size_t i = 0; i < edges.size(); ++i )
9682 uvPtVec[ i ].node = edges[i]->_nodes.back();
9683 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
9684 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
9686 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
9687 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
9688 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9690 // temporary clear the FACE sub-mesh from faces made by refine()
9691 vector< const SMDS_MeshElement* > elems;
9692 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
9693 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9694 elems.push_back( ite->next() );
9695 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
9696 elems.push_back( ite->next() );
9699 // compute the mesh on the FACE
9700 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
9701 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
9703 // re-fill proxy sub-meshes of the FACE
9704 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9705 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9706 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9707 psm->AddElement( ite->next() );
9710 for ( size_t i = 0; i < elems.size(); ++i )
9711 smDS->AddElement( elems[i] );
9713 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
9714 return error( errMsg );
9716 } // end of re-meshing in case of failed smoothing
9719 // No wrongly shaped faces remain; final smooth. Set node XYZ.
9720 bool isStructuredFixed = false;
9721 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
9722 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
9723 if ( !isStructuredFixed )
9725 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
9726 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
9728 for ( int st = 3; st; --st )
9731 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
9732 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
9733 case 3: smoothType = _SmoothNode::ANGULAR; break;
9735 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9736 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9738 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
9739 smoothType,/*set3D=*/st==1 );
9744 if ( !getMeshDS()->IsEmbeddedMode() )
9745 // Log node movement
9746 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9748 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
9749 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
9753 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
9754 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
9756 } // loop on FACES to srink mesh on
9759 // Replace source nodes by target nodes in shrinked mesh edges
9761 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
9762 for ( ; e2shr != e2shrMap.end(); ++e2shr )
9763 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
9768 //================================================================================
9770 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
9772 //================================================================================
9774 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
9776 SMESH_MesherHelper& helper,
9777 const SMESHDS_SubMesh* faceSubMesh)
9779 const SMDS_MeshNode* srcNode = edge._nodes[0];
9780 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9782 if ( eos.SWOLType() == TopAbs_FACE )
9784 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
9787 return srcNode == tgtNode;
9789 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
9790 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
9791 gp_Vec2d uvDir( srcUV, tgtUV );
9792 double uvLen = uvDir.Magnitude();
9794 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
9797 edge._pos.resize(1);
9798 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
9800 // set UV of source node to target node
9801 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9802 pos->SetUParameter( srcUV.X() );
9803 pos->SetVParameter( srcUV.Y() );
9805 else // _sWOL is TopAbs_EDGE
9807 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
9810 return srcNode == tgtNode;
9812 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
9813 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
9814 if ( !edgeSM || edgeSM->NbElements() == 0 )
9815 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9817 const SMDS_MeshNode* n2 = 0;
9818 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
9819 while ( eIt->more() && !n2 )
9821 const SMDS_MeshElement* e = eIt->next();
9822 if ( !edgeSM->Contains(e)) continue;
9823 n2 = e->GetNode( 0 );
9824 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
9827 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9829 double uSrc = helper.GetNodeU( E, srcNode, n2 );
9830 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
9831 double u2 = helper.GetNodeU( E, n2, srcNode );
9835 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
9837 // tgtNode is located so that it does not make faces with wrong orientation
9840 edge._pos.resize(1);
9841 edge._pos[0].SetCoord( U_TGT, uTgt );
9842 edge._pos[0].SetCoord( U_SRC, uSrc );
9843 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
9845 edge._simplices.resize( 1 );
9846 edge._simplices[0]._nPrev = n2;
9848 // set U of source node to the target node
9849 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9850 pos->SetUParameter( uSrc );
9855 //================================================================================
9857 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
9859 //================================================================================
9861 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
9863 if ( edge._nodes.size() == 1 )
9868 const SMDS_MeshNode* srcNode = edge._nodes[0];
9869 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
9870 if ( S.IsNull() ) return;
9874 switch ( S.ShapeType() )
9879 TopLoc_Location loc;
9880 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
9881 if ( curve.IsNull() ) return;
9882 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
9883 p = curve->Value( ePos->GetUParameter() );
9888 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
9893 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
9894 dumpMove( srcNode );
9898 //================================================================================
9900 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
9902 //================================================================================
9904 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
9905 SMESH_MesherHelper& helper,
9908 set<const SMDS_MeshNode*> * involvedNodes)
9910 SMESH::Controls::AspectRatio qualifier;
9911 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
9912 const double maxAspectRatio = is2D ? 4. : 2;
9913 _NodeCoordHelper xyz( F, helper, is2D );
9915 // find bad triangles
9917 vector< const SMDS_MeshElement* > badTrias;
9918 vector< double > badAspects;
9919 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
9920 SMDS_ElemIteratorPtr fIt = sm->GetElements();
9921 while ( fIt->more() )
9923 const SMDS_MeshElement * f = fIt->next();
9924 if ( f->NbCornerNodes() != 3 ) continue;
9925 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
9926 double aspect = qualifier.GetValue( points );
9927 if ( aspect > maxAspectRatio )
9929 badTrias.push_back( f );
9930 badAspects.push_back( aspect );
9935 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
9936 SMDS_ElemIteratorPtr fIt = sm->GetElements();
9937 while ( fIt->more() )
9939 const SMDS_MeshElement * f = fIt->next();
9940 if ( f->NbCornerNodes() == 3 )
9941 dumpChangeNodes( f );
9945 if ( badTrias.empty() )
9948 // find couples of faces to swap diagonal
9950 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
9951 vector< T2Trias > triaCouples;
9953 TIDSortedElemSet involvedFaces, emptySet;
9954 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
9957 double aspRatio [3];
9960 if ( !involvedFaces.insert( badTrias[iTia] ).second )
9962 for ( int iP = 0; iP < 3; ++iP )
9963 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
9965 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
9966 int bestCouple = -1;
9967 for ( int iSide = 0; iSide < 3; ++iSide )
9969 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
9970 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
9971 trias [iSide].first = badTrias[iTia];
9972 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
9974 if (( ! trias[iSide].second ) ||
9975 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
9976 ( ! sm->Contains( trias[iSide].second )))
9979 // aspect ratio of an adjacent tria
9980 for ( int iP = 0; iP < 3; ++iP )
9981 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
9982 double aspectInit = qualifier.GetValue( points2 );
9984 // arrange nodes as after diag-swaping
9985 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
9986 i3 = helper.WrapIndex( i1-1, 3 );
9988 i3 = helper.WrapIndex( i1+1, 3 );
9990 points1( 1+ iSide ) = points2( 1+ i3 );
9991 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
9993 // aspect ratio after diag-swaping
9994 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
9995 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
9998 // prevent inversion of a triangle
9999 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10000 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10001 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10004 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10005 bestCouple = iSide;
10008 if ( bestCouple >= 0 )
10010 triaCouples.push_back( trias[bestCouple] );
10011 involvedFaces.insert ( trias[bestCouple].second );
10015 involvedFaces.erase( badTrias[iTia] );
10018 if ( triaCouples.empty() )
10023 SMESH_MeshEditor editor( helper.GetMesh() );
10024 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10025 for ( size_t i = 0; i < triaCouples.size(); ++i )
10027 dumpChangeNodes( triaCouples[i].first );
10028 dumpChangeNodes( triaCouples[i].second );
10029 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10032 if ( involvedNodes )
10033 for ( size_t i = 0; i < triaCouples.size(); ++i )
10035 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10036 triaCouples[i].first->end_nodes() );
10037 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10038 triaCouples[i].second->end_nodes() );
10041 // just for debug dump resulting triangles
10042 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10043 for ( size_t i = 0; i < triaCouples.size(); ++i )
10045 dumpChangeNodes( triaCouples[i].first );
10046 dumpChangeNodes( triaCouples[i].second );
10050 //================================================================================
10052 * \brief Move target node to it's final position on the FACE during shrinking
10054 //================================================================================
10056 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10057 const TopoDS_Face& F,
10058 _EdgesOnShape& eos,
10059 SMESH_MesherHelper& helper )
10061 if ( _pos.empty() )
10062 return false; // already at the target position
10064 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10066 if ( eos.SWOLType() == TopAbs_FACE )
10068 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
10069 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10070 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10071 const double uvLen = tgtUV.Distance( curUV );
10072 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10074 // Select shrinking step such that not to make faces with wrong orientation.
10075 double stepSize = 1e100;
10076 for ( size_t i = 0; i < _simplices.size(); ++i )
10078 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10079 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10080 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10081 gp_XY dirN = uvN2 - uvN1;
10082 double det = uvDir.Crossed( dirN );
10083 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
10084 gp_XY dirN2Cur = curUV - uvN1;
10085 double step = dirN.Crossed( dirN2Cur ) / det;
10087 stepSize = Min( step, stepSize );
10090 if ( uvLen <= stepSize )
10095 else if ( stepSize > 0 )
10097 newUV = curUV + uvDir.XY() * stepSize * kSafe;
10103 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10104 pos->SetUParameter( newUV.X() );
10105 pos->SetVParameter( newUV.Y() );
10108 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10109 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10110 dumpMove( tgtNode );
10113 else // _sWOL is TopAbs_EDGE
10115 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10116 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
10117 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10119 const double u2 = helper.GetNodeU( E, n2, tgtNode );
10120 const double uSrc = _pos[0].Coord( U_SRC );
10121 const double lenTgt = _pos[0].Coord( LEN_TGT );
10123 double newU = _pos[0].Coord( U_TGT );
10124 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10130 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10132 tgtPos->SetUParameter( newU );
10134 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10135 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10136 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10137 dumpMove( tgtNode );
10144 //================================================================================
10146 * \brief Perform smooth on the FACE
10147 * \retval bool - true if the node has been moved
10149 //================================================================================
10151 bool _SmoothNode::Smooth(int& badNb,
10152 Handle(Geom_Surface)& surface,
10153 SMESH_MesherHelper& helper,
10154 const double refSign,
10158 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10160 // get uv of surrounding nodes
10161 vector<gp_XY> uv( _simplices.size() );
10162 for ( size_t i = 0; i < _simplices.size(); ++i )
10163 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10165 // compute new UV for the node
10166 gp_XY newPos (0,0);
10167 if ( how == TFI && _simplices.size() == 4 )
10170 for ( size_t i = 0; i < _simplices.size(); ++i )
10171 if ( _simplices[i]._nOpp )
10172 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10174 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10176 newPos = helper.calcTFI ( 0.5, 0.5,
10177 corners[0], corners[1], corners[2], corners[3],
10178 uv[1], uv[2], uv[3], uv[0] );
10180 else if ( how == ANGULAR )
10182 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10184 else if ( how == CENTROIDAL && _simplices.size() > 3 )
10186 // average centers of diagonals wieghted with their reciprocal lengths
10187 if ( _simplices.size() == 4 )
10189 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10190 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10191 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10195 double sumWeight = 0;
10196 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10197 for ( int i = 0; i < nb; ++i )
10200 int iTo = i + _simplices.size() - 1;
10201 for ( int j = iFrom; j < iTo; ++j )
10203 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10204 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10206 newPos += w * ( uv[i]+uv[i2] );
10209 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10214 // Laplacian smooth
10215 for ( size_t i = 0; i < _simplices.size(); ++i )
10217 newPos /= _simplices.size();
10220 // count quality metrics (orientation) of triangles around the node
10221 int nbOkBefore = 0;
10222 gp_XY tgtUV = helper.GetNodeUV( face, _node );
10223 for ( size_t i = 0; i < _simplices.size(); ++i )
10224 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10227 for ( size_t i = 0; i < _simplices.size(); ++i )
10228 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10230 if ( nbOkAfter < nbOkBefore )
10232 badNb += _simplices.size() - nbOkBefore;
10236 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10237 pos->SetUParameter( newPos.X() );
10238 pos->SetVParameter( newPos.Y() );
10245 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10246 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10250 badNb += _simplices.size() - nbOkAfter;
10251 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10254 //================================================================================
10256 * \brief Computes new UV using angle based smoothing technic
10258 //================================================================================
10260 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10261 const gp_XY& uvToFix,
10262 const double refSign)
10264 uv.push_back( uv.front() );
10266 vector< gp_XY > edgeDir ( uv.size() );
10267 vector< double > edgeSize( uv.size() );
10268 for ( size_t i = 1; i < edgeDir.size(); ++i )
10270 edgeDir [i-1] = uv[i] - uv[i-1];
10271 edgeSize[i-1] = edgeDir[i-1].Modulus();
10272 if ( edgeSize[i-1] < numeric_limits<double>::min() )
10273 edgeDir[i-1].SetX( 100 );
10275 edgeDir[i-1] /= edgeSize[i-1] * refSign;
10277 edgeDir.back() = edgeDir.front();
10278 edgeSize.back() = edgeSize.front();
10282 double sumSize = 0;
10283 for ( size_t i = 1; i < edgeDir.size(); ++i )
10285 if ( edgeDir[i-1].X() > 1. ) continue;
10287 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10288 if ( i == edgeDir.size() ) break;
10290 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10291 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
10292 gp_XY bisec = norm1 + norm2;
10293 double bisecSize = bisec.Modulus();
10294 if ( bisecSize < numeric_limits<double>::min() )
10296 bisec = -edgeDir[i1] + edgeDir[i];
10297 bisecSize = bisec.Modulus();
10299 bisec /= bisecSize;
10301 gp_XY dirToN = uvToFix - p;
10302 double distToN = dirToN.Modulus();
10303 if ( bisec * dirToN < 0 )
10304 distToN = -distToN;
10306 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10308 sumSize += edgeSize[i1] + edgeSize[i];
10310 newPos /= /*nbEdges * */sumSize;
10314 //================================================================================
10316 * \brief Delete _SolidData
10318 //================================================================================
10320 _SolidData::~_SolidData()
10322 TNode2Edge::iterator n2e = _n2eMap.begin();
10323 for ( ; n2e != _n2eMap.end(); ++n2e )
10325 _LayerEdge* & e = n2e->second;
10328 delete e->_curvature;
10329 if ( e->_2neibors )
10330 delete e->_2neibors->_plnNorm;
10331 delete e->_2neibors;
10342 //================================================================================
10344 * \brief Keep a _LayerEdge inflated along the EDGE
10346 //================================================================================
10348 void _Shrinker1D::AddEdge( const _LayerEdge* e,
10349 _EdgesOnShape& eos,
10350 SMESH_MesherHelper& helper )
10353 if ( _nodes.empty() )
10355 _edges[0] = _edges[1] = 0;
10358 // check _LayerEdge
10359 if ( e == _edges[0] || e == _edges[1] )
10361 if ( eos.SWOLType() != TopAbs_EDGE )
10362 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10363 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10364 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10366 // store _LayerEdge
10367 _geomEdge = TopoDS::Edge( eos._sWOL );
10369 BRep_Tool::Range( _geomEdge, f,l );
10370 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10371 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10375 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10376 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10378 if ( _nodes.empty() )
10380 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10381 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10383 TopLoc_Location loc;
10384 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10385 GeomAdaptor_Curve aCurve(C, f,l);
10386 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10388 int nbExpectNodes = eSubMesh->NbNodes();
10389 _initU .reserve( nbExpectNodes );
10390 _normPar.reserve( nbExpectNodes );
10391 _nodes .reserve( nbExpectNodes );
10392 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10393 while ( nIt->more() )
10395 const SMDS_MeshNode* node = nIt->next();
10396 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10397 node == tgtNode0 || node == tgtNode1 )
10398 continue; // refinement nodes
10399 _nodes.push_back( node );
10400 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10401 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10402 _normPar.push_back( len / totLen );
10407 // remove target node of the _LayerEdge from _nodes
10408 size_t nbFound = 0;
10409 for ( size_t i = 0; i < _nodes.size(); ++i )
10410 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10411 _nodes[i] = 0, nbFound++;
10412 if ( nbFound == _nodes.size() )
10417 //================================================================================
10419 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10421 //================================================================================
10423 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10425 if ( _done || _nodes.empty())
10427 const _LayerEdge* e = _edges[0];
10428 if ( !e ) e = _edges[1];
10431 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10432 ( !_edges[1] || _edges[1]->_pos.empty() ));
10435 if ( set3D || _done )
10437 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10438 GeomAdaptor_Curve aCurve(C, f,l);
10441 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10443 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10444 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10446 for ( size_t i = 0; i < _nodes.size(); ++i )
10448 if ( !_nodes[i] ) continue;
10449 double len = totLen * _normPar[i];
10450 GCPnts_AbscissaPoint discret( aCurve, len, f );
10451 if ( !discret.IsDone() )
10452 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10453 double u = discret.Parameter();
10454 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10455 pos->SetUParameter( u );
10456 gp_Pnt p = C->Value( u );
10457 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10462 BRep_Tool::Range( _geomEdge, f,l );
10464 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10466 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10468 for ( size_t i = 0; i < _nodes.size(); ++i )
10470 if ( !_nodes[i] ) continue;
10471 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10472 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10473 pos->SetUParameter( u );
10478 //================================================================================
10480 * \brief Restore initial parameters of nodes on EDGE
10482 //================================================================================
10484 void _Shrinker1D::RestoreParams()
10487 for ( size_t i = 0; i < _nodes.size(); ++i )
10489 if ( !_nodes[i] ) continue;
10490 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10491 pos->SetUParameter( _initU[i] );
10496 //================================================================================
10498 * \brief Replace source nodes by target nodes in shrinked mesh edges
10500 //================================================================================
10502 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10504 const SMDS_MeshNode* nodes[3];
10505 for ( int i = 0; i < 2; ++i )
10507 if ( !_edges[i] ) continue;
10509 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10510 if ( !eSubMesh ) return;
10511 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10512 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10513 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10514 while ( eIt->more() )
10516 const SMDS_MeshElement* e = eIt->next();
10517 if ( !eSubMesh->Contains( e ))
10519 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10520 for ( int iN = 0; iN < e->NbNodes(); ++iN )
10522 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10523 nodes[iN] = ( n == srcNode ? tgtNode : n );
10525 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10530 //================================================================================
10532 * \brief Creates 2D and 1D elements on boundaries of new prisms
10534 //================================================================================
10536 bool _ViscousBuilder::addBoundaryElements()
10538 SMESH_MesherHelper helper( *_mesh );
10540 vector< const SMDS_MeshNode* > faceNodes;
10542 for ( size_t i = 0; i < _sdVec.size(); ++i )
10544 _SolidData& data = _sdVec[i];
10545 TopTools_IndexedMapOfShape geomEdges;
10546 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10547 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10549 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10550 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10553 // Get _LayerEdge's based on E
10555 map< double, const SMDS_MeshNode* > u2nodes;
10556 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10559 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10560 TNode2Edge & n2eMap = data._n2eMap;
10561 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10563 //check if 2D elements are needed on E
10564 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10565 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10566 ledges.push_back( n2e->second );
10568 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10569 continue; // no layers on E
10570 ledges.push_back( n2eMap[ u2n->second ]);
10572 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10573 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10574 int nbSharedPyram = 0;
10575 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10576 while ( vIt->more() )
10578 const SMDS_MeshElement* v = vIt->next();
10579 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10581 if ( nbSharedPyram > 1 )
10582 continue; // not free border of the pyramid
10585 faceNodes.push_back( ledges[0]->_nodes[0] );
10586 faceNodes.push_back( ledges[1]->_nodes[0] );
10587 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10588 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10590 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10591 continue; // faces already created
10593 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10594 ledges.push_back( n2eMap[ u2n->second ]);
10596 // Find out orientation and type of face to create
10598 bool reverse = false, isOnFace;
10600 map< TGeomID, TopoDS_Shape >::iterator e2f =
10601 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10603 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10605 F = e2f->second.Oriented( TopAbs_FORWARD );
10606 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
10607 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
10608 reverse = !reverse, F.Reverse();
10609 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
10610 reverse = !reverse;
10614 // find FACE with layers sharing E
10615 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
10616 while ( fIt->more() && F.IsNull() )
10618 const TopoDS_Shape* pF = fIt->next();
10619 if ( helper.IsSubShape( *pF, data._solid) &&
10620 !data._ignoreFaceIds.count( e2f->first ))
10624 // Find the sub-mesh to add new faces
10625 SMESHDS_SubMesh* sm = 0;
10627 sm = getMeshDS()->MeshElements( F );
10629 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
10631 return error("error in addBoundaryElements()", data._index);
10634 const int dj1 = reverse ? 0 : 1;
10635 const int dj2 = reverse ? 1 : 0;
10636 for ( size_t j = 1; j < ledges.size(); ++j )
10638 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
10639 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
10640 if ( nn1.size() == nn2.size() )
10643 for ( size_t z = 1; z < nn1.size(); ++z )
10644 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10646 for ( size_t z = 1; z < nn1.size(); ++z )
10647 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10649 else if ( nn1.size() == 1 )
10652 for ( size_t z = 1; z < nn2.size(); ++z )
10653 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
10655 for ( size_t z = 1; z < nn2.size(); ++z )
10656 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
10661 for ( size_t z = 1; z < nn1.size(); ++z )
10662 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
10664 for ( size_t z = 1; z < nn1.size(); ++z )
10665 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
10670 for ( int isFirst = 0; isFirst < 2; ++isFirst )
10672 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
10673 _EdgesOnShape* eos = data.GetShapeEdges( edge );
10674 if ( eos && eos->SWOLType() == TopAbs_EDGE )
10676 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
10677 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
10679 helper.SetSubShape( eos->_sWOL );
10680 helper.SetElementsOnShape( true );
10681 for ( size_t z = 1; z < nn.size(); ++z )
10682 helper.AddEdge( nn[z-1], nn[z] );
10686 } // loop on EDGE's
10687 } // loop on _SolidData's