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 "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
109 //================================================================================
114 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
116 const double theMinSmoothCosin = 0.1;
117 const double theSmoothThickToElemSizeRatio = 0.3;
118 const double theMinSmoothTriaAngle = 30;
119 const double theMinSmoothQuadAngle = 45;
121 // what part of thickness is allowed till intersection
122 // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123 const double theThickToIntersection = 1.5;
125 bool needSmoothing( double cosin, double tgtThick, double elemSize )
127 return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
129 double getSmoothingThickness( double cosin, double elemSize )
131 return theSmoothThickToElemSizeRatio * elemSize / cosin;
135 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
138 struct _MeshOfSolid : public SMESH_ProxyMesh,
139 public SMESH_subMeshEventListenerData
141 bool _n2nMapComputed;
142 SMESH_ComputeErrorPtr _warning;
144 _MeshOfSolid( SMESH_Mesh* mesh)
145 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
147 SMESH_ProxyMesh::setMesh( *mesh );
150 // returns submesh for a geom face
151 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
153 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
156 void setNode2Node(const SMDS_MeshNode* srcNode,
157 const SMDS_MeshNode* proxyNode,
158 const SMESH_ProxyMesh::SubMesh* subMesh)
160 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
163 //--------------------------------------------------------------------------------
165 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166 * It is used to clear an inferior dim sub-meshes modified by viscous layers
168 class _ShrinkShapeListener : SMESH_subMeshEventListener
170 _ShrinkShapeListener()
171 : SMESH_subMeshEventListener(/*isDeletable=*/false,
172 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
174 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175 virtual void ProcessEvent(const int event,
177 SMESH_subMesh* solidSM,
178 SMESH_subMeshEventListenerData* data,
179 const SMESH_Hypothesis* hyp)
181 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
183 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
187 //--------------------------------------------------------------------------------
189 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191 * delete the data as soon as it has been used
193 class _ViscousListener : SMESH_subMeshEventListener
196 SMESH_subMeshEventListener(/*isDeletable=*/false,
197 "StdMeshers_ViscousLayers::_ViscousListener") {}
198 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
200 virtual void ProcessEvent(const int event,
202 SMESH_subMesh* subMesh,
203 SMESH_subMeshEventListenerData* data,
204 const SMESH_Hypothesis* hyp)
206 if (( SMESH_subMesh::COMPUTE_EVENT == eventType ) &&
207 ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208 SMESH_subMesh::SUBMESH_COMPUTED != event ))
210 // delete SMESH_ProxyMesh containing temporary faces
211 subMesh->DeleteEventListener( this );
214 // Finds or creates proxy mesh of the solid
215 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
216 const TopoDS_Shape& solid,
219 if ( !mesh ) return 0;
220 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222 if ( !data && toCreate )
224 data = new _MeshOfSolid(mesh);
225 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226 sm->SetEventListener( Get(), data, sm );
230 // Removes proxy mesh of the solid
231 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
233 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
237 //================================================================================
239 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240 * the main shape when sub-mesh of the main shape is cleared,
241 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
244 //================================================================================
246 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
248 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249 SMESH_subMeshEventListenerData* data =
250 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
253 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254 data->mySubMeshes.end())
255 data->mySubMeshes.push_back( sub );
259 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
264 //--------------------------------------------------------------------------------
266 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268 * The class is used to check validity of face or volumes around a smoothed node;
269 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
273 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275 _Simplex(const SMDS_MeshNode* nPrev=0,
276 const SMDS_MeshNode* nNext=0,
277 const SMDS_MeshNode* nOpp=0)
278 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279 bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
281 const double M[3][3] =
282 {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283 { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284 { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285 vol = ( + M[0][0] * M[1][1] * M[2][2]
286 + M[0][1] * M[1][2] * M[2][0]
287 + M[0][2] * M[1][0] * M[2][1]
288 - M[0][0] * M[1][2] * M[2][1]
289 - M[0][1] * M[1][0] * M[2][2]
290 - M[0][2] * M[1][1] * M[2][0]);
293 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
295 SMESH_TNodeXYZ pSrc( nSrc );
296 return IsForward( &pSrc, &pTgt, vol );
298 bool IsForward(const gp_XY& tgtUV,
299 const SMDS_MeshNode* smoothedNode,
300 const TopoDS_Face& face,
301 SMESH_MesherHelper& helper,
302 const double refSign) const
304 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
308 return d*refSign > 1e-100;
310 bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
312 SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313 if ( !_nOpp ) // triangle
315 gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316 double tp2 = tp.SquareMagnitude();
317 double pn2 = pn.SquareMagnitude();
318 double nt2 = nt.SquareMagnitude();
320 if ( tp2 < pn2 && tp2 < nt2 )
321 minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322 else if ( pn2 < nt2 )
323 minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
325 minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
327 static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328 Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329 return minAngle < theMaxCos2;
333 SMESH_TNodeXYZ pOpp( _nOpp );
334 gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335 double tp2 = tp.SquareMagnitude();
336 double po2 = po.SquareMagnitude();
337 double on2 = on.SquareMagnitude();
338 double nt2 = nt.SquareMagnitude();
339 minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340 (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341 Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342 (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
344 static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345 Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346 return minAngle < theMaxCos2;
349 bool IsNeighbour(const _Simplex& other) const
351 return _nPrev == other._nNext || _nNext == other._nPrev;
353 bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354 static void GetSimplices( const SMDS_MeshNode* node,
355 vector<_Simplex>& simplices,
356 const set<TGeomID>& ingnoreShapes,
357 const _SolidData* dataToCheckOri = 0,
358 const bool toSort = false);
359 static void SortSimplices(vector<_Simplex>& simplices);
361 //--------------------------------------------------------------------------------
363 * Structure used to take into account surface curvature while smoothing
368 double _k; // factor to correct node smoothed position
369 double _h2lenRatio; // avgNormProj / (2*avgDist)
370 gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
372 static _Curvature* New( double avgNormProj, double avgDist )
375 if ( fabs( avgNormProj / avgDist ) > 1./200 )
378 c->_r = avgDist * avgDist / avgNormProj;
379 c->_k = avgDist * avgDist / c->_r / c->_r;
380 //c->_k = avgNormProj / c->_r;
381 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
384 c->_uv.SetCoord( 0., 0. );
388 double lenDelta(double len) const { return _k * ( _r + len ); }
389 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
391 //--------------------------------------------------------------------------------
395 struct _EdgesOnShape;
397 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
399 //--------------------------------------------------------------------------------
401 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402 * and a node of the most internal layer (_nodes.back())
406 typedef gp_XYZ (_LayerEdge::*PSmooFun)();
408 vector< const SMDS_MeshNode*> _nodes;
410 gp_XYZ _normal; // to boundary of solid
411 vector<gp_XYZ> _pos; // points computed during inflation
412 double _len; // length achived with the last inflation step
413 double _maxLen; // maximal possible length
414 double _cosin; // of angle (_normal ^ surface)
415 double _minAngle; // of _simplices
416 double _lenFactor; // to compute _len taking _cosin into account
419 // simplices connected to the source node (_nodes[0]);
420 // used for smoothing and quality check of _LayerEdge's based on the FACE
421 vector<_Simplex> _simplices;
422 vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423 PSmooFun _smooFunction; // smoothing function
424 _Curvature* _curvature;
425 // data for smoothing of _LayerEdge's based on the EDGE
426 _2NearEdges* _2neibors;
428 enum EFlags { TO_SMOOTH = 0x0000001,
429 MOVED = 0x0000002, // set by _neibors[i]->SetNewLength()
430 SMOOTHED = 0x0000004, // set by this->Smooth()
431 DIFFICULT = 0x0000008, // near concave VERTEX
432 ON_CONCAVE_FACE = 0x0000010,
433 BLOCKED = 0x0000020, // not to inflate any more
434 INTERSECTED = 0x0000040, // close intersection with a face found
435 NORMAL_UPDATED = 0x0000080,
436 MARKED = 0x0000100, // local usage
437 MULTI_NORMAL = 0x0000200, // a normal is invisible by some of surrounding faces
438 NEAR_BOUNDARY = 0x0000400, // is near FACE boundary forcing smooth
439 SMOOTHED_C1 = 0x0000800, // is on _eosC1
440 DISTORTED = 0x0001000, // was bad before smoothing
441 RISKY_SWOL = 0x0002000, // SWOL is parallel to a source FACE
442 SHRUNK = 0x0004000, // target node reached a tgt position while shrink()
443 UNUSED_FLAG = 0x0100000
445 bool Is ( int flag ) const { return _flags & flag; }
446 void Set ( int flag ) { _flags |= flag; }
447 void Unset( int flag ) { _flags &= ~flag; }
448 std::string DumpFlags() const; // debug
450 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
451 bool SetNewLength2d( Handle(Geom_Surface)& surface,
452 const TopoDS_Face& F,
454 SMESH_MesherHelper& helper );
455 void SetDataByNeighbors( const SMDS_MeshNode* n1,
456 const SMDS_MeshNode* n2,
457 const _EdgesOnShape& eos,
458 SMESH_MesherHelper& helper);
459 void Block( _SolidData& data );
460 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
461 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
462 const TNode2Edge& n2eMap);
463 void SmoothPos( const vector< double >& segLen, const double tol );
464 int GetSmoothedPos( const double tol );
465 int Smooth(const int step, const bool isConcaveFace, bool findBest);
466 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
467 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
468 void SmoothWoCheck();
469 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
470 const TopoDS_Face& F,
471 SMESH_MesherHelper& helper);
472 void MoveNearConcaVer( const _EdgesOnShape* eov,
473 const _EdgesOnShape* eos,
475 vector< _LayerEdge* > & badSmooEdges);
476 bool FindIntersection( SMESH_ElementSearcher& searcher,
478 const double& epsilon,
480 const SMDS_MeshElement** face = 0);
481 bool SegTriaInter( const gp_Ax1& lastSegment,
486 const double& epsilon) const;
487 bool SegTriaInter( const gp_Ax1& lastSegment,
488 const SMDS_MeshNode* n0,
489 const SMDS_MeshNode* n1,
490 const SMDS_MeshNode* n2,
492 const double& epsilon) const
493 { return SegTriaInter( lastSegment,
494 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
497 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
498 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
499 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
500 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
501 bool IsOnEdge() const { return _2neibors; }
502 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
503 void SetCosin( double cosin );
504 void SetNormal( const gp_XYZ& n ) { _normal = n; }
505 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
506 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
507 void SetSmooLen( double len ) { // set _len at which smoothing is needed
508 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
510 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
512 gp_XYZ smoothLaplacian();
513 gp_XYZ smoothAngular();
514 gp_XYZ smoothLengthWeighted();
515 gp_XYZ smoothCentroidal();
516 gp_XYZ smoothNefPolygon();
518 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
519 static const int theNbSmooFuns = FUN_NB;
520 static PSmooFun _funs[theNbSmooFuns];
521 static const char* _funNames[theNbSmooFuns+1];
522 int smooFunID( PSmooFun fun=0) const;
524 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
525 &_LayerEdge::smoothLengthWeighted,
526 &_LayerEdge::smoothCentroidal,
527 &_LayerEdge::smoothNefPolygon,
528 &_LayerEdge::smoothAngular };
529 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
537 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
539 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
540 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
543 //--------------------------------------------------------------------------------
545 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
549 gp_XY _pos, _dir, _inNorm;
550 bool IsOut( const gp_XY p, const double tol ) const
552 return _inNorm * ( p - _pos ) < -tol;
554 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
556 //const double eps = 1e-10;
557 double D = _dir.Crossed( hp._dir );
558 if ( fabs(D) < std::numeric_limits<double>::min())
560 gp_XY vec21 = _pos - hp._pos;
561 double u = hp._dir.Crossed( vec21 ) / D;
562 intPnt = _pos + _dir * u;
566 //--------------------------------------------------------------------------------
568 * Structure used to smooth a _LayerEdge based on an EDGE.
572 double _wgt [2]; // weights of _nodes
573 _LayerEdge* _edges[2];
575 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
578 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
579 const SMDS_MeshNode* tgtNode(bool is2nd) {
580 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
582 const SMDS_MeshNode* srcNode(bool is2nd) {
583 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
586 std::swap( _wgt [0], _wgt [1] );
587 std::swap( _edges[0], _edges[1] );
589 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
590 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
592 bool include( const _LayerEdge* e ) {
593 return ( _edges[0] == e || _edges[1] == e );
598 //--------------------------------------------------------------------------------
600 * \brief Layers parameters got by averaging several hypotheses
604 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
605 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
609 void Add( const StdMeshers_ViscousLayers* hyp )
614 _nbLayers = hyp->GetNumberLayers();
615 //_thickness += hyp->GetTotalThickness();
616 _thickness = Max( _thickness, hyp->GetTotalThickness() );
617 _stretchFactor += hyp->GetStretchFactor();
618 _method = hyp->GetMethod();
621 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
622 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
623 int GetNumberLayers() const { return _nbLayers; }
624 int GetMethod() const { return _method; }
626 bool UseSurfaceNormal() const
627 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628 bool ToSmooth() const
629 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
630 bool IsOffsetMethod() const
631 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
634 int _nbLayers, _nbHyps, _method;
635 double _thickness, _stretchFactor;
638 //--------------------------------------------------------------------------------
640 * \brief _LayerEdge's on a shape and other shape data
644 vector< _LayerEdge* > _edges;
648 SMESH_subMesh * _subMesh;
649 // face or edge w/o layer along or near which _edges are inflated
651 bool _isRegularSWOL; // w/o singularities
652 // averaged StdMeshers_ViscousLayers parameters
655 _Smoother1D* _edgeSmoother;
656 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
657 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
659 vector< gp_XYZ > _faceNormals; // if _shape is FACE
660 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
662 Handle(ShapeAnalysis_Surface) _offsetSurf;
663 _LayerEdge* _edgeForOffset;
665 _SolidData* _data; // parent SOLID
667 TopAbs_ShapeEnum ShapeType() const
668 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
669 TopAbs_ShapeEnum SWOLType() const
670 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
671 bool HasC1( const _EdgesOnShape* other ) const
672 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
673 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
674 _SolidData& GetData() const { return *_data; }
676 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
679 //--------------------------------------------------------------------------------
681 * \brief Convex FACE whose radius of curvature is less than the thickness of
682 * layers. It is used to detect distortion of prisms based on a convex
683 * FACE and to update normals to enable further increasing the thickness
689 // edges whose _simplices are used to detect prism distortion
690 vector< _LayerEdge* > _simplexTestEdges;
692 // map a sub-shape to _SolidData::_edgesOnShape
693 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
697 bool GetCenterOfCurvature( _LayerEdge* ledge,
698 BRepLProp_SLProps& surfProp,
699 SMESH_MesherHelper& helper,
700 gp_Pnt & center ) const;
701 bool CheckPrisms() const;
704 //--------------------------------------------------------------------------------
706 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
707 * at inflation up to the full thickness. A detected collision
708 * is fixed in updateNormals()
710 struct _CollisionEdges
713 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
714 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
715 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
718 //--------------------------------------------------------------------------------
720 * \brief Data of a SOLID
724 typedef const StdMeshers_ViscousLayers* THyp;
726 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
727 TGeomID _index; // SOLID id
728 _MeshOfSolid* _proxyMesh;
730 list< TopoDS_Shape > _hypShapes;
731 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
732 set< TGeomID > _reversedFaceIds;
733 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
735 double _stepSize, _stepSizeCoeff, _geomSize;
736 const SMDS_MeshNode* _stepSizeNodes[2];
738 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
740 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
741 map< TGeomID, TNode2Edge* > _s2neMap;
742 // _LayerEdge's with underlying shapes
743 vector< _EdgesOnShape > _edgesOnShape;
745 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
746 // layers and a FACE w/o layers
747 // value: the shape (FACE or EDGE) to shrink mesh on.
748 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
749 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
751 // Convex FACEs whose radius of curvature is less than the thickness of layers
752 map< TGeomID, _ConvexFace > _convexFaces;
754 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
755 // the adjacent SOLID
756 set< TGeomID > _noShrinkShapes;
758 int _nbShapesToSmooth;
760 //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
762 vector< _CollisionEdges > _collisionEdges;
763 set< TGeomID > _concaveFaces;
765 double _maxThickness; // of all _hyps
766 double _minThickness; // of all _hyps
768 double _epsilon; // precision for SegTriaInter()
770 SMESH_MesherHelper* _helper;
772 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
774 :_solid(s), _proxyMesh(m), _helper(0) {}
777 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
778 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
780 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
781 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
782 return id2face == _convexFaces.end() ? 0 : & id2face->second;
784 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
785 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
786 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
787 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
789 SMESH_MesherHelper& GetHelper() const { return *_helper; }
791 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
792 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
793 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
794 _edgesOnShape[i]._edges[j]->Unset( flag );
796 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
797 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
799 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
801 //--------------------------------------------------------------------------------
803 * \brief Offset plane used in getNormalByOffset()
809 int _faceIndexNext[2];
810 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
813 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
815 void ComputeIntersectionLine( _OffsetPlane& pln,
816 const TopoDS_Edge& E,
817 const TopoDS_Vertex& V );
818 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
819 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
821 //--------------------------------------------------------------------------------
823 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
825 struct _CentralCurveOnEdge
828 vector< gp_Pnt > _curvaCenters;
829 vector< _LayerEdge* > _ledges;
830 vector< gp_XYZ > _normals; // new normal for each of _ledges
831 vector< double > _segLength2;
834 TopoDS_Face _adjFace;
835 bool _adjFaceToSmooth;
837 void Append( const gp_Pnt& center, _LayerEdge* ledge )
839 if ( _curvaCenters.size() > 0 )
840 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
841 _curvaCenters.push_back( center );
842 _ledges.push_back( ledge );
843 _normals.push_back( ledge->_normal );
845 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
846 void SetShapes( const TopoDS_Edge& edge,
847 const _ConvexFace& convFace,
849 SMESH_MesherHelper& helper);
851 //--------------------------------------------------------------------------------
853 * \brief Data of node on a shrinked FACE
857 const SMDS_MeshNode* _node;
858 vector<_Simplex> _simplices; // for quality check
860 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
862 bool Smooth(int& badNb,
863 Handle(Geom_Surface)& surface,
864 SMESH_MesherHelper& helper,
865 const double refSign,
869 gp_XY computeAngularPos(vector<gp_XY>& uv,
870 const gp_XY& uvToFix,
871 const double refSign );
873 //--------------------------------------------------------------------------------
875 * \brief Builder of viscous layers
877 class _ViscousBuilder
882 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
883 const TopoDS_Shape& shape);
884 // check validity of hypotheses
885 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
886 const TopoDS_Shape& shape );
888 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
889 void RestoreListeners();
891 // computes SMESH_ProxyMesh::SubMesh::_n2n;
892 bool MakeN2NMap( _MeshOfSolid* pm );
896 bool findSolidsWithLayers();
897 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
898 bool findFacesWithLayers(const bool onlyWith=false);
899 void getIgnoreFaces(const TopoDS_Shape& solid,
900 const StdMeshers_ViscousLayers* hyp,
901 const TopoDS_Shape& hypShape,
902 set<TGeomID>& ignoreFaces);
903 bool makeLayer(_SolidData& data);
904 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
905 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
906 SMESH_MesherHelper& helper, _SolidData& data);
907 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
908 const TopoDS_Face& face,
909 SMESH_MesherHelper& helper,
911 bool shiftInside=false);
912 bool getFaceNormalAtSingularity(const gp_XY& uv,
913 const TopoDS_Face& face,
914 SMESH_MesherHelper& helper,
916 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
917 gp_XYZ getNormalByOffset( _LayerEdge* edge,
918 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
920 bool lastNoOffset = false);
921 bool findNeiborsOnEdge(const _LayerEdge* edge,
922 const SMDS_MeshNode*& n1,
923 const SMDS_MeshNode*& n2,
926 void findSimplexTestEdges( _SolidData& data,
927 vector< vector<_LayerEdge*> >& edgesByGeom);
928 void computeGeomSize( _SolidData& data );
929 bool findShapesToSmooth( _SolidData& data);
930 void limitStepSizeByCurvature( _SolidData& data );
931 void limitStepSize( _SolidData& data,
932 const SMDS_MeshElement* face,
933 const _LayerEdge* maxCosinEdge );
934 void limitStepSize( _SolidData& data, const double minSize);
935 bool inflate(_SolidData& data);
936 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
937 int invalidateBadSmooth( _SolidData& data,
938 SMESH_MesherHelper& helper,
939 vector< _LayerEdge* >& badSmooEdges,
940 vector< _EdgesOnShape* >& eosC1,
942 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
943 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
944 vector< _EdgesOnShape* >& eosC1,
945 int smooStep=0, bool moveAll=false );
946 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
947 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
948 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
949 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
950 SMESH_MesherHelper& helper );
951 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
952 bool updateNormalsOfConvexFaces( _SolidData& data,
953 SMESH_MesherHelper& helper,
955 void updateNormalsOfC1Vertices( _SolidData& data );
956 bool updateNormalsOfSmoothed( _SolidData& data,
957 SMESH_MesherHelper& helper,
959 const double stepSize );
960 bool isNewNormalOk( _SolidData& data,
962 const gp_XYZ& newNormal);
963 bool refine(_SolidData& data);
964 bool shrink(_SolidData& data);
965 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
966 SMESH_MesherHelper& helper,
967 const SMESHDS_SubMesh* faceSubMesh );
968 void restoreNoShrink( _LayerEdge& edge ) const;
969 void fixBadFaces(const TopoDS_Face& F,
970 SMESH_MesherHelper& helper,
973 set<const SMDS_MeshNode*> * involvedNodes=NULL);
974 bool addBoundaryElements(_SolidData& data);
976 bool error( const string& text, int solidID=-1 );
977 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
980 void makeGroupOfLE();
983 SMESH_ComputeErrorPtr _error;
985 vector< _SolidData > _sdVec;
986 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
987 TopTools_MapOfShape _shrinkedFaces;
991 //--------------------------------------------------------------------------------
993 * \brief Shrinker of nodes on the EDGE
997 TopoDS_Edge _geomEdge;
998 vector<double> _initU;
999 vector<double> _normPar;
1000 vector<const SMDS_MeshNode*> _nodes;
1001 const _LayerEdge* _edges[2];
1004 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1005 void Compute(bool set3D, SMESH_MesherHelper& helper);
1006 void RestoreParams();
1007 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1008 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1009 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1010 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1011 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1012 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1014 //--------------------------------------------------------------------------------
1016 * \brief Smoother of _LayerEdge's on EDGE.
1020 struct OffPnt // point of the offsetted EDGE
1022 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1023 double _len; // length reached at previous inflation step
1024 double _param; // on EDGE
1025 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1026 gp_XYZ _edgeDir;// EDGE tangent at _param
1027 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1029 vector< OffPnt > _offPoints;
1030 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1031 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1032 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1033 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1034 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1035 _EdgesOnShape& _eos;
1036 double _curveLen; // length of the EDGE
1038 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1040 SMESH_MesherHelper& helper);
1042 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1043 _EdgesOnShape& eos )
1044 : _anaCurve( curveForSmooth ), _eos( eos )
1047 bool Perform(_SolidData& data,
1048 Handle(ShapeAnalysis_Surface)& surface,
1049 const TopoDS_Face& F,
1050 SMESH_MesherHelper& helper )
1052 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1056 return smoothAnalyticEdge( data, surface, F, helper );
1058 return smoothComplexEdge ( data, surface, F, helper );
1060 void prepare(_SolidData& data );
1062 bool smoothAnalyticEdge( _SolidData& data,
1063 Handle(ShapeAnalysis_Surface)& surface,
1064 const TopoDS_Face& F,
1065 SMESH_MesherHelper& helper);
1067 bool smoothComplexEdge( _SolidData& data,
1068 Handle(ShapeAnalysis_Surface)& surface,
1069 const TopoDS_Face& F,
1070 SMESH_MesherHelper& helper);
1072 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1073 const gp_XYZ& edgeDir);
1075 _LayerEdge* getLEdgeOnV( bool is2nd )
1077 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1079 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1081 //--------------------------------------------------------------------------------
1083 * \brief Class of temporary mesh face.
1084 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1085 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1087 struct _TmpMeshFace : public SMDS_MeshElement
1089 vector<const SMDS_MeshNode* > _nn;
1090 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1091 int id, int faceID=-1, int idInFace=-1):
1092 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1093 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1094 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1095 virtual vtkIdType GetVtkType() const { return -1; }
1096 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1097 virtual SMDSAbs_GeometryType GetGeomType() const
1098 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1099 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1100 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1102 //--------------------------------------------------------------------------------
1104 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1106 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1108 _LayerEdge *_le1, *_le2;
1109 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1110 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1112 _nn[0]=_le1->_nodes[0];
1113 _nn[1]=_le1->_nodes.back();
1114 _nn[2]=_le2->_nodes.back();
1115 _nn[3]=_le2->_nodes[0];
1117 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1119 SMESH_TNodeXYZ p0s( _nn[0] );
1120 SMESH_TNodeXYZ p0t( _nn[1] );
1121 SMESH_TNodeXYZ p1t( _nn[2] );
1122 SMESH_TNodeXYZ p1s( _nn[3] );
1123 gp_XYZ v0 = p0t - p0s;
1124 gp_XYZ v1 = p1t - p1s;
1125 gp_XYZ v01 = p1s - p0s;
1126 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1131 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1133 _nn[0]=le1->_nodes[0];
1134 _nn[1]=le1->_nodes.back();
1135 _nn[2]=le2->_nodes.back();
1136 _nn[3]=le2->_nodes[0];
1140 //--------------------------------------------------------------------------------
1142 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1143 * \warning Location of a surface is ignored
1145 struct _NodeCoordHelper
1147 SMESH_MesherHelper& _helper;
1148 const TopoDS_Face& _face;
1149 Handle(Geom_Surface) _surface;
1150 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1152 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1153 : _helper( helper ), _face( F )
1157 TopLoc_Location loc;
1158 _surface = BRep_Tool::Surface( _face, loc );
1160 if ( _surface.IsNull() )
1161 _fun = & _NodeCoordHelper::direct;
1163 _fun = & _NodeCoordHelper::byUV;
1165 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1168 gp_XYZ direct(const SMDS_MeshNode* n) const
1170 return SMESH_TNodeXYZ( n );
1172 gp_XYZ byUV (const SMDS_MeshNode* n) const
1174 gp_XY uv = _helper.GetNodeUV( _face, n );
1175 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1179 //================================================================================
1181 * \brief Check angle between vectors
1183 //================================================================================
1185 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1187 double dot = v1 * v2; // cos * |v1| * |v2|
1188 double l1 = v1.SquareMagnitude();
1189 double l2 = v2.SquareMagnitude();
1190 return (( dot * cos >= 0 ) &&
1191 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1194 } // namespace VISCOUS_3D
1198 //================================================================================
1199 // StdMeshers_ViscousLayers hypothesis
1201 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1202 :SMESH_Hypothesis(hypId, studyId, gen),
1203 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1204 _method( SURF_OFFSET_SMOOTH )
1206 _name = StdMeshers_ViscousLayers::GetHypType();
1207 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1211 if ( faceIds != _shapeIds )
1212 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1213 if ( _isToIgnoreShapes != toIgnore )
1214 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1215 } // --------------------------------------------------------------------------------
1216 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1218 if ( thickness != _thickness )
1219 _thickness = thickness, NotifySubMeshesHypothesisModification();
1220 } // --------------------------------------------------------------------------------
1221 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1223 if ( _nbLayers != nb )
1224 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1225 } // --------------------------------------------------------------------------------
1226 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1228 if ( _stretchFactor != factor )
1229 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1230 } // --------------------------------------------------------------------------------
1231 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1233 if ( _method != method )
1234 _method = method, NotifySubMeshesHypothesisModification();
1235 } // --------------------------------------------------------------------------------
1236 SMESH_ProxyMesh::Ptr
1237 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1238 const TopoDS_Shape& theShape,
1239 const bool toMakeN2NMap) const
1241 using namespace VISCOUS_3D;
1242 _ViscousBuilder builder;
1243 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1244 if ( err && !err->IsOK() )
1245 return SMESH_ProxyMesh::Ptr();
1247 vector<SMESH_ProxyMesh::Ptr> components;
1248 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1249 for ( ; exp.More(); exp.Next() )
1251 if ( _MeshOfSolid* pm =
1252 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1254 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1255 if ( !builder.MakeN2NMap( pm ))
1256 return SMESH_ProxyMesh::Ptr();
1257 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1258 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1260 if ( pm->_warning && !pm->_warning->IsOK() )
1262 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1263 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1264 if ( !smError || smError->IsOK() )
1265 smError = pm->_warning;
1268 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1270 switch ( components.size() )
1274 case 1: return components[0];
1276 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1278 return SMESH_ProxyMesh::Ptr();
1279 } // --------------------------------------------------------------------------------
1280 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1282 save << " " << _nbLayers
1283 << " " << _thickness
1284 << " " << _stretchFactor
1285 << " " << _shapeIds.size();
1286 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1287 save << " " << _shapeIds[i];
1288 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1289 save << " " << _method;
1291 } // --------------------------------------------------------------------------------
1292 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1294 int nbFaces, faceID, shapeToTreat, method;
1295 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1296 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1297 _shapeIds.push_back( faceID );
1298 if ( load >> shapeToTreat ) {
1299 _isToIgnoreShapes = !shapeToTreat;
1300 if ( load >> method )
1301 _method = (ExtrusionMethod) method;
1304 _isToIgnoreShapes = true; // old behavior
1307 } // --------------------------------------------------------------------------------
1308 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1309 const TopoDS_Shape& theShape)
1313 } // --------------------------------------------------------------------------------
1314 SMESH_ComputeErrorPtr
1315 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1316 const TopoDS_Shape& theShape,
1317 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1319 VISCOUS_3D::_ViscousBuilder builder;
1320 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1321 if ( err && !err->IsOK() )
1322 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1324 theStatus = SMESH_Hypothesis::HYP_OK;
1328 // --------------------------------------------------------------------------------
1329 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1332 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1333 return IsToIgnoreShapes() ? !isIn : isIn;
1335 // END StdMeshers_ViscousLayers hypothesis
1336 //================================================================================
1338 namespace VISCOUS_3D
1340 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1344 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1345 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1346 gp_Pnt p = BRep_Tool::Pnt( fromV );
1347 double distF = p.SquareDistance( c->Value( f ));
1348 double distL = p.SquareDistance( c->Value( l ));
1349 c->D1(( distF < distL ? f : l), p, dir );
1350 if ( distL < distF ) dir.Reverse();
1353 //--------------------------------------------------------------------------------
1354 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1355 SMESH_MesherHelper& helper)
1358 double f,l; gp_Pnt p;
1359 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1360 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1361 double u = helper.GetNodeU( E, atNode );
1365 //--------------------------------------------------------------------------------
1366 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1367 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1369 //--------------------------------------------------------------------------------
1370 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1371 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1374 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1377 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1378 return getFaceDir( F, v, node, helper, ok );
1380 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1381 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1382 gp_Pnt p; gp_Vec du, dv, norm;
1383 surface->D1( uv.X(),uv.Y(), p, du,dv );
1386 double u = helper.GetNodeU( fromE, node, 0, &ok );
1388 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1389 if ( o == TopAbs_REVERSED )
1392 gp_Vec dir = norm ^ du;
1394 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1395 helper.IsClosedEdge( fromE ))
1397 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1398 else c->D1( f, p, dv );
1399 if ( o == TopAbs_REVERSED )
1401 gp_Vec dir2 = norm ^ dv;
1402 dir = dir.Normalized() + dir2.Normalized();
1406 //--------------------------------------------------------------------------------
1407 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1408 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1409 bool& ok, double* cosin)
1411 TopoDS_Face faceFrw = F;
1412 faceFrw.Orientation( TopAbs_FORWARD );
1413 //double f,l; TopLoc_Location loc;
1414 TopoDS_Edge edges[2]; // sharing a vertex
1417 TopoDS_Vertex VV[2];
1418 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1419 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1421 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1422 if ( SMESH_Algo::isDegenerated( e )) continue;
1423 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1424 if ( VV[1].IsSame( fromV )) {
1425 nbEdges += edges[ 0 ].IsNull();
1428 else if ( VV[0].IsSame( fromV )) {
1429 nbEdges += edges[ 1 ].IsNull();
1434 gp_XYZ dir(0,0,0), edgeDir[2];
1437 // get dirs of edges going fromV
1439 for ( size_t i = 0; i < nbEdges && ok; ++i )
1441 edgeDir[i] = getEdgeDir( edges[i], fromV );
1442 double size2 = edgeDir[i].SquareModulus();
1443 if (( ok = size2 > numeric_limits<double>::min() ))
1444 edgeDir[i] /= sqrt( size2 );
1446 if ( !ok ) return dir;
1448 // get angle between the 2 edges
1450 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1451 if ( Abs( angle ) < 5 * M_PI/180 )
1453 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1457 dir = edgeDir[0] + edgeDir[1];
1462 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1463 *cosin = Cos( angle );
1466 else if ( nbEdges == 1 )
1468 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1469 if ( cosin ) *cosin = 1.;
1479 //================================================================================
1481 * \brief Finds concave VERTEXes of a FACE
1483 //================================================================================
1485 bool getConcaveVertices( const TopoDS_Face& F,
1486 SMESH_MesherHelper& helper,
1487 set< TGeomID >* vertices = 0)
1489 // check angles at VERTEXes
1491 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1492 for ( size_t iW = 0; iW < wires.size(); ++iW )
1494 const int nbEdges = wires[iW]->NbEdges();
1495 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1497 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1499 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1500 int iE2 = ( iE1 + 1 ) % nbEdges;
1501 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1502 iE2 = ( iE2 + 1 ) % nbEdges;
1503 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1504 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1505 wires[iW]->Edge( iE2 ), F, V );
1506 if ( angle < -5. * M_PI / 180. )
1510 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1514 return vertices ? !vertices->empty() : false;
1517 //================================================================================
1519 * \brief Returns true if a FACE is bound by a concave EDGE
1521 //================================================================================
1523 bool isConcave( const TopoDS_Face& F,
1524 SMESH_MesherHelper& helper,
1525 set< TGeomID >* vertices = 0 )
1527 bool isConcv = false;
1528 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1530 gp_Vec2d drv1, drv2;
1532 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1533 for ( ; eExp.More(); eExp.Next() )
1535 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1536 if ( SMESH_Algo::isDegenerated( E )) continue;
1537 // check if 2D curve is concave
1538 BRepAdaptor_Curve2d curve( E, F );
1539 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1540 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1541 curve.Intervals( intervals, GeomAbs_C2 );
1542 bool isConvex = true;
1543 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1545 double u1 = intervals( i );
1546 double u2 = intervals( i+1 );
1547 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1548 double cross = drv1 ^ drv2;
1549 if ( E.Orientation() == TopAbs_REVERSED )
1551 isConvex = ( cross > -1e-9 ); // 0.1 );
1555 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1564 // check angles at VERTEXes
1565 if ( getConcaveVertices( F, helper, vertices ))
1571 //================================================================================
1573 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1574 * \param [in] face - the mesh face to treat
1575 * \param [in] nodeOnEdge - a node on the EDGE
1576 * \param [out] faceSize - the computed distance
1577 * \return bool - true if faceSize computed
1579 //================================================================================
1581 bool getDistFromEdge( const SMDS_MeshElement* face,
1582 const SMDS_MeshNode* nodeOnEdge,
1585 faceSize = Precision::Infinite();
1588 int nbN = face->NbCornerNodes();
1589 int iOnE = face->GetNodeIndex( nodeOnEdge );
1590 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1591 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1592 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1593 face->GetNode( iNext[1] ) };
1594 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1595 double segLen = -1.;
1596 // look for two neighbor not in-FACE nodes of face
1597 for ( int i = 0; i < 2; ++i )
1599 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1600 nNext[i]->GetID() < nodeOnEdge->GetID() )
1602 // look for an in-FACE node
1603 for ( int iN = 0; iN < nbN; ++iN )
1605 if ( iN == iOnE || iN == iNext[i] )
1607 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1608 gp_XYZ v = pInFace - segEnd;
1611 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1612 segLen = segVec.Modulus();
1614 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1615 faceSize = Min( faceSize, distToSeg );
1623 //================================================================================
1625 * \brief Return direction of axis or revolution of a surface
1627 //================================================================================
1629 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1632 switch ( surface.GetType() ) {
1635 gp_Cone cone = surface.Cone();
1636 axis = cone.Axis().Direction();
1639 case GeomAbs_Sphere:
1641 gp_Sphere sphere = surface.Sphere();
1642 axis = sphere.Position().Direction();
1645 case GeomAbs_SurfaceOfRevolution:
1647 axis = surface.AxeOfRevolution().Direction();
1650 //case GeomAbs_SurfaceOfExtrusion:
1651 case GeomAbs_OffsetSurface:
1653 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1654 return getRovolutionAxis( base->Surface(), axis );
1656 default: return false;
1661 //--------------------------------------------------------------------------------
1662 // DEBUG. Dump intermediate node positions into a python script
1663 // HOWTO use: run python commands written in a console to see
1664 // construction steps of viscous layers
1669 PyDump(SMESH_Mesh& m) {
1670 int tag = 3 + m.GetId();
1671 const char* fname = "/tmp/viscous.py";
1672 cout << "execfile('"<<fname<<"')"<<endl;
1673 py = new ofstream(fname);
1674 *py << "import SMESH" << endl
1675 << "from salome.smesh import smeshBuilder" << endl
1676 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1677 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1678 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1683 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1684 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1685 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1686 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1690 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1692 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1693 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1694 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1695 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1696 void _dumpFunction(const string& fun, int ln)
1697 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1698 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1699 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1700 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1701 void _dumpCmd(const string& txt, int ln)
1702 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1703 void dumpFunctionEnd()
1704 { if (py) *py<< " return"<< endl; }
1705 void dumpChangeNodes( const SMDS_MeshElement* f )
1706 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1707 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1708 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1709 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1713 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1714 #define dumpFunction(f) f
1716 #define dumpMoveComm(n,txt)
1717 #define dumpCmd(txt)
1718 #define dumpFunctionEnd()
1719 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1720 #define debugMsg( txt ) {}
1725 using namespace VISCOUS_3D;
1727 //================================================================================
1729 * \brief Constructor of _ViscousBuilder
1731 //================================================================================
1733 _ViscousBuilder::_ViscousBuilder()
1735 _error = SMESH_ComputeError::New(COMPERR_OK);
1739 //================================================================================
1741 * \brief Stores error description and returns false
1743 //================================================================================
1745 bool _ViscousBuilder::error(const string& text, int solidId )
1747 const string prefix = string("Viscous layers builder: ");
1748 _error->myName = COMPERR_ALGO_FAILED;
1749 _error->myComment = prefix + text;
1752 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1753 if ( !sm && !_sdVec.empty() )
1754 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1755 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1757 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1758 if ( smError && smError->myAlgo )
1759 _error->myAlgo = smError->myAlgo;
1761 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1763 // set KO to all solids
1764 for ( size_t i = 0; i < _sdVec.size(); ++i )
1766 if ( _sdVec[i]._index == solidId )
1768 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1769 if ( !sm->IsEmpty() )
1771 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1772 if ( !smError || smError->IsOK() )
1774 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1775 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1779 makeGroupOfLE(); // debug
1784 //================================================================================
1786 * \brief At study restoration, restore event listeners used to clear an inferior
1787 * dim sub-mesh modified by viscous layers
1789 //================================================================================
1791 void _ViscousBuilder::RestoreListeners()
1796 //================================================================================
1798 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1800 //================================================================================
1802 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1804 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1805 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1806 for ( ; fExp.More(); fExp.Next() )
1808 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1809 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1811 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1813 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1816 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1817 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1819 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1820 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1821 while( prxIt->more() )
1823 const SMDS_MeshElement* fSrc = srcIt->next();
1824 const SMDS_MeshElement* fPrx = prxIt->next();
1825 if ( fSrc->NbNodes() != fPrx->NbNodes())
1826 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1827 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1828 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1831 pm->_n2nMapComputed = true;
1835 //================================================================================
1837 * \brief Does its job
1839 //================================================================================
1841 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1842 const TopoDS_Shape& theShape)
1846 // check if proxy mesh already computed
1847 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1849 return error("No SOLID's in theShape"), _error;
1851 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1852 return SMESH_ComputeErrorPtr(); // everything already computed
1854 PyDump debugDump( theMesh );
1856 // TODO: ignore already computed SOLIDs
1857 if ( !findSolidsWithLayers())
1860 if ( !findFacesWithLayers() )
1863 for ( size_t i = 0; i < _sdVec.size(); ++i )
1866 for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1867 if ( _sdVec[iSD]._before.IsEmpty() &&
1868 _sdVec[iSD]._n2eMap.empty() )
1871 if ( ! makeLayer(_sdVec[iSD]) ) // create _LayerEdge's
1874 if ( _sdVec[iSD]._n2eMap.size() == 0 )
1877 if ( ! inflate(_sdVec[iSD]) ) // increase length of _LayerEdge's
1880 if ( ! refine(_sdVec[iSD]) ) // create nodes and prisms
1883 if ( ! shrink(_sdVec[iSD]) ) // shrink 2D mesh on FACEs w/o layer
1886 addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1888 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1889 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1890 _sdVec[iSD]._before.Remove( solid );
1893 makeGroupOfLE(); // debug
1899 //================================================================================
1901 * \brief Check validity of hypotheses
1903 //================================================================================
1905 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1906 const TopoDS_Shape& shape )
1910 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1911 return SMESH_ComputeErrorPtr(); // everything already computed
1914 findSolidsWithLayers();
1915 bool ok = findFacesWithLayers( true );
1917 // remove _MeshOfSolid's of _SolidData's
1918 for ( size_t i = 0; i < _sdVec.size(); ++i )
1919 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1924 return SMESH_ComputeErrorPtr();
1927 //================================================================================
1929 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1931 //================================================================================
1933 bool _ViscousBuilder::findSolidsWithLayers()
1936 TopTools_IndexedMapOfShape allSolids;
1937 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1938 _sdVec.reserve( allSolids.Extent());
1940 SMESH_HypoFilter filter;
1941 for ( int i = 1; i <= allSolids.Extent(); ++i )
1943 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1944 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1945 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1946 continue; // solid is already meshed
1947 SMESH_Algo* algo = sm->GetAlgo();
1948 if ( !algo ) continue;
1949 // TODO: check if algo is hidden
1950 const list <const SMESHDS_Hypothesis *> & allHyps =
1951 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1952 _SolidData* soData = 0;
1953 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1954 const StdMeshers_ViscousLayers* viscHyp = 0;
1955 for ( ; hyp != allHyps.end(); ++hyp )
1956 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1958 TopoDS_Shape hypShape;
1959 filter.Init( filter.Is( viscHyp ));
1960 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1964 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1967 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1968 soData = & _sdVec.back();
1969 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1970 soData->_helper = new SMESH_MesherHelper( *_mesh );
1971 soData->_helper->SetSubShape( allSolids(i) );
1972 _solids.Add( allSolids(i) );
1974 soData->_hyps.push_back( viscHyp );
1975 soData->_hypShapes.push_back( hypShape );
1978 if ( _sdVec.empty() )
1980 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1985 //================================================================================
1987 * \brief Set a _SolidData to be computed before another
1989 //================================================================================
1991 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1993 // check possibility to set this order; get all solids before solidBefore
1994 TopTools_IndexedMapOfShape allSolidsBefore;
1995 allSolidsBefore.Add( solidBefore._solid );
1996 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1998 int iSD = _solids.FindIndex( allSolidsBefore(i) );
2001 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2002 for ( ; soIt.More(); soIt.Next() )
2003 allSolidsBefore.Add( soIt.Value() );
2006 if ( allSolidsBefore.Contains( solidAfter._solid ))
2009 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2010 solidAfter._before.Add( allSolidsBefore(i) );
2015 //================================================================================
2019 //================================================================================
2021 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2023 SMESH_MesherHelper helper( *_mesh );
2024 TopExp_Explorer exp;
2026 // collect all faces-to-ignore defined by hyp
2027 for ( size_t i = 0; i < _sdVec.size(); ++i )
2029 // get faces-to-ignore defined by each hyp
2030 typedef const StdMeshers_ViscousLayers* THyp;
2031 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2032 list< TFacesOfHyp > ignoreFacesOfHyps;
2033 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2034 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2035 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2037 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2038 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2041 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2042 const int nbHyps = _sdVec[i]._hyps.size();
2045 // check if two hypotheses define different parameters for the same FACE
2046 list< TFacesOfHyp >::iterator igFacesOfHyp;
2047 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2049 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2051 igFacesOfHyp = ignoreFacesOfHyps.begin();
2052 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2053 if ( ! igFacesOfHyp->first.count( faceID ))
2056 return error(SMESH_Comment("Several hypotheses define "
2057 "Viscous Layers on the face #") << faceID );
2058 hyp = igFacesOfHyp->second;
2061 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2063 _sdVec[i]._ignoreFaceIds.insert( faceID );
2066 // check if two hypotheses define different number of viscous layers for
2067 // adjacent faces of a solid
2068 set< int > nbLayersSet;
2069 igFacesOfHyp = ignoreFacesOfHyps.begin();
2070 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2072 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2074 if ( nbLayersSet.size() > 1 )
2076 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2078 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2079 THyp hyp1 = 0, hyp2 = 0;
2080 while( const TopoDS_Shape* face = fIt->next() )
2082 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2083 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2084 if ( f2h != _sdVec[i]._face2hyp.end() )
2086 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2089 if ( hyp1 && hyp2 &&
2090 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2092 return error("Two hypotheses define different number of "
2093 "viscous layers on adjacent faces");
2097 } // if ( nbHyps > 1 )
2100 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2104 if ( onlyWith ) // is called to check hypotheses compatibility only
2107 // fill _SolidData::_reversedFaceIds
2108 for ( size_t i = 0; i < _sdVec.size(); ++i )
2110 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2111 for ( ; exp.More(); exp.Next() )
2113 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2114 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2115 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2116 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2117 helper.IsReversedSubMesh( face ))
2119 _sdVec[i]._reversedFaceIds.insert( faceID );
2124 // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2125 TopTools_IndexedMapOfShape shapes;
2126 std::string structAlgoName = "Hexa_3D";
2127 for ( size_t i = 0; i < _sdVec.size(); ++i )
2130 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2131 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2133 const TopoDS_Shape& edge = shapes(iE);
2134 // find 2 FACEs sharing an EDGE
2136 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2137 while ( fIt->more())
2139 const TopoDS_Shape* f = fIt->next();
2140 FF[ int( !FF[0].IsNull()) ] = *f;
2142 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2144 // check presence of layers on them
2146 for ( int j = 0; j < 2; ++j )
2147 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2148 if ( ignore[0] == ignore[1] )
2149 continue; // nothing interesting
2150 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2153 if ( !fWOL.IsNull())
2155 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2156 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2161 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2163 for ( size_t i = 0; i < _sdVec.size(); ++i )
2166 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2167 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2169 const TopoDS_Shape& vertex = shapes(iV);
2170 // find faces WOL sharing the vertex
2171 vector< TopoDS_Shape > facesWOL;
2172 size_t totalNbFaces = 0;
2173 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2174 while ( fIt->more())
2176 const TopoDS_Shape* f = fIt->next();
2178 const int fID = getMeshDS()->ShapeToIndex( *f );
2179 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2180 facesWOL.push_back( *f );
2182 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2183 continue; // no layers at this vertex or no WOL
2184 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2185 switch ( facesWOL.size() )
2189 helper.SetSubShape( facesWOL[0] );
2190 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2192 TopoDS_Shape seamEdge;
2193 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2194 while ( eIt->more() && seamEdge.IsNull() )
2196 const TopoDS_Shape* e = eIt->next();
2197 if ( helper.IsRealSeam( *e ) )
2200 if ( !seamEdge.IsNull() )
2202 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2206 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2211 // find an edge shared by 2 faces
2212 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2213 while ( eIt->more())
2215 const TopoDS_Shape* e = eIt->next();
2216 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2217 helper.IsSubShape( *e, facesWOL[1]))
2219 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2225 return error("Not yet supported case", _sdVec[i]._index);
2230 // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2231 // the algo of the SOLID sharing the FACE does not support it or for other reasons
2232 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2233 for ( size_t i = 0; i < _sdVec.size(); ++i )
2235 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2236 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2238 const TopoDS_Shape& fWOL = e2f->second;
2239 const TGeomID edgeID = e2f->first;
2240 TGeomID faceID = getMeshDS()->ShapeToIndex( fWOL );
2241 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2242 if ( edge.ShapeType() != TopAbs_EDGE )
2243 continue; // shrink shape is VERTEX
2246 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2247 while ( soIt->more() && solid.IsNull() )
2249 const TopoDS_Shape* so = soIt->next();
2250 if ( !so->IsSame( _sdVec[i]._solid ))
2253 if ( solid.IsNull() )
2256 bool noShrinkE = false;
2257 SMESH_Algo* algo = _mesh->GetSubMesh( solid )->GetAlgo();
2258 bool isStructured = ( algo && algo->GetName() == structAlgoName );
2259 size_t iSolid = _solids.FindIndex( solid ) - 1;
2260 if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2262 // the adjacent SOLID has NO layers on fWOL;
2263 // shrink allowed if
2264 // - there are layers on the EDGE in the adjacent SOLID
2265 // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2266 bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2267 bool shrinkAllowed = (( hasWLAdj ) ||
2268 ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2269 noShrinkE = !shrinkAllowed;
2271 else if ( iSolid < _sdVec.size() )
2273 // the adjacent SOLID has layers on fWOL;
2274 // check if SOLID's mesh is unstructured and then try to set it
2275 // to be computed after the i-th solid
2276 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2277 noShrinkE = true; // don't shrink fWOL
2281 // the adjacent SOLID has NO layers at all
2282 noShrinkE = isStructured;
2287 _sdVec[i]._noShrinkShapes.insert( edgeID );
2289 // check if there is a collision with to-shrink-from EDGEs in iSolid
2290 // if ( iSolid < _sdVec.size() )
2293 // TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2294 // for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2296 // const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2297 // const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2298 // if ( eID == edgeID ||
2299 // !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2300 // _sdVec[i]._noShrinkShapes.count( eID ))
2302 // for ( int is1st = 0; is1st < 2; ++is1st )
2304 // TopoDS_Vertex V = helper.IthVertex( is1st, E );
2305 // if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2307 // return error("No way to make a conformal mesh with "
2308 // "the given set of faces with layers", _sdVec[i]._index);
2315 // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2316 // _shrinkShape2Shape is different in the adjacent SOLID
2317 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2319 TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2320 bool noShrinkV = false;
2322 if ( iSolid < _sdVec.size() )
2324 if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2326 map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2327 i2S = _sdVec[i ]._shrinkShape2Shape.find( vID );
2328 i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2329 if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2330 noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2332 noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2336 noShrinkV = noShrinkE;
2341 // the adjacent SOLID has NO layers at all
2342 noShrinkV = ( isStructured ||
2343 _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2346 _sdVec[i]._noShrinkShapes.insert( vID );
2349 } // loop on _sdVec[i]._shrinkShape2Shape
2350 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2353 // add FACEs of other SOLIDs to _ignoreFaceIds
2354 for ( size_t i = 0; i < _sdVec.size(); ++i )
2357 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2359 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2361 if ( !shapes.Contains( exp.Current() ))
2362 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2369 //================================================================================
2371 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2373 //================================================================================
2375 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2376 const StdMeshers_ViscousLayers* hyp,
2377 const TopoDS_Shape& hypShape,
2378 set<TGeomID>& ignoreFaceIds)
2380 TopExp_Explorer exp;
2382 vector<TGeomID> ids = hyp->GetBndShapes();
2383 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2385 for ( size_t ii = 0; ii < ids.size(); ++ii )
2387 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2388 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2389 ignoreFaceIds.insert( ids[ii] );
2392 else // FACEs with layers are given
2394 exp.Init( solid, TopAbs_FACE );
2395 for ( ; exp.More(); exp.Next() )
2397 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2398 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2399 ignoreFaceIds.insert( faceInd );
2403 // ignore internal FACEs if inlets and outlets are specified
2404 if ( hyp->IsToIgnoreShapes() )
2406 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2407 TopExp::MapShapesAndAncestors( hypShape,
2408 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2410 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2412 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2413 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2416 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2418 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2423 //================================================================================
2425 * \brief Create the inner surface of the viscous layer and prepare data for infation
2427 //================================================================================
2429 bool _ViscousBuilder::makeLayer(_SolidData& data)
2431 // get all sub-shapes to make layers on
2432 set<TGeomID> subIds, faceIds;
2433 subIds = data._noShrinkShapes;
2434 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2435 for ( ; exp.More(); exp.Next() )
2437 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2438 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2439 faceIds.insert( fSubM->GetId() );
2442 // make a map to find new nodes on sub-shapes shared with other SOLID
2443 map< TGeomID, TNode2Edge* >::iterator s2ne;
2444 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2445 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2447 TGeomID shapeInd = s2s->first;
2448 for ( size_t i = 0; i < _sdVec.size(); ++i )
2450 if ( _sdVec[i]._index == data._index ) continue;
2451 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2452 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2453 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2455 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2461 // Create temporary faces and _LayerEdge's
2463 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2465 data._stepSize = Precision::Infinite();
2466 data._stepSizeNodes[0] = 0;
2468 SMESH_MesherHelper helper( *_mesh );
2469 helper.SetSubShape( data._solid );
2470 helper.SetElementsOnShape( true );
2472 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2473 TNode2Edge::iterator n2e2;
2475 // collect _LayerEdge's of shapes they are based on
2476 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2477 const int nbShapes = getMeshDS()->MaxShapeIndex();
2478 edgesByGeom.resize( nbShapes+1 );
2480 // set data of _EdgesOnShape's
2481 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2483 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2484 while ( smIt->more() )
2487 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2488 !faceIds.count( sm->GetId() ))
2490 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2493 // make _LayerEdge's
2494 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2496 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2497 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2498 SMESH_ProxyMesh::SubMesh* proxySub =
2499 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2501 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2502 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2504 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2505 while ( eIt->more() )
2507 const SMDS_MeshElement* face = eIt->next();
2508 double faceMaxCosin = -1;
2509 _LayerEdge* maxCosinEdge = 0;
2510 int nbDegenNodes = 0;
2512 newNodes.resize( face->NbCornerNodes() );
2513 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2515 const SMDS_MeshNode* n = face->GetNode( i );
2516 const int shapeID = n->getshapeId();
2517 const bool onDegenShap = helper.IsDegenShape( shapeID );
2518 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2523 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2524 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2525 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2526 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2536 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2537 if ( !(*n2e).second )
2540 _LayerEdge* edge = new _LayerEdge();
2541 edge->_nodes.push_back( n );
2543 edgesByGeom[ shapeID ]._edges.push_back( edge );
2544 const bool noShrink = data._noShrinkShapes.count( shapeID );
2546 SMESH_TNodeXYZ xyz( n );
2548 // set edge data or find already refined _LayerEdge and get data from it
2549 if (( !noShrink ) &&
2550 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2551 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2552 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2554 _LayerEdge* foundEdge = (*n2e2).second;
2555 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2556 foundEdge->_pos.push_back( lastPos );
2557 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2558 const_cast< SMDS_MeshNode* >
2559 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2565 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2567 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2570 if ( edge->_nodes.size() < 2 )
2571 edge->Block( data );
2572 //data._noShrinkShapes.insert( shapeID );
2574 dumpMove(edge->_nodes.back());
2576 if ( edge->_cosin > faceMaxCosin )
2578 faceMaxCosin = edge->_cosin;
2579 maxCosinEdge = edge;
2582 newNodes[ i ] = n2e->second->_nodes.back();
2585 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2587 if ( newNodes.size() - nbDegenNodes < 2 )
2590 // create a temporary face
2591 const SMDS_MeshElement* newFace =
2592 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2593 proxySub->AddElement( newFace );
2595 // compute inflation step size by min size of element on a convex surface
2596 if ( faceMaxCosin > theMinSmoothCosin )
2597 limitStepSize( data, face, maxCosinEdge );
2599 } // loop on 2D elements on a FACE
2600 } // loop on FACEs of a SOLID to create _LayerEdge's
2603 // Set _LayerEdge::_neibors
2604 TNode2Edge::iterator n2e;
2605 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2607 _EdgesOnShape& eos = data._edgesOnShape[iS];
2608 for ( size_t i = 0; i < eos._edges.size(); ++i )
2610 _LayerEdge* edge = eos._edges[i];
2611 TIDSortedNodeSet nearNodes;
2612 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2613 while ( fIt->more() )
2615 const SMDS_MeshElement* f = fIt->next();
2616 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2617 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2619 nearNodes.erase( edge->_nodes[0] );
2620 edge->_neibors.reserve( nearNodes.size() );
2621 TIDSortedNodeSet::iterator node = nearNodes.begin();
2622 for ( ; node != nearNodes.end(); ++node )
2623 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2624 edge->_neibors.push_back( n2e->second );
2628 data._epsilon = 1e-7;
2629 if ( data._stepSize < 1. )
2630 data._epsilon *= data._stepSize;
2632 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2635 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2636 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2638 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2639 const SMDS_MeshNode* nn[2];
2640 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2642 _EdgesOnShape& eos = data._edgesOnShape[iS];
2643 for ( size_t i = 0; i < eos._edges.size(); ++i )
2645 _LayerEdge* edge = eos._edges[i];
2646 if ( edge->IsOnEdge() )
2648 // get neighbor nodes
2649 bool hasData = ( edge->_2neibors->_edges[0] );
2650 if ( hasData ) // _LayerEdge is a copy of another one
2652 nn[0] = edge->_2neibors->srcNode(0);
2653 nn[1] = edge->_2neibors->srcNode(1);
2655 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2659 // set neighbor _LayerEdge's
2660 for ( int j = 0; j < 2; ++j )
2662 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2663 return error("_LayerEdge not found by src node", data._index);
2664 edge->_2neibors->_edges[j] = n2e->second;
2667 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2670 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2672 _Simplex& s = edge->_simplices[j];
2673 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2674 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2677 // For an _LayerEdge on a degenerated EDGE, copy some data from
2678 // a corresponding _LayerEdge on a VERTEX
2679 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2680 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2682 // Generally we should not get here
2683 if ( eos.ShapeType() != TopAbs_EDGE )
2685 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2686 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2687 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2689 const _LayerEdge* vEdge = n2e->second;
2690 edge->_normal = vEdge->_normal;
2691 edge->_lenFactor = vEdge->_lenFactor;
2692 edge->_cosin = vEdge->_cosin;
2695 } // loop on data._edgesOnShape._edges
2696 } // loop on data._edgesOnShape
2698 // fix _LayerEdge::_2neibors on EDGEs to smooth
2699 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2700 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2701 // if ( !e2c->second.IsNull() )
2703 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2704 // data.Sort2NeiborsOnEdge( eos->_edges );
2711 //================================================================================
2713 * \brief Compute inflation step size by min size of element on a convex surface
2715 //================================================================================
2717 void _ViscousBuilder::limitStepSize( _SolidData& data,
2718 const SMDS_MeshElement* face,
2719 const _LayerEdge* maxCosinEdge )
2722 double minSize = 10 * data._stepSize;
2723 const int nbNodes = face->NbCornerNodes();
2724 for ( int i = 0; i < nbNodes; ++i )
2726 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2727 const SMDS_MeshNode* curN = face->GetNode( i );
2728 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2729 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2731 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2732 if ( dist < minSize )
2733 minSize = dist, iN = i;
2736 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2737 if ( newStep < data._stepSize )
2739 data._stepSize = newStep;
2740 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2741 data._stepSizeNodes[0] = face->GetNode( iN );
2742 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2746 //================================================================================
2748 * \brief Compute inflation step size by min size of element on a convex surface
2750 //================================================================================
2752 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2754 if ( minSize < data._stepSize )
2756 data._stepSize = minSize;
2757 if ( data._stepSizeNodes[0] )
2760 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2761 data._stepSizeCoeff = data._stepSize / dist;
2766 //================================================================================
2768 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2770 //================================================================================
2772 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2774 SMESH_MesherHelper helper( *_mesh );
2776 const int nbTestPnt = 5; // on a FACE sub-shape
2778 BRepLProp_SLProps surfProp( 2, 1e-6 );
2779 data._convexFaces.clear();
2781 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2783 _EdgesOnShape& eof = data._edgesOnShape[iS];
2784 if ( eof.ShapeType() != TopAbs_FACE ||
2785 data._ignoreFaceIds.count( eof._shapeID ))
2788 TopoDS_Face F = TopoDS::Face( eof._shape );
2789 SMESH_subMesh * sm = eof._subMesh;
2790 const TGeomID faceID = eof._shapeID;
2792 BRepAdaptor_Surface surface( F, false );
2793 surfProp.SetSurface( surface );
2795 bool isTooCurved = false;
2797 _ConvexFace cnvFace;
2798 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2799 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2800 while ( smIt->more() )
2803 const TGeomID subID = sm->GetId();
2804 // find _LayerEdge's of a sub-shape
2806 if (( eos = data.GetShapeEdges( subID )))
2807 cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2810 // check concavity and curvature and limit data._stepSize
2811 const double minCurvature =
2812 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2813 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2814 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2816 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2817 surfProp.SetParameters( uv.X(), uv.Y() );
2818 if ( !surfProp.IsCurvatureDefined() )
2820 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2822 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2825 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2827 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2831 } // loop on sub-shapes of the FACE
2833 if ( !isTooCurved ) continue;
2835 _ConvexFace & convFace =
2836 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2839 convFace._normalsFixed = false;
2841 // skip a closed surface (data._convexFaces is useful anyway)
2842 bool isClosedF = false;
2843 helper.SetSubShape( F );
2844 if ( helper.HasRealSeam() )
2846 // in the closed surface there must be a closed EDGE
2847 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2848 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2852 // limit _LayerEdge::_maxLen on the FACE
2853 const double minCurvature =
2854 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2855 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2856 if ( id2eos != cnvFace._subIdToEOS.end() )
2858 _EdgesOnShape& eos = * id2eos->second;
2859 for ( size_t i = 0; i < eos._edges.size(); ++i )
2861 _LayerEdge* ledge = eos._edges[ i ];
2862 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2863 surfProp.SetParameters( uv.X(), uv.Y() );
2864 if ( !surfProp.IsCurvatureDefined() )
2867 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2868 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2870 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2871 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2877 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2878 // prism distortion.
2879 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2880 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2882 // there are _LayerEdge's on the FACE it-self;
2883 // select _LayerEdge's near EDGEs
2884 _EdgesOnShape& eos = * id2eos->second;
2885 for ( size_t i = 0; i < eos._edges.size(); ++i )
2887 _LayerEdge* ledge = eos._edges[ i ];
2888 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2889 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2891 convFace._simplexTestEdges.push_back( ledge );
2898 // where there are no _LayerEdge's on a _ConvexFace,
2899 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2900 // so that collision of viscous internal faces is not detected by check of
2901 // intersection of _LayerEdge's with the viscous internal faces.
2903 set< const SMDS_MeshNode* > usedNodes;
2905 // look for _LayerEdge's with null _sWOL
2906 id2eos = convFace._subIdToEOS.begin();
2907 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2909 _EdgesOnShape& eos = * id2eos->second;
2910 if ( !eos._sWOL.IsNull() )
2912 for ( size_t i = 0; i < eos._edges.size(); ++i )
2914 _LayerEdge* ledge = eos._edges[ i ];
2915 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2916 if ( !usedNodes.insert( srcNode ).second ) continue;
2918 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2920 usedNodes.insert( ledge->_simplices[i]._nPrev );
2921 usedNodes.insert( ledge->_simplices[i]._nNext );
2923 convFace._simplexTestEdges.push_back( ledge );
2927 } // loop on FACEs of data._solid
2930 //================================================================================
2932 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2934 //================================================================================
2936 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2938 // define allowed thickness
2939 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2941 data._maxThickness = 0;
2942 data._minThickness = 1e100;
2943 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2944 for ( ; hyp != data._hyps.end(); ++hyp )
2946 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2947 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2949 //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2951 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2952 // boundry inclined to the shape at a sharp angle
2954 //list< TGeomID > shapesToSmooth;
2955 TopTools_MapOfShape edgesOfSmooFaces;
2957 SMESH_MesherHelper helper( *_mesh );
2960 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2961 data._nbShapesToSmooth = 0;
2963 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2965 _EdgesOnShape& eos = edgesByGeom[iS];
2966 eos._toSmooth = false;
2967 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2970 double tgtThick = eos._hyp.GetTotalThickness();
2971 TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2972 for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2974 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2975 vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2976 if ( eE.empty() ) continue;
2979 for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2980 if ( eE[i]->_cosin > theMinSmoothCosin )
2982 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2983 while ( fIt->more() && !eos._toSmooth )
2985 const SMDS_MeshElement* face = fIt->next();
2986 if ( face->getshapeId() == eos._shapeID &&
2987 getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2989 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2994 if ( eos._toSmooth )
2996 for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2997 edgesOfSmooFaces.Add( eExp.Current() );
2999 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3001 data._nbShapesToSmooth += eos._toSmooth;
3005 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3007 _EdgesOnShape& eos = edgesByGeom[iS];
3008 eos._edgeSmoother = NULL;
3009 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3010 if ( !eos._hyp.ToSmooth() ) continue;
3012 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3013 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3016 double tgtThick = eos._hyp.GetTotalThickness();
3017 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3019 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3020 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3021 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3022 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3023 double angle = eDir.Angle( eV[0]->_normal );
3024 double cosin = Cos( angle );
3025 double cosinAbs = Abs( cosin );
3026 if ( cosinAbs > theMinSmoothCosin )
3028 // always smooth analytic EDGEs
3029 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3030 eos._toSmooth = ! curve.IsNull();
3032 // compare tgtThick with the length of an end segment
3033 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3034 while ( eIt->more() && !eos._toSmooth )
3036 const SMDS_MeshElement* endSeg = eIt->next();
3037 if ( endSeg->getshapeId() == (int) iS )
3040 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3041 eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3044 if ( eos._toSmooth )
3046 eos._edgeSmoother = new _Smoother1D( curve, eos );
3048 for ( size_t i = 0; i < eos._edges.size(); ++i )
3049 eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3053 data._nbShapesToSmooth += eos._toSmooth;
3057 // Reset _cosin if no smooth is allowed by the user
3058 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3060 _EdgesOnShape& eos = edgesByGeom[iS];
3061 if ( eos._edges.empty() ) continue;
3063 if ( !eos._hyp.ToSmooth() )
3064 for ( size_t i = 0; i < eos._edges.size(); ++i )
3065 eos._edges[i]->SetCosin( 0 );
3069 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3071 TopTools_MapOfShape c1VV;
3073 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3075 _EdgesOnShape& eos = edgesByGeom[iS];
3076 if ( eos._edges.empty() ||
3077 eos.ShapeType() != TopAbs_FACE ||
3081 // check EDGEs of a FACE
3082 TopTools_MapOfShape checkedEE, allVV;
3083 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3084 while ( !smQueue.empty() )
3086 SMESH_subMesh* sm = smQueue.front();
3087 smQueue.pop_front();
3088 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3089 while ( smIt->more() )
3092 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3093 allVV.Add( sm->GetSubShape() );
3094 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3095 !checkedEE.Add( sm->GetSubShape() ))
3098 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3099 vector<_LayerEdge*>& eE = eoe->_edges;
3100 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3103 bool isC1 = true; // check continuity along an EDGE
3104 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3105 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3109 // check that mesh faces are C1 as well
3111 gp_XYZ norm1, norm2;
3112 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3113 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3114 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3116 while ( fIt->more() && isC1 )
3117 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3118 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3123 // add the EDGE and an adjacent FACE to _eosC1
3124 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3125 while ( const TopoDS_Shape* face = fIt->next() )
3127 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3128 if ( !eof ) continue; // other solid
3129 if ( !eos.HasC1( eoe ))
3131 eos._eosC1.push_back( eoe );
3132 eoe->_toSmooth = false;
3133 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3135 if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof ))
3137 eos._eosC1.push_back( eof );
3138 eof->_toSmooth = false;
3139 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3140 smQueue.push_back( eof->_subMesh );
3145 if ( eos._eosC1.empty() )
3148 // check VERTEXes of C1 FACEs
3149 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3150 for ( ; vIt.More(); vIt.Next() )
3152 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3153 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3156 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3157 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3158 while ( const TopoDS_Shape* face = fIt->next() )
3160 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3161 if ( !eof ) continue; // other solid
3162 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3168 eos._eosC1.push_back( eov );
3169 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3170 c1VV.Add( eov->_shape );
3174 } // fill _eosC1 of FACEs
3179 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3181 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3183 _EdgesOnShape& eov = edgesByGeom[iS];
3184 if ( eov._edges.empty() ||
3185 eov.ShapeType() != TopAbs_VERTEX ||
3186 c1VV.Contains( eov._shape ))
3188 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3190 // get directions of surrounding EDGEs
3192 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3193 while ( const TopoDS_Shape* e = fIt->next() )
3195 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3196 if ( !eoe ) continue; // other solid
3197 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3198 if ( !Precision::IsInfinite( eDir.X() ))
3199 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3202 // find EDGEs with C1 directions
3203 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3204 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3205 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3207 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3208 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3211 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3212 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3213 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3214 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3215 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3216 dirOfEdges[i].first = 0;
3217 dirOfEdges[j].first = 0;
3220 } // fill _eosC1 of VERTEXes
3227 //================================================================================
3229 * \brief initialize data of _EdgesOnShape
3231 //================================================================================
3233 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3237 if ( !eos._shape.IsNull() ||
3238 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3241 SMESH_MesherHelper helper( *_mesh );
3244 eos._shapeID = sm->GetId();
3245 eos._shape = sm->GetSubShape();
3246 if ( eos.ShapeType() == TopAbs_FACE )
3247 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3248 eos._toSmooth = false;
3252 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3253 data._shrinkShape2Shape.find( eos._shapeID );
3254 if ( s2s != data._shrinkShape2Shape.end() )
3255 eos._sWOL = s2s->second;
3257 eos._isRegularSWOL = true;
3258 if ( eos.SWOLType() == TopAbs_FACE )
3260 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3261 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3262 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3266 if ( data._hyps.size() == 1 )
3268 eos._hyp = data._hyps.back();
3272 // compute average StdMeshers_ViscousLayers parameters
3273 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3274 if ( eos.ShapeType() == TopAbs_FACE )
3276 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3277 eos._hyp = f2hyp->second;
3281 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3282 while ( const TopoDS_Shape* face = fIt->next() )
3284 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3285 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3286 eos._hyp.Add( f2hyp->second );
3292 if ( ! eos._hyp.UseSurfaceNormal() )
3294 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3296 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3297 eos._faceNormals.resize( smDS->NbElements() );
3299 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3300 for ( int iF = 0; eIt->more(); ++iF )
3302 const SMDS_MeshElement* face = eIt->next();
3303 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3304 eos._faceNormals[iF].SetCoord( 0,0,0 );
3307 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3308 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3309 eos._faceNormals[iF].Reverse();
3311 else // find EOS of adjacent FACEs
3313 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3314 while ( const TopoDS_Shape* face = fIt->next() )
3316 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3317 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3318 if ( eos._faceEOS.back()->_shape.IsNull() )
3319 // avoid using uninitialised _shapeID in GetNormal()
3320 eos._faceEOS.back()->_shapeID = faceID;
3326 //================================================================================
3328 * \brief Returns normal of a face
3330 //================================================================================
3332 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3335 const _EdgesOnShape* eos = 0;
3337 if ( face->getshapeId() == _shapeID )
3343 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3344 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3345 eos = _faceEOS[ iF ];
3349 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3351 norm = eos->_faceNormals[ face->getIdInShape() ];
3355 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3356 << " on _shape #" << _shapeID );
3362 //================================================================================
3364 * \brief Set data of _LayerEdge needed for smoothing
3366 //================================================================================
3368 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3370 SMESH_MesherHelper& helper,
3373 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3376 edge._maxLen = Precision::Infinite();
3379 edge._curvature = 0;
3382 // --------------------------
3383 // Compute _normal and _cosin
3384 // --------------------------
3387 edge._lenFactor = 1.;
3388 edge._normal.SetCoord(0,0,0);
3389 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3391 int totalNbFaces = 0;
3393 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3397 const bool onShrinkShape = !eos._sWOL.IsNull();
3398 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3399 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3401 // get geom FACEs the node lies on
3402 //if ( useGeometry )
3404 set<TGeomID> faceIds;
3405 if ( eos.ShapeType() == TopAbs_FACE )
3407 faceIds.insert( eos._shapeID );
3411 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3412 while ( fIt->more() )
3413 faceIds.insert( fIt->next()->getshapeId() );
3415 set<TGeomID>::iterator id = faceIds.begin();
3416 for ( ; id != faceIds.end(); ++id )
3418 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3419 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3421 F = TopoDS::Face( s );
3422 face2Norm[ totalNbFaces ].first = F;
3430 bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3431 eos.SWOLType() == TopAbs_FACE &&
3434 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3436 if ( eos.SWOLType() == TopAbs_EDGE )
3438 // inflate from VERTEX along EDGE
3439 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3441 else if ( eos.ShapeType() == TopAbs_VERTEX )
3443 // inflate from VERTEX along FACE
3444 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3445 node, helper, normOK, &edge._cosin);
3449 // inflate from EDGE along FACE
3450 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3451 node, helper, normOK);
3454 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3457 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3460 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3462 F = face2Norm[ iF ].first;
3463 geomNorm = getFaceNormal( node, F, helper, normOK );
3464 if ( !normOK ) continue;
3467 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3469 face2Norm[ iF ].second = geomNorm.XYZ();
3470 edge._normal += geomNorm.XYZ();
3472 if ( nbOkNorms == 0 )
3473 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3475 if ( totalNbFaces >= 3 )
3477 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3480 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3482 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3483 edge._normal.SetCoord( 0,0,0 );
3484 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3486 const TopoDS_Face& F = face2Norm[iF].first;
3487 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3488 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3491 face2Norm[ iF ].second = geomNorm.XYZ();
3492 edge._normal += face2Norm[ iF ].second;
3497 else // !useGeometry - get _normal using surrounding mesh faces
3499 edge._normal = getWeigthedNormal( &edge );
3501 // set<TGeomID> faceIds;
3503 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3504 // while ( fIt->more() )
3506 // const SMDS_MeshElement* face = fIt->next();
3507 // if ( eos.GetNormal( face, geomNorm ))
3509 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3510 // continue; // use only one mesh face on FACE
3511 // edge._normal += geomNorm.XYZ();
3518 //if ( eos._hyp.UseSurfaceNormal() )
3520 switch ( eos.ShapeType() )
3527 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3528 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3529 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3530 edge._cosin = Cos( angle );
3533 case TopAbs_VERTEX: {
3534 //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3536 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3537 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3538 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3539 edge._cosin = Cos( angle );
3540 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3541 for ( int iF = totalNbFaces-2; iF >=0; --iF )
3543 F = face2Norm[ iF ].first;
3544 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3546 double angle = inFaceDir.Angle( edge._normal );
3547 double cosin = Cos( angle );
3548 if ( Abs( cosin ) > Abs( edge._cosin ))
3549 edge._cosin = cosin;
3556 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3560 double normSize = edge._normal.SquareModulus();
3561 if ( normSize < numeric_limits<double>::min() )
3562 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3564 edge._normal /= sqrt( normSize );
3566 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3568 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3569 edge._nodes.resize( 1 );
3570 edge._normal.SetCoord( 0,0,0 );
3574 // Set the rest data
3575 // --------------------
3577 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3579 if ( onShrinkShape )
3581 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3582 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3583 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3585 // set initial position which is parameters on _sWOL in this case
3586 if ( eos.SWOLType() == TopAbs_EDGE )
3588 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3589 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3590 if ( edge._nodes.size() > 1 )
3591 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3593 else // eos.SWOLType() == TopAbs_FACE
3595 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3596 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3597 if ( edge._nodes.size() > 1 )
3598 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3601 if ( edge._nodes.size() > 1 )
3603 // check if an angle between a FACE with layers and SWOL is sharp,
3604 // else the edge should not inflate
3606 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3607 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3608 F = face2Norm[iF].first;
3611 geomNorm = getFaceNormal( node, F, helper, normOK );
3612 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3613 geomNorm.Reverse(); // inside the SOLID
3614 if ( geomNorm * edge._normal < -0.001 )
3616 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3617 edge._nodes.resize( 1 );
3619 else if ( edge._lenFactor > 3 )
3621 edge._lenFactor = 2;
3622 edge.Set( _LayerEdge::RISKY_SWOL );
3629 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3631 if ( eos.ShapeType() == TopAbs_FACE )
3634 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3636 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3637 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3642 // Set neighbor nodes for a _LayerEdge based on EDGE
3644 if ( eos.ShapeType() == TopAbs_EDGE /*||
3645 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3647 edge._2neibors = new _2NearEdges;
3648 // target nodes instead of source ones will be set later
3654 //================================================================================
3656 * \brief Return normal to a FACE at a node
3657 * \param [in] n - node
3658 * \param [in] face - FACE
3659 * \param [in] helper - helper
3660 * \param [out] isOK - true or false
3661 * \param [in] shiftInside - to find normal at a position shifted inside the face
3662 * \return gp_XYZ - normal
3664 //================================================================================
3666 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3667 const TopoDS_Face& face,
3668 SMESH_MesherHelper& helper,
3675 // get a shifted position
3676 gp_Pnt p = SMESH_TNodeXYZ( node );
3677 gp_XYZ shift( 0,0,0 );
3678 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3679 switch ( S.ShapeType() ) {
3682 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3687 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3695 p.Translate( shift * 1e-5 );
3697 TopLoc_Location loc;
3698 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3700 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3702 projector.Perform( p );
3703 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3708 Quantity_Parameter U,V;
3709 projector.LowerDistanceParameters(U,V);
3714 uv = helper.GetNodeUV( face, node, 0, &isOK );
3720 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3722 if ( !shiftInside &&
3723 helper.IsDegenShape( node->getshapeId() ) &&
3724 getFaceNormalAtSingularity( uv, face, helper, normal ))
3727 return normal.XYZ();
3730 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3731 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3733 if ( pointKind == IMPOSSIBLE &&
3734 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3736 // probably NormEstim() failed due to a too high tolerance
3737 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3738 isOK = ( pointKind < IMPOSSIBLE );
3740 if ( pointKind < IMPOSSIBLE )
3742 if ( pointKind != REGULAR &&
3744 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3746 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3747 if ( normShift * normal.XYZ() < 0. )
3753 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3755 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3757 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3758 while ( fIt->more() )
3760 const SMDS_MeshElement* f = fIt->next();
3761 if ( f->getshapeId() == faceID )
3763 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3766 TopoDS_Face ff = face;
3767 ff.Orientation( TopAbs_FORWARD );
3768 if ( helper.IsReversedSubMesh( ff ))
3775 return normal.XYZ();
3778 //================================================================================
3780 * \brief Try to get normal at a singularity of a surface basing on it's nature
3782 //================================================================================
3784 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3785 const TopoDS_Face& face,
3786 SMESH_MesherHelper& helper,
3789 BRepAdaptor_Surface surface( face );
3791 if ( !getRovolutionAxis( surface, axis ))
3794 double f,l, d, du, dv;
3795 f = surface.FirstUParameter();
3796 l = surface.LastUParameter();
3797 d = ( uv.X() - f ) / ( l - f );
3798 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3799 f = surface.FirstVParameter();
3800 l = surface.LastVParameter();
3801 d = ( uv.Y() - f ) / ( l - f );
3802 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3805 gp_Pnt2d testUV = uv;
3806 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3808 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3809 for ( int iLoop = 0; true ; ++iLoop )
3811 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3812 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3819 if ( axis * refDir < 0. )
3827 //================================================================================
3829 * \brief Return a normal at a node weighted with angles taken by faces
3831 //================================================================================
3833 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3835 const SMDS_MeshNode* n = edge->_nodes[0];
3837 gp_XYZ resNorm(0,0,0);
3838 SMESH_TNodeXYZ p0( n ), pP, pN;
3839 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3841 pP.Set( edge->_simplices[i]._nPrev );
3842 pN.Set( edge->_simplices[i]._nNext );
3843 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3844 double l0P = v0P.SquareMagnitude();
3845 double l0N = v0N.SquareMagnitude();
3846 double lPN = vPN.SquareMagnitude();
3847 if ( l0P < std::numeric_limits<double>::min() ||
3848 l0N < std::numeric_limits<double>::min() ||
3849 lPN < std::numeric_limits<double>::min() )
3851 double lNorm = norm.SquareMagnitude();
3852 double sin2 = lNorm / l0P / l0N;
3853 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3855 double weight = sin2 * angle / lPN;
3856 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3862 //================================================================================
3864 * \brief Return a normal at a node by getting a common point of offset planes
3865 * defined by the FACE normals
3867 //================================================================================
3869 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3870 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3874 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3876 gp_XYZ resNorm(0,0,0);
3877 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3878 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3880 for ( int i = 0; i < nbFaces; ++i )
3881 resNorm += f2Normal[i].second;
3885 // prepare _OffsetPlane's
3886 vector< _OffsetPlane > pln( nbFaces );
3887 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3889 pln[i]._faceIndex = i;
3890 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3894 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3895 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3898 // intersect neighboring OffsetPlane's
3899 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3900 while ( const TopoDS_Shape* edge = edgeIt->next() )
3902 int f1 = -1, f2 = -1;
3903 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3904 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3905 (( f1 < 0 ) ? f1 : f2 ) = i;
3908 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3911 // get a common point
3912 gp_XYZ commonPnt( 0, 0, 0 );
3915 for ( int i = 0; i < nbFaces; ++i )
3917 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3918 nbPoints += isPointFound;
3920 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3921 if ( nbPoints == 0 )
3924 commonPnt /= nbPoints;
3925 resNorm = commonPnt - p0;
3929 // choose the best among resNorm and wgtNorm
3930 resNorm.Normalize();
3931 wgtNorm.Normalize();
3932 double resMinDot = std::numeric_limits<double>::max();
3933 double wgtMinDot = std::numeric_limits<double>::max();
3934 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3936 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3937 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3940 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3942 edge->Set( _LayerEdge::MULTI_NORMAL );
3945 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3948 //================================================================================
3950 * \brief Compute line of intersection of 2 planes
3952 //================================================================================
3954 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3955 const TopoDS_Edge& E,
3956 const TopoDS_Vertex& V )
3958 int iNext = bool( _faceIndexNext[0] >= 0 );
3959 _faceIndexNext[ iNext ] = pln._faceIndex;
3961 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3962 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3964 gp_XYZ lineDir = n1 ^ n2;
3966 double x = Abs( lineDir.X() );
3967 double y = Abs( lineDir.Y() );
3968 double z = Abs( lineDir.Z() );
3970 int cooMax; // max coordinate
3972 if (x > z) cooMax = 1;
3976 if (y > z) cooMax = 2;
3981 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3983 // parallel planes - intersection is an offset of the common EDGE
3984 gp_Pnt p = BRep_Tool::Pnt( V );
3985 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3986 lineDir = getEdgeDir( E, V );
3990 // the constants in the 2 plane equations
3991 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
3992 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3997 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3998 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4001 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4003 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4006 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4007 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4011 gp_Lin& line = _lines[ iNext ];
4012 line.SetDirection( lineDir );
4013 line.SetLocation ( linePos );
4015 _isLineOK[ iNext ] = true;
4018 iNext = bool( pln._faceIndexNext[0] >= 0 );
4019 pln._lines [ iNext ] = line;
4020 pln._faceIndexNext[ iNext ] = this->_faceIndex;
4021 pln._isLineOK [ iNext ] = true;
4024 //================================================================================
4026 * \brief Computes intersection point of two _lines
4028 //================================================================================
4030 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4031 const TopoDS_Vertex & V) const
4036 if ( NbLines() == 2 )
4038 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4039 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4040 if ( Abs( dot01 ) > 0.05 )
4042 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4043 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4044 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4049 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4050 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4051 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4052 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4053 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4061 //================================================================================
4063 * \brief Find 2 neigbor nodes of a node on EDGE
4065 //================================================================================
4067 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4068 const SMDS_MeshNode*& n1,
4069 const SMDS_MeshNode*& n2,
4073 const SMDS_MeshNode* node = edge->_nodes[0];
4074 const int shapeInd = eos._shapeID;
4075 SMESHDS_SubMesh* edgeSM = 0;
4076 if ( eos.ShapeType() == TopAbs_EDGE )
4078 edgeSM = eos._subMesh->GetSubMeshDS();
4079 if ( !edgeSM || edgeSM->NbElements() == 0 )
4080 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4084 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4085 while ( eIt->more() && !n2 )
4087 const SMDS_MeshElement* e = eIt->next();
4088 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4089 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4092 if (!edgeSM->Contains(e)) continue;
4096 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4097 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4099 ( iN++ ? n2 : n1 ) = nNeibor;
4102 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4106 //================================================================================
4108 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4110 //================================================================================
4112 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4113 const SMDS_MeshNode* n2,
4114 const _EdgesOnShape& eos,
4115 SMESH_MesherHelper& helper)
4117 if ( eos.ShapeType() != TopAbs_EDGE )
4120 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4121 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4122 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4126 double sumLen = vec1.Modulus() + vec2.Modulus();
4127 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4128 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4129 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4130 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4131 if ( _curvature ) delete _curvature;
4132 _curvature = _Curvature::New( avgNormProj, avgLen );
4133 // if ( _curvature )
4134 // debugMsg( _nodes[0]->GetID()
4135 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4136 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4137 // << _curvature->lenDelta(0) );
4141 if ( eos._sWOL.IsNull() )
4143 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4144 // if ( SMESH_Algo::isDegenerated( E ))
4146 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4147 gp_XYZ plnNorm = dirE ^ _normal;
4148 double proj0 = plnNorm * vec1;
4149 double proj1 = plnNorm * vec2;
4150 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4152 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4153 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4158 //================================================================================
4160 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4161 * this and other _LayerEdge's are inflated along a FACE or an EDGE
4163 //================================================================================
4165 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4167 SMESH_MesherHelper& helper )
4169 _nodes = other._nodes;
4170 _normal = other._normal;
4172 _lenFactor = other._lenFactor;
4173 _cosin = other._cosin;
4174 _2neibors = other._2neibors;
4175 _curvature = 0; std::swap( _curvature, other._curvature );
4176 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4178 gp_XYZ lastPos( 0,0,0 );
4179 if ( eos.SWOLType() == TopAbs_EDGE )
4181 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4182 _pos.push_back( gp_XYZ( u, 0, 0));
4184 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4189 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4190 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4192 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4193 lastPos.SetX( uv.X() );
4194 lastPos.SetY( uv.Y() );
4199 //================================================================================
4201 * \brief Set _cosin and _lenFactor
4203 //================================================================================
4205 void _LayerEdge::SetCosin( double cosin )
4208 cosin = Abs( _cosin );
4209 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4210 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4213 //================================================================================
4215 * \brief Check if another _LayerEdge is a neighbor on EDGE
4217 //================================================================================
4219 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4221 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4222 ( edge->_2neibors && edge->_2neibors->include( this )));
4225 //================================================================================
4227 * \brief Fills a vector<_Simplex >
4229 //================================================================================
4231 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4232 vector<_Simplex>& simplices,
4233 const set<TGeomID>& ingnoreShapes,
4234 const _SolidData* dataToCheckOri,
4238 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4239 while ( fIt->more() )
4241 const SMDS_MeshElement* f = fIt->next();
4242 const TGeomID shapeInd = f->getshapeId();
4243 if ( ingnoreShapes.count( shapeInd )) continue;
4244 const int nbNodes = f->NbCornerNodes();
4245 const int srcInd = f->GetNodeIndex( node );
4246 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4247 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4248 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4249 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4250 std::swap( nPrev, nNext );
4251 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4255 SortSimplices( simplices );
4258 //================================================================================
4260 * \brief Set neighbor simplices side by side
4262 //================================================================================
4264 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4266 vector<_Simplex> sortedSimplices( simplices.size() );
4267 sortedSimplices[0] = simplices[0];
4269 for ( size_t i = 1; i < simplices.size(); ++i )
4271 for ( size_t j = 1; j < simplices.size(); ++j )
4272 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4274 sortedSimplices[i] = simplices[j];
4279 if ( nbFound == simplices.size() - 1 )
4280 simplices.swap( sortedSimplices );
4283 //================================================================================
4285 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4287 //================================================================================
4289 void _ViscousBuilder::makeGroupOfLE()
4292 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4294 if ( _sdVec[i]._n2eMap.empty() ) continue;
4296 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4297 TNode2Edge::iterator n2e;
4298 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4300 _LayerEdge* le = n2e->second;
4301 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4302 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4303 // << ", " << le->_nodes[iN]->GetID() <<"])");
4305 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4306 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4311 dumpFunction( SMESH_Comment("makeNormals") << i );
4312 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4314 _LayerEdge* edge = n2e->second;
4315 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4316 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4317 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4318 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4322 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4323 dumpCmd( "faceId1 = mesh.NbElements()" );
4324 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4325 for ( ; fExp.More(); fExp.Next() )
4327 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4329 if ( sm->NbElements() == 0 ) continue;
4330 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4331 while ( fIt->more())
4333 const SMDS_MeshElement* e = fIt->next();
4334 SMESH_Comment cmd("mesh.AddFace([");
4335 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4336 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4341 dumpCmd( "faceId2 = mesh.NbElements()" );
4342 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4343 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4344 << "'%s-%s' % (faceId1+1, faceId2))");
4350 //================================================================================
4352 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4354 //================================================================================
4356 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4358 data._geomSize = Precision::Infinite();
4359 double intersecDist;
4360 const SMDS_MeshElement* face;
4361 SMESH_MesherHelper helper( *_mesh );
4363 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4364 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4365 data._proxyMesh->GetFaces( data._solid )));
4367 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4369 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4370 if ( eos._edges.empty() )
4372 // get neighbor faces intersection with which should not be considered since
4373 // collisions are avoided by means of smoothing
4374 set< TGeomID > neighborFaces;
4375 if ( eos._hyp.ToSmooth() )
4377 SMESH_subMeshIteratorPtr subIt =
4378 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4379 while ( subIt->more() )
4381 SMESH_subMesh* sm = subIt->next();
4382 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4383 while ( const TopoDS_Shape* face = fIt->next() )
4384 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4387 // find intersections
4388 double thinkness = eos._hyp.GetTotalThickness();
4389 for ( size_t i = 0; i < eos._edges.size(); ++i )
4391 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4392 eos._edges[i]->_maxLen = thinkness;
4393 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4394 if ( intersecDist > 0 && face )
4396 data._geomSize = Min( data._geomSize, intersecDist );
4397 if ( !neighborFaces.count( face->getshapeId() ))
4398 eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4404 //================================================================================
4406 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4408 //================================================================================
4410 bool _ViscousBuilder::inflate(_SolidData& data)
4412 SMESH_MesherHelper helper( *_mesh );
4414 // Limit inflation step size by geometry size found by itersecting
4415 // normals of _LayerEdge's with mesh faces
4416 if ( data._stepSize > 0.3 * data._geomSize )
4417 limitStepSize( data, 0.3 * data._geomSize );
4419 const double tgtThick = data._maxThickness;
4420 if ( data._stepSize > data._minThickness )
4421 limitStepSize( data, data._minThickness );
4423 if ( data._stepSize < 1. )
4424 data._epsilon = data._stepSize * 1e-7;
4426 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4428 findCollisionEdges( data, helper );
4430 limitMaxLenByCurvature( data, helper );
4432 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4433 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4434 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4435 data._edgesOnShape[i]._edges.size() > 0 &&
4436 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4438 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4439 data._edgesOnShape[i]._edges[0]->Block( data );
4442 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4444 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4445 int nbSteps = 0, nbRepeats = 0;
4446 while ( avgThick < 0.99 )
4448 // new target length
4449 double prevThick = curThick;
4450 curThick += data._stepSize;
4451 if ( curThick > tgtThick )
4453 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4457 double stepSize = curThick - prevThick;
4458 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4460 // Elongate _LayerEdge's
4461 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4462 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4464 _EdgesOnShape& eos = data._edgesOnShape[iS];
4465 if ( eos._edges.empty() ) continue;
4467 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4468 for ( size_t i = 0; i < eos._edges.size(); ++i )
4470 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4475 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4478 // Improve and check quality
4479 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4483 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4484 debugMsg("NOT INVALIDATED STEP!");
4485 return error("Smoothing failed", data._index);
4487 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4488 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4490 _EdgesOnShape& eos = data._edgesOnShape[iS];
4491 for ( size_t i = 0; i < eos._edges.size(); ++i )
4492 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4496 break; // no more inflating possible
4500 // Evaluate achieved thickness
4502 int nbActiveEdges = 0;
4503 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4505 _EdgesOnShape& eos = data._edgesOnShape[iS];
4506 if ( eos._edges.empty() ) continue;
4508 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4509 for ( size_t i = 0; i < eos._edges.size(); ++i )
4511 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4512 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4515 avgThick /= data._n2eMap.size();
4516 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4518 #ifdef BLOCK_INFLATION
4519 if ( nbActiveEdges == 0 )
4521 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4525 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4527 debugMsg( "-- Stop inflation since "
4528 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4529 << tgtThick * avgThick << " ) * " << safeFactor );
4534 limitStepSize( data, 0.25 * distToIntersection );
4535 if ( data._stepSizeNodes[0] )
4536 data._stepSize = data._stepSizeCoeff *
4537 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4539 } // while ( avgThick < 0.99 )
4542 return error("failed at the very first inflation step", data._index);
4544 if ( avgThick < 0.99 )
4546 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4548 data._proxyMesh->_warning.reset
4549 ( new SMESH_ComputeError (COMPERR_WARNING,
4550 SMESH_Comment("Thickness ") << tgtThick <<
4551 " of viscous layers not reached,"
4552 " average reached thickness is " << avgThick*tgtThick));
4556 // Restore position of src nodes moved by inflation on _noShrinkShapes
4557 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4558 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4560 _EdgesOnShape& eos = data._edgesOnShape[iS];
4561 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4562 for ( size_t i = 0; i < eos._edges.size(); ++i )
4564 restoreNoShrink( *eos._edges[ i ] );
4569 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4572 //================================================================================
4574 * \brief Improve quality of layer inner surface and check intersection
4576 //================================================================================
4578 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4580 double & distToIntersection)
4582 if ( data._nbShapesToSmooth == 0 )
4583 return true; // no shapes needing smoothing
4585 bool moved, improved;
4587 vector< _LayerEdge* > movedEdges, badEdges;
4588 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4589 vector< bool > isConcaveFace;
4591 SMESH_MesherHelper helper(*_mesh);
4592 Handle(ShapeAnalysis_Surface) surface;
4595 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4597 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4599 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4601 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4602 if ( !eos._toSmooth ||
4603 eos.ShapeType() != shapeType ||
4604 eos._edges.empty() )
4607 // already smoothed?
4608 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4609 // if ( !toSmooth ) continue;
4611 if ( !eos._hyp.ToSmooth() )
4613 // smooth disabled by the user; check validy only
4614 if ( !isFace ) continue;
4616 for ( size_t i = 0; i < eos._edges.size(); ++i )
4618 _LayerEdge* edge = eos._edges[i];
4619 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4620 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4622 // debugMsg( "-- Stop inflation. Bad simplex ("
4623 // << " "<< edge->_nodes[0]->GetID()
4624 // << " "<< edge->_nodes.back()->GetID()
4625 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4626 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4628 badEdges.push_back( edge );
4631 if ( !badEdges.empty() )
4635 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4639 continue; // goto the next EDGE or FACE
4643 if ( eos.SWOLType() == TopAbs_FACE )
4645 if ( !F.IsSame( eos._sWOL )) {
4646 F = TopoDS::Face( eos._sWOL );
4647 helper.SetSubShape( F );
4648 surface = helper.GetSurface( F );
4653 F.Nullify(); surface.Nullify();
4655 const TGeomID sInd = eos._shapeID;
4657 // perform smoothing
4659 if ( eos.ShapeType() == TopAbs_EDGE )
4661 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4663 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4665 // smooth on EDGE's (normally we should not get here)
4669 for ( size_t i = 0; i < eos._edges.size(); ++i )
4671 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4673 dumpCmd( SMESH_Comment("# end step ")<<step);
4675 while ( moved && step++ < 5 );
4680 else // smooth on FACE
4683 eosC1.push_back( & eos );
4684 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4687 isConcaveFace.resize( eosC1.size() );
4688 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4690 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4691 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4692 for ( size_t i = 0; i < edges.size(); ++i )
4693 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4694 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4695 movedEdges.push_back( edges[i] );
4697 makeOffsetSurface( *eosC1[ iEOS ], helper );
4700 int step = 0, stepLimit = 5, nbBad = 0;
4701 while (( ++step <= stepLimit ) || improved )
4703 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4704 <<"_InfStep"<<infStep<<"_"<<step); // debug
4705 int oldBadNb = nbBad;
4708 #ifdef INCREMENTAL_SMOOTH
4709 bool findBest = false; // ( step == stepLimit );
4710 for ( size_t i = 0; i < movedEdges.size(); ++i )
4712 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4713 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4714 badEdges.push_back( movedEdges[i] );
4717 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4718 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4720 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4721 for ( size_t i = 0; i < edges.size(); ++i )
4723 edges[i]->Unset( _LayerEdge::SMOOTHED );
4724 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4725 badEdges.push_back( eos._edges[i] );
4729 nbBad = badEdges.size();
4732 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4734 if ( !badEdges.empty() && step >= stepLimit / 2 )
4736 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4739 // resolve hard smoothing situation around concave VERTEXes
4740 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4742 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4743 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4744 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4747 // look for the best smooth of _LayerEdge's neighboring badEdges
4749 for ( size_t i = 0; i < badEdges.size(); ++i )
4751 _LayerEdge* ledge = badEdges[i];
4752 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4754 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4755 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4757 ledge->Unset( _LayerEdge::SMOOTHED );
4758 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4760 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4763 if ( nbBad == oldBadNb &&
4765 step < stepLimit ) // smooth w/o chech of validity
4768 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4769 <<"_InfStep"<<infStep<<"_"<<step); // debug
4770 for ( size_t i = 0; i < movedEdges.size(); ++i )
4772 movedEdges[i]->SmoothWoCheck();
4774 if ( stepLimit < 9 )
4778 improved = ( nbBad < oldBadNb );
4782 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4783 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4785 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4788 } // smoothing steps
4790 // project -- to prevent intersections or fix bad simplices
4791 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4793 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4794 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4797 //if ( !badEdges.empty() )
4800 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4802 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4804 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4806 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4807 edge->CheckNeiborsOnBoundary( & badEdges );
4808 if (( nbBad > 0 ) ||
4809 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4811 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4812 gp_XYZ prevXYZ = edge->PrevCheckPos();
4813 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4814 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4816 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4817 << " "<< tgtXYZ._node->GetID()
4818 << " "<< edge->_simplices[j]._nPrev->GetID()
4819 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4820 badEdges.push_back( edge );
4827 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4828 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4834 } // // smooth on FACE's
4836 } // smooth on [ EDGEs, FACEs ]
4838 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4840 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4842 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4843 if ( eos.ShapeType() == TopAbs_FACE ||
4844 eos._edges.empty() ||
4845 !eos._sWOL.IsNull() )
4849 for ( size_t i = 0; i < eos._edges.size(); ++i )
4851 _LayerEdge* edge = eos._edges[i];
4852 if ( edge->_nodes.size() < 2 ) continue;
4853 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4854 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4855 //const gp_XYZ& prevXYZ = edge->PrevPos();
4856 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4857 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4859 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4860 << " "<< tgtXYZ._node->GetID()
4861 << " "<< edge->_simplices[j]._nPrev->GetID()
4862 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4863 badEdges.push_back( edge );
4868 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4870 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4876 // Check if the last segments of _LayerEdge intersects 2D elements;
4877 // checked elements are either temporary faces or faces on surfaces w/o the layers
4879 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4880 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4881 data._proxyMesh->GetFaces( data._solid )) );
4883 #ifdef BLOCK_INFLATION
4884 const bool toBlockInfaltion = true;
4886 const bool toBlockInfaltion = false;
4888 distToIntersection = Precision::Infinite();
4890 const SMDS_MeshElement* intFace = 0;
4891 const SMDS_MeshElement* closestFace = 0;
4893 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4895 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4896 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4898 for ( size_t i = 0; i < eos._edges.size(); ++i )
4900 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4901 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4903 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4906 // commented due to "Illegal hash-positionPosition" error in NETGEN
4907 // on Debian60 on viscous_layers_01/B2 case
4908 // Collision; try to deflate _LayerEdge's causing it
4909 // badEdges.clear();
4910 // badEdges.push_back( eos._edges[i] );
4911 // eosC1[0] = & eos;
4912 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4916 // badEdges.clear();
4917 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4919 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4921 // const SMDS_MeshElement* srcFace =
4922 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4923 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4924 // while ( nIt->more() )
4926 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4927 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4928 // if ( n2e != data._n2eMap.end() )
4929 // badEdges.push_back( n2e->second );
4932 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4937 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4944 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4949 const bool isShorterDist = ( distToIntersection > dist );
4950 if ( toBlockInfaltion || isShorterDist )
4952 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4953 // lying on this _ConvexFace
4954 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4955 if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4958 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4959 // ( avoid limiting the thickness on the case of issue 22576)
4960 if ( intFace->getshapeId() == eos._shapeID )
4963 // ignore intersection with intFace of an adjacent FACE
4966 bool toIgnore = false;
4967 if ( eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4969 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4970 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4972 TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4973 for ( ; !toIgnore && edge.More(); edge.Next() )
4974 // is adjacent - has a common EDGE
4975 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4977 if ( toIgnore ) // check angle between normals
4980 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4981 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
4985 if ( !toIgnore ) // check if the edge is a neighbor of intFace
4987 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
4989 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4990 toIgnore = ( nInd >= 0 );
4997 // intersection not ignored
4999 if ( toBlockInfaltion &&
5000 dist < ( eos._edges[i]->_len * theThickToIntersection ))
5002 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5003 eos._edges[i]->Block( data ); // not to inflate
5005 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5007 // block _LayerEdge's, on top of which intFace is
5008 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5010 const SMDS_MeshElement* srcFace =
5011 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5012 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5013 while ( nIt->more() )
5015 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5016 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5017 if ( n2e != data._n2eMap.end() )
5018 n2e->second->Block( data );
5024 if ( isShorterDist )
5026 distToIntersection = dist;
5028 closestFace = intFace;
5031 } // if ( toBlockInfaltion || isShorterDist )
5032 } // loop on eos._edges
5033 } // loop on data._edgesOnShape
5035 if ( closestFace && le )
5038 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5039 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5040 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5041 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5042 << ") distance = " << distToIntersection<< endl;
5049 //================================================================================
5051 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5052 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5053 * \return int - resulting nb of bad _LayerEdge's
5055 //================================================================================
5057 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5058 SMESH_MesherHelper& helper,
5059 vector< _LayerEdge* >& badSmooEdges,
5060 vector< _EdgesOnShape* >& eosC1,
5063 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5065 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5068 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5069 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5070 ADDED = _LayerEdge::UNUSED_FLAG * 4
5072 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5075 bool haveInvalidated = true;
5076 while ( haveInvalidated )
5078 haveInvalidated = false;
5079 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5081 _LayerEdge* edge = badSmooEdges[i];
5082 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5084 bool invalidated = false;
5085 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5087 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5088 edge->Block( data );
5089 edge->Set( INVALIDATED );
5090 edge->Unset( TO_INVALIDATE );
5092 haveInvalidated = true;
5095 // look for _LayerEdge's of bad _simplices
5097 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5098 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5099 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5100 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5102 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5103 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5107 _LayerEdge* ee[2] = { 0,0 };
5108 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5109 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5110 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5112 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5113 while ( maxNbSteps > edge->NbSteps() && isBad )
5116 for ( int iE = 0; iE < 2; ++iE )
5118 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5119 ee[ iE ]->NbSteps() > 1 )
5121 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5122 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5123 ee[ iE ]->Block( data );
5124 ee[ iE ]->Set( INVALIDATED );
5125 haveInvalidated = true;
5128 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5129 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5133 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5134 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5135 ee[0]->Set( ADDED );
5136 ee[1]->Set( ADDED );
5139 ee[0]->Set( TO_INVALIDATE );
5140 ee[1]->Set( TO_INVALIDATE );
5144 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5146 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5147 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5148 edge->Block( data );
5149 edge->Set( INVALIDATED );
5150 edge->Unset( TO_INVALIDATE );
5151 haveInvalidated = true;
5153 } // loop on badSmooEdges
5154 } // while ( haveInvalidated )
5156 // re-smooth on analytical EDGEs
5157 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5159 _LayerEdge* edge = badSmooEdges[i];
5160 if ( !edge->Is( INVALIDATED )) continue;
5162 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5163 if ( eos->ShapeType() == TopAbs_VERTEX )
5165 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5166 while ( const TopoDS_Shape* e = eIt->next() )
5167 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5168 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5170 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5171 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5172 // F = TopoDS::Face( eoe->_sWOL );
5173 // surface = helper.GetSurface( F );
5175 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5176 eoe->_edgeSmoother->_anaCurve.Nullify();
5182 // check result of invalidation
5185 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5187 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5189 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5190 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5191 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5192 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5193 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5194 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5197 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5198 << " "<< tgtXYZ._node->GetID()
5199 << " "<< edge->_simplices[j]._nPrev->GetID()
5200 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5209 //================================================================================
5211 * \brief Create an offset surface
5213 //================================================================================
5215 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5217 if ( eos._offsetSurf.IsNull() ||
5218 eos._edgeForOffset == 0 ||
5219 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5222 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5225 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5226 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5227 double offset = baseSurface->Gap();
5229 eos._offsetSurf.Nullify();
5233 BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5234 if ( !offsetMaker.IsDone() ) return;
5236 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5237 if ( !fExp.More() ) return;
5239 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5240 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5241 if ( surf.IsNull() ) return;
5243 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5245 catch ( Standard_Failure )
5250 //================================================================================
5252 * \brief Put nodes of a curved FACE to its offset surface
5254 //================================================================================
5256 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5258 vector< _EdgesOnShape* >& eosC1,
5262 _EdgesOnShape * eof = & eos;
5263 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5266 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5268 if ( eosC1[i]->_offsetSurf.IsNull() ||
5269 eosC1[i]->ShapeType() != TopAbs_FACE ||
5270 eosC1[i]->_edgeForOffset == 0 ||
5271 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5273 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5278 eof->_offsetSurf.IsNull() ||
5279 eof->ShapeType() != TopAbs_FACE ||
5280 eof->_edgeForOffset == 0 ||
5281 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5284 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5285 for ( size_t i = 0; i < eos._edges.size(); ++i )
5287 _LayerEdge* edge = eos._edges[i];
5288 edge->Unset( _LayerEdge::MARKED );
5289 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5291 if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5294 int nbBlockedAround = 0;
5295 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5296 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5297 if ( nbBlockedAround > 1 )
5300 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5301 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5302 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5303 edge->_curvature->_uv = uv;
5304 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5306 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5307 gp_XYZ prevP = edge->PrevCheckPos();
5310 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5312 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5316 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5317 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5318 edge->_pos.back() = newP;
5320 edge->Set( _LayerEdge::MARKED );
5325 // dumpMove() for debug
5327 for ( ; i < eos._edges.size(); ++i )
5328 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5330 if ( i < eos._edges.size() )
5332 dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5333 << "_InfStep" << infStep << "_" << smooStep );
5334 for ( ; i < eos._edges.size(); ++i )
5336 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5337 dumpMove( eos._edges[i]->_nodes.back() );
5344 //================================================================================
5346 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5347 * _LayerEdge's to be in a consequent order
5349 //================================================================================
5351 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5353 SMESH_MesherHelper& helper)
5355 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5357 TopLoc_Location loc; double f,l;
5359 Handle(Geom_Line) line;
5360 Handle(Geom_Circle) circle;
5361 bool isLine, isCirc;
5362 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5364 // check if the EDGE is a line
5365 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5366 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5367 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5369 line = Handle(Geom_Line)::DownCast( curve );
5370 circle = Handle(Geom_Circle)::DownCast( curve );
5371 isLine = (!line.IsNull());
5372 isCirc = (!circle.IsNull());
5374 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5376 isLine = SMESH_Algo::IsStraight( E );
5379 line = new Geom_Line( gp::OX() ); // only type does matter
5381 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5386 else //////////////////////////////////////////////////////////////////////// 2D case
5388 if ( !eos._isRegularSWOL ) // 23190
5391 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5393 // check if the EDGE is a line
5394 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5395 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5396 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5398 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5399 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5400 isLine = (!line2d.IsNull());
5401 isCirc = (!circle2d.IsNull());
5403 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5406 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5407 while ( nIt->more() )
5408 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5409 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5411 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5412 for ( int i = 0; i < 2 && !isLine; ++i )
5413 isLine = ( size.Coord( i+1 ) <= lineTol );
5415 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5421 line = new Geom_Line( gp::OX() ); // only type does matter
5425 gp_Pnt2d p = circle2d->Location();
5426 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5427 circle = new Geom_Circle( ax, 1.); // only center position does matter
5436 return Handle(Geom_Curve)();
5439 //================================================================================
5441 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5443 //================================================================================
5445 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5446 Handle(ShapeAnalysis_Surface)& surface,
5447 const TopoDS_Face& F,
5448 SMESH_MesherHelper& helper)
5450 if ( !isAnalytic() ) return false;
5452 const size_t iFrom = 0, iTo = _eos._edges.size();
5454 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5456 if ( F.IsNull() ) // 3D
5458 SMESH_TNodeXYZ p0 ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5459 SMESH_TNodeXYZ p1 ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5460 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5461 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5462 gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5463 _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5464 _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5465 bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5466 vLE0->Is( _LayerEdge::BLOCKED ) ||
5467 vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5468 vLE1->Is( _LayerEdge::BLOCKED ));
5469 for ( size_t i = iFrom; i < iTo; ++i )
5471 _LayerEdge* edge = _eos._edges[i];
5472 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5473 newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5475 if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5477 gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5478 double shift = ( lineDir * ( newPos - pSrc0 ) -
5479 lineDir * ( curPos - pSrc0 ));
5480 newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5482 if ( edge->Is( _LayerEdge::BLOCKED ))
5484 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5485 double curThick = pSrc.SquareDistance( tgtNode );
5486 double newThink = ( pSrc - newPos ).SquareModulus();
5487 if ( newThink > curThick )
5490 edge->_pos.back() = newPos;
5491 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5492 dumpMove( tgtNode );
5497 _LayerEdge* e0 = getLEdgeOnV( 0 );
5498 _LayerEdge* e1 = getLEdgeOnV( 1 );
5499 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5500 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5501 if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5503 int iPeriodic = helper.GetPeriodicIndex();
5504 if ( iPeriodic == 1 || iPeriodic == 2 )
5506 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5507 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5508 std::swap( uv0, uv1 );
5511 const gp_XY rangeUV = uv1 - uv0;
5512 for ( size_t i = iFrom; i < iTo; ++i )
5514 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5515 gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5516 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5518 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5519 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5520 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5521 dumpMove( tgtNode );
5523 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5524 pos->SetUParameter( newUV.X() );
5525 pos->SetVParameter( newUV.Y() );
5531 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5533 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5534 gp_Pnt center3D = circle->Location();
5536 if ( F.IsNull() ) // 3D
5538 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5539 return true; // closed EDGE - nothing to do
5541 // circle is a real curve of EDGE
5542 gp_Circ circ = circle->Circ();
5544 // new center is shifted along its axis
5545 const gp_Dir& axis = circ.Axis().Direction();
5546 _LayerEdge* e0 = getLEdgeOnV(0);
5547 _LayerEdge* e1 = getLEdgeOnV(1);
5548 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5549 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5550 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5551 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5552 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5554 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5556 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5557 gp_Circ newCirc( newAxis, newRadius );
5558 gp_Vec vecC1 ( newCenter, p1 );
5560 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5564 for ( size_t i = iFrom; i < iTo; ++i )
5566 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5567 double u = uLast * _leParams[i];
5568 gp_Pnt p = ElCLib::Value( u, newCirc );
5569 _eos._edges[i]->_pos.back() = p.XYZ();
5571 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5572 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5573 dumpMove( tgtNode );
5579 const gp_XY center( center3D.X(), center3D.Y() );
5581 _LayerEdge* e0 = getLEdgeOnV(0);
5582 _LayerEdge* eM = _eos._edges[ 0 ];
5583 _LayerEdge* e1 = getLEdgeOnV(1);
5584 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5585 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5586 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5587 gp_Vec2d vec0( center, uv0 );
5588 gp_Vec2d vecM( center, uvM );
5589 gp_Vec2d vec1( center, uv1 );
5590 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5591 double uMidl = vec0.Angle( vecM );
5592 if ( uLast * uMidl <= 0. )
5593 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5594 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5596 gp_Ax2d axis( center, vec0 );
5597 gp_Circ2d circ( axis, radius );
5598 for ( size_t i = iFrom; i < iTo; ++i )
5600 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5601 double newU = uLast * _leParams[i];
5602 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5603 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5605 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5606 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5607 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5608 dumpMove( tgtNode );
5610 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5611 pos->SetUParameter( newUV.X() );
5612 pos->SetVParameter( newUV.Y() );
5621 //================================================================================
5623 * \brief smooth _LayerEdge's on a an EDGE
5625 //================================================================================
5627 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5628 Handle(ShapeAnalysis_Surface)& surface,
5629 const TopoDS_Face& F,
5630 SMESH_MesherHelper& helper)
5632 if ( _offPoints.empty() )
5635 // move _offPoints along normals of _LayerEdge's
5637 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5638 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5639 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5640 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5641 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5642 _leOnV[0]._len = e[0]->_len;
5643 _leOnV[1]._len = e[1]->_len;
5644 for ( size_t i = 0; i < _offPoints.size(); i++ )
5646 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5647 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5648 const double w0 = _offPoints[i]._2edges._wgt[0];
5649 const double w1 = _offPoints[i]._2edges._wgt[1];
5650 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5651 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5652 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5653 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5654 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5655 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5657 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5658 _offPoints[i]._len = avgLen;
5662 if ( !surface.IsNull() ) // project _offPoints to the FACE
5664 fTol = 100 * BRep_Tool::Tolerance( F );
5665 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5667 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5668 //if ( surface->Gap() < 0.5 * segLen )
5669 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5671 for ( size_t i = 1; i < _offPoints.size(); ++i )
5673 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5674 //if ( surface->Gap() < 0.5 * segLen )
5675 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5679 // project tgt nodes of extreme _LayerEdge's to the offset segments
5681 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5682 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5684 gp_Pnt pExtreme[2], pProj[2];
5685 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5687 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5688 int i = _iSeg[ is2nd ];
5689 int di = is2nd ? -1 : +1;
5690 bool projected = false;
5691 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5694 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5695 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5696 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5697 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5698 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5699 if ( dist < distMin || projected )
5702 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5705 else if ( dist > distPrev )
5707 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5713 while ( !projected &&
5714 i >= 0 && i+1 < (int)_offPoints.size() );
5718 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5721 _iSeg[1] = _offPoints.size()-2;
5722 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5727 if ( _iSeg[0] > _iSeg[1] )
5729 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5733 // adjust length of extreme LE (test viscous_layers_01/B7)
5734 gp_Vec vDiv0( pExtreme[0], pProj[0] );
5735 gp_Vec vDiv1( pExtreme[1], pProj[1] );
5736 double d0 = vDiv0.Magnitude();
5737 double d1 = vDiv1.Magnitude();
5738 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5739 else e[0]->_len -= d0;
5740 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5741 else e[1]->_len -= d1;
5743 // compute normalized length of the offset segments located between the projections
5745 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5746 vector< double > len( nbSeg + 1 );
5748 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5749 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5751 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5753 len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5755 // d0 *= e[0]->_lenFactor;
5756 // d1 *= e[1]->_lenFactor;
5757 double fullLen = len.back() - d0 - d1;
5758 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5759 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5761 // temporary replace extreme _offPoints by pExtreme
5762 gp_XYZ op[2] = { _offPoints[ _iSeg[0] ]._xyz,
5763 _offPoints[ _iSeg[1]+1 ]._xyz };
5764 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
5765 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5767 // distribute tgt nodes of _LayerEdge's between the projections
5770 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5772 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5773 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5775 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5776 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
5777 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5779 if ( surface.IsNull() )
5781 _eos._edges[i]->_pos.back() = p;
5783 else // project a new node position to a FACE
5785 gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5786 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5788 p = surface->Value( uv2 ).XYZ();
5789 _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5791 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5792 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5793 dumpMove( tgtNode );
5796 _offPoints[ _iSeg[0] ]._xyz = op[0];
5797 _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5802 //================================================================================
5804 * \brief Prepare for smoothing
5806 //================================================================================
5808 void _Smoother1D::prepare(_SolidData& data)
5810 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5811 _curveLen = SMESH_Algo::EdgeLength( E );
5813 // sort _LayerEdge's by position on the EDGE
5814 data.SortOnEdge( E, _eos._edges );
5816 // compute normalized param of _eos._edges on EDGE
5817 _leParams.resize( _eos._edges.size() + 1 );
5820 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5822 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5824 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5825 curLen = p.Distance( pPrev );
5826 _leParams[i+1] = _leParams[i] + curLen;
5829 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5830 for ( size_t i = 0; i < _leParams.size()-1; ++i )
5831 _leParams[i] = _leParams[i+1] / fullLen;
5837 // divide E to have offset segments with low deflection
5838 BRepAdaptor_Curve c3dAdaptor( E );
5839 const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5840 const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5841 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5842 if ( discret.NbPoints() <= 2 )
5844 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5848 const double u0 = c3dAdaptor.FirstParameter();
5849 gp_Pnt p; gp_Vec tangent;
5850 _offPoints.resize( discret.NbPoints() );
5851 for ( size_t i = 0; i < _offPoints.size(); i++ )
5853 double u = discret.Parameter( i+1 );
5854 c3dAdaptor.D1( u, p, tangent );
5855 _offPoints[i]._xyz = p.XYZ();
5856 _offPoints[i]._edgeDir = tangent.XYZ();
5857 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5860 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5863 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5864 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5865 _2NearEdges tmp2edges;
5866 tmp2edges._edges[1] = _eos._edges[0];
5867 _leOnV[0]._2neibors = & tmp2edges;
5868 _leOnV[0]._nodes = leOnV[0]->_nodes;
5869 _leOnV[1]._nodes = leOnV[1]->_nodes;
5870 _LayerEdge* eNext, *ePrev = & _leOnV[0];
5871 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5873 // find _LayerEdge's located before and after an offset point
5874 // (_eos._edges[ iLE ] is next after ePrev)
5875 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5876 ePrev = _eos._edges[ iLE++ ];
5877 eNext = ePrev->_2neibors->_edges[1];
5879 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5880 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5881 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5882 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5885 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5886 for ( size_t i = 0; i < _offPoints.size(); i++ )
5887 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5888 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5890 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5891 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5892 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5895 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5897 int iLBO = _offPoints.size() - 2; // last but one
5899 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5900 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5902 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5903 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5904 _leOnV[ 0 ]._len = 0;
5905 _leOnV[ 1 ]._len = 0;
5906 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
5907 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5910 _iSeg[1] = _offPoints.size()-2;
5912 // initialize OffPnt::_len
5913 for ( size_t i = 0; i < _offPoints.size(); ++i )
5914 _offPoints[i]._len = 0;
5916 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5918 _leOnV[0]._len = leOnV[0]->_len;
5919 _leOnV[1]._len = leOnV[1]->_len;
5920 for ( size_t i = 0; i < _offPoints.size(); i++ )
5922 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5923 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5924 const double w0 = _offPoints[i]._2edges._wgt[0];
5925 const double w1 = _offPoints[i]._2edges._wgt[1];
5926 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5927 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5928 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5929 _offPoints[i]._xyz = avgXYZ;
5930 _offPoints[i]._len = avgLen;
5935 //================================================================================
5937 * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5939 //================================================================================
5941 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5942 const gp_XYZ& edgeDir)
5944 gp_XYZ cross = normal ^ edgeDir;
5945 gp_XYZ norm = edgeDir ^ cross;
5946 double size = norm.Modulus();
5951 //================================================================================
5953 * \brief Sort _LayerEdge's by a parameter on a given EDGE
5955 //================================================================================
5957 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
5958 vector< _LayerEdge* >& edges)
5960 map< double, _LayerEdge* > u2edge;
5961 for ( size_t i = 0; i < edges.size(); ++i )
5962 u2edge.insert( u2edge.end(),
5963 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5965 ASSERT( u2edge.size() == edges.size() );
5966 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5967 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5968 edges[i] = u2e->second;
5970 Sort2NeiborsOnEdge( edges );
5973 //================================================================================
5975 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5977 //================================================================================
5979 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5981 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5983 for ( size_t i = 0; i < edges.size()-1; ++i )
5984 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5985 edges[i]->_2neibors->reverse();
5987 const size_t iLast = edges.size() - 1;
5988 if ( edges.size() > 1 &&
5989 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5990 edges[iLast]->_2neibors->reverse();
5993 //================================================================================
5995 * \brief Return _EdgesOnShape* corresponding to the shape
5997 //================================================================================
5999 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6001 if ( shapeID < (int)_edgesOnShape.size() &&
6002 _edgesOnShape[ shapeID ]._shapeID == shapeID )
6003 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6005 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6006 if ( _edgesOnShape[i]._shapeID == shapeID )
6007 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6012 //================================================================================
6014 * \brief Return _EdgesOnShape* corresponding to the shape
6016 //================================================================================
6018 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6020 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6021 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6024 //================================================================================
6026 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6028 //================================================================================
6030 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6032 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6034 set< TGeomID > vertices;
6036 if ( eos->ShapeType() == TopAbs_FACE )
6038 // check FACE concavity and get concave VERTEXes
6039 F = TopoDS::Face( eos->_shape );
6040 if ( isConcave( F, helper, &vertices ))
6041 _concaveFaces.insert( eos->_shapeID );
6043 // set eos._eosConcaVer
6044 eos->_eosConcaVer.clear();
6045 eos->_eosConcaVer.reserve( vertices.size() );
6046 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6048 _EdgesOnShape* eov = GetShapeEdges( *v );
6049 if ( eov && eov->_edges.size() == 1 )
6051 eos->_eosConcaVer.push_back( eov );
6052 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6053 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6057 // SetSmooLen() to _LayerEdge's on FACE
6058 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6060 eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6062 SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6063 while ( smIt->more() ) // loop on sub-shapes of the FACE
6065 _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6066 if ( !eoe ) continue;
6068 vector<_LayerEdge*>& eE = eoe->_edges;
6069 for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6071 if ( eE[iE]->_cosin <= theMinSmoothCosin )
6074 SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6075 while ( segIt->more() )
6077 const SMDS_MeshElement* seg = segIt->next();
6078 if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6080 if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6081 continue; // not to check a seg twice
6082 for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6084 _LayerEdge* eN = eE[iE]->_neibors[iN];
6085 if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6087 double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6088 double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6089 eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6090 eN->Set( _LayerEdge::NEAR_BOUNDARY );
6095 } // if ( eos->ShapeType() == TopAbs_FACE )
6097 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6099 eos->_edges[i]->_smooFunction = 0;
6100 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6102 bool isCurved = false;
6103 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6105 _LayerEdge* edge = eos->_edges[i];
6107 // get simplices sorted
6108 _Simplex::SortSimplices( edge->_simplices );
6110 // smoothing function
6111 edge->ChooseSmooFunction( vertices, _n2eMap );
6114 double avgNormProj = 0, avgLen = 0;
6115 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6117 _Simplex& s = edge->_simplices[iS];
6119 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6120 avgNormProj += edge->_normal * vec;
6121 avgLen += vec.Modulus();
6122 if ( substituteSrcNodes )
6124 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6125 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6128 avgNormProj /= edge->_simplices.size();
6129 avgLen /= edge->_simplices.size();
6130 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6133 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6135 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6136 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6138 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6142 // prepare for putOnOffsetSurface()
6143 if (( eos->ShapeType() == TopAbs_FACE ) &&
6144 ( isCurved || !eos->_eosConcaVer.empty() ))
6146 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6147 eos->_edgeForOffset = 0;
6149 double maxCosin = -1;
6150 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6152 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6153 if ( !eoe || eoe->_edges.empty() ) continue;
6155 vector<_LayerEdge*>& eE = eoe->_edges;
6156 _LayerEdge* e = eE[ eE.size() / 2 ];
6157 if ( e->_cosin > maxCosin )
6159 eos->_edgeForOffset = e;
6160 maxCosin = e->_cosin;
6166 //================================================================================
6168 * \brief Add faces for smoothing
6170 //================================================================================
6172 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6173 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6175 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6176 for ( ; eos != eosToSmooth.end(); ++eos )
6178 if ( !*eos || (*eos)->_toSmooth ) continue;
6180 (*eos)->_toSmooth = true;
6182 if ( (*eos)->ShapeType() == TopAbs_FACE )
6184 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6185 (*eos)->_toSmooth = true;
6189 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6190 if ( edgesNoAnaSmooth )
6191 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6193 if ( (*eos)->_edgeSmoother )
6194 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6198 //================================================================================
6200 * \brief Limit _LayerEdge::_maxLen according to local curvature
6202 //================================================================================
6204 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6206 // find intersection of neighbor _LayerEdge's to limit _maxLen
6207 // according to local curvature (IPAL52648)
6209 // This method must be called after findCollisionEdges() where _LayerEdge's
6210 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6212 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6214 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6215 if ( eosI._edges.empty() ) continue;
6216 if ( !eosI._hyp.ToSmooth() )
6218 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6220 _LayerEdge* eI = eosI._edges[i];
6221 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6223 _LayerEdge* eN = eI->_neibors[iN];
6224 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6226 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6227 limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6232 else if ( eosI.ShapeType() == TopAbs_EDGE )
6234 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6235 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6237 _LayerEdge* e0 = eosI._edges[0];
6238 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6240 _LayerEdge* eI = eosI._edges[i];
6241 limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6248 //================================================================================
6250 * \brief Limit _LayerEdge::_maxLen according to local curvature
6252 //================================================================================
6254 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6256 _EdgesOnShape& eos1,
6257 _EdgesOnShape& eos2,
6258 SMESH_MesherHelper& helper )
6260 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6261 double norSize = plnNorm.SquareModulus();
6262 if ( norSize < std::numeric_limits<double>::min() )
6263 return; // parallel normals
6265 // find closest points of skew _LayerEdge's
6266 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6267 gp_XYZ dir12 = src2 - src1;
6268 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6269 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6270 double dot1 = perp2 * e1->_normal;
6271 double dot2 = perp1 * e2->_normal;
6272 double u1 = ( perp2 * dir12 ) / dot1;
6273 double u2 = - ( perp1 * dir12 ) / dot2;
6274 if ( u1 > 0 && u2 > 0 )
6276 double ovl = ( u1 * e1->_normal * dir12 -
6277 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6278 if ( ovl > theSmoothThickToElemSizeRatio )
6280 e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6281 e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6286 //================================================================================
6288 * \brief Fill data._collisionEdges
6290 //================================================================================
6292 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6294 data._collisionEdges.clear();
6296 // set the full thickness of the layers to LEs
6297 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6299 _EdgesOnShape& eos = data._edgesOnShape[iS];
6300 if ( eos._edges.empty() ) continue;
6301 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6303 for ( size_t i = 0; i < eos._edges.size(); ++i )
6305 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6306 double maxLen = eos._edges[i]->_maxLen;
6307 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6308 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6309 eos._edges[i]->_maxLen = maxLen;
6313 // make temporary quadrangles got by extrusion of
6314 // mesh edges along _LayerEdge._normal's
6316 vector< const SMDS_MeshElement* > tmpFaces;
6318 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6320 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6321 if ( eos.ShapeType() != TopAbs_EDGE )
6323 if ( eos._edges.empty() )
6325 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6326 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6327 while ( smIt->more() )
6328 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6329 if ( eov->_edges.size() == 1 )
6330 edge[ bool( edge[0]) ] = eov->_edges[0];
6334 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6335 tmpFaces.push_back( f );
6338 for ( size_t i = 0; i < eos._edges.size(); ++i )
6340 _LayerEdge* edge = eos._edges[i];
6341 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6343 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6344 if ( src2->GetPosition()->GetDim() > 0 &&
6345 src2->GetID() < edge->_nodes[0]->GetID() )
6346 continue; // avoid using same segment twice
6348 // a _LayerEdge containg tgt2
6349 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6351 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6352 tmpFaces.push_back( f );
6357 // Find _LayerEdge's intersecting tmpFaces.
6359 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6361 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6362 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6364 double dist1, dist2, segLen, eps = 0.5;
6365 _CollisionEdges collEdges;
6366 vector< const SMDS_MeshElement* > suspectFaces;
6367 const double angle45 = Cos( 45. * M_PI / 180. );
6369 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6371 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6372 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6374 // find sub-shapes whose VL can influence VL on eos
6375 set< TGeomID > neighborShapes;
6376 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6377 while ( const TopoDS_Shape* face = fIt->next() )
6379 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6380 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6382 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6383 while ( subIt->more() )
6384 neighborShapes.insert( subIt->next()->GetId() );
6387 if ( eos.ShapeType() == TopAbs_VERTEX )
6389 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6390 while ( const TopoDS_Shape* edge = eIt->next() )
6391 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6393 // find intersecting _LayerEdge's
6394 for ( size_t i = 0; i < eos._edges.size(); ++i )
6396 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6397 _LayerEdge* edge = eos._edges[i];
6398 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6401 gp_Vec eSegDir0, eSegDir1;
6402 if ( edge->IsOnEdge() )
6404 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6405 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6406 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6408 suspectFaces.clear();
6409 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6410 SMDSAbs_Face, suspectFaces );
6411 collEdges._intEdges.clear();
6412 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6414 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6415 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6416 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6417 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6418 if ( edge->IsOnEdge() ) {
6419 if ( edge->_2neibors->include( f->_le1 ) ||
6420 edge->_2neibors->include( f->_le2 )) continue;
6423 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6424 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6426 dist1 = dist2 = Precision::Infinite();
6427 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6428 dist1 = Precision::Infinite();
6429 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6430 dist2 = Precision::Infinite();
6431 if (( dist1 > segLen ) && ( dist2 > segLen ))
6434 if ( edge->IsOnEdge() )
6436 // skip perpendicular EDGEs
6437 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6438 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6439 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6440 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6441 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6446 // either limit inflation of edges or remember them for updating _normal
6447 // double dot = edge->_normal * f->GetDir();
6450 collEdges._intEdges.push_back( f->_le1 );
6451 collEdges._intEdges.push_back( f->_le2 );
6455 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6456 // edge->_maxLen = Min( shortLen, edge->_maxLen );
6460 if ( !collEdges._intEdges.empty() )
6462 collEdges._edge = edge;
6463 data._collisionEdges.push_back( collEdges );
6468 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6471 // restore the zero thickness
6472 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6474 _EdgesOnShape& eos = data._edgesOnShape[iS];
6475 if ( eos._edges.empty() ) continue;
6476 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6478 for ( size_t i = 0; i < eos._edges.size(); ++i )
6480 eos._edges[i]->InvalidateStep( 1, eos );
6481 eos._edges[i]->_len = 0;
6486 //================================================================================
6488 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6489 * _LayerEdge's on neighbor EDGE's
6491 //================================================================================
6493 bool _ViscousBuilder::updateNormals( _SolidData& data,
6494 SMESH_MesherHelper& helper,
6498 updateNormalsOfC1Vertices( data );
6500 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6503 // map to store new _normal and _cosin for each intersected edge
6504 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6505 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6506 _LayerEdge zeroEdge;
6507 zeroEdge._normal.SetCoord( 0,0,0 );
6508 zeroEdge._maxLen = Precision::Infinite();
6509 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6511 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6513 double segLen, dist1, dist2, dist;
6514 vector< pair< _LayerEdge*, double > > intEdgesDist;
6515 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6517 for ( int iter = 0; iter < 5; ++iter )
6519 edge2newEdge.clear();
6521 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6523 _CollisionEdges& ce = data._collisionEdges[iE];
6524 _LayerEdge* edge1 = ce._edge;
6525 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6526 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6527 if ( !eos1 ) continue;
6529 // detect intersections
6530 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6531 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6533 intEdgesDist.clear();
6534 double minIntDist = Precision::Infinite();
6535 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6537 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6538 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6539 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6541 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6542 double fact = ( 1.1 + dot * dot );
6543 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6544 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6545 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6546 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6547 dist1 = dist2 = Precision::Infinite();
6548 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
6549 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6552 if ( dist > testLen || dist <= 0 )
6555 if ( dist > testLen || dist <= 0 )
6558 // choose a closest edge
6559 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6560 double d1 = intP.SquareDistance( pSrc0 );
6561 double d2 = intP.SquareDistance( pSrc1 );
6562 int iClose = i + ( d2 < d1 );
6563 _LayerEdge* edge2 = ce._intEdges[iClose];
6564 edge2->Unset( _LayerEdge::MARKED );
6566 // choose a closest edge among neighbors
6567 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6568 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6569 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6571 _LayerEdge * edgeJ = intEdgesDist[j].first;
6572 if ( edge2->IsNeiborOnEdge( edgeJ ))
6574 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6575 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6578 intEdgesDist.push_back( make_pair( edge2, dist ));
6579 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6581 // iClose = i + !( d2 < d1 );
6582 // intEdges.push_back( ce._intEdges[iClose] );
6583 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6585 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6590 // compute new _normals
6591 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6593 _LayerEdge* edge2 = intEdgesDist[i].first;
6594 double distWgt = edge1->_len / intEdgesDist[i].second;
6595 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6596 // edge2->Is( _LayerEdge::BLOCKED )) continue;
6597 if ( edge2->Is( _LayerEdge::MARKED )) continue;
6598 edge2->Set( _LayerEdge::MARKED );
6601 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6603 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6604 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6605 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6606 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6607 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6608 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6609 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6610 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6611 newNormal.Normalize();
6615 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6616 if ( cos1 < theMinSmoothCosin )
6618 newCos = cos2 * sgn1;
6620 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6622 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6626 newCos = edge1->_cosin;
6629 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6630 e2neIt->second._normal += distWgt * newNormal;
6631 e2neIt->second._cosin = newCos;
6632 e2neIt->second._maxLen = 0.7 * minIntDist / edge1->_lenFactor;
6633 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6634 e2neIt->second._normal += dir2;
6635 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6636 e2neIt->second._normal += distWgt * newNormal;
6637 e2neIt->second._cosin = edge2->_cosin;
6638 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6639 e2neIt->second._normal += dir1;
6643 if ( edge2newEdge.empty() )
6644 break; //return true;
6646 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6648 // Update data of edges depending on a new _normal
6651 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6653 _LayerEdge* edge = e2neIt->first;
6654 if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6655 _LayerEdge& newEdge = e2neIt->second;
6656 _EdgesOnShape* eos = data.GetShapeEdges( edge );
6658 // Check if a new _normal is OK:
6659 newEdge._normal.Normalize();
6660 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6662 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6664 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6665 edge->_maxLen = newEdge._maxLen;
6666 edge->SetNewLength( newEdge._maxLen, *eos, helper );
6668 continue; // the new _normal is bad
6670 // the new _normal is OK
6672 // find shapes that need smoothing due to change of _normal
6673 if ( edge->_cosin < theMinSmoothCosin &&
6674 newEdge._cosin > theMinSmoothCosin )
6676 if ( eos->_sWOL.IsNull() )
6678 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6679 while ( fIt->more() )
6680 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6682 else // edge inflates along a FACE
6684 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6685 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
6686 while ( const TopoDS_Shape* E = eIt->next() )
6688 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6689 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6690 if ( angle < M_PI / 2 )
6691 shapesToSmooth.insert( data.GetShapeEdges( *E ));
6696 double len = edge->_len;
6697 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6698 edge->SetNormal( newEdge._normal );
6699 edge->SetCosin( newEdge._cosin );
6700 edge->SetNewLength( len, *eos, helper );
6701 edge->Set( _LayerEdge::MARKED );
6702 edge->Set( _LayerEdge::NORMAL_UPDATED );
6703 edgesNoAnaSmooth.insert( eos );
6706 // Update normals and other dependent data of not intersecting _LayerEdge's
6707 // neighboring the intersecting ones
6709 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6711 _LayerEdge* edge1 = e2neIt->first;
6712 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6713 if ( !edge1->Is( _LayerEdge::MARKED ))
6716 if ( edge1->IsOnEdge() )
6718 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6719 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6720 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6723 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6725 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6727 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6728 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6729 continue; // j-th neighbor is also intersected
6730 _LayerEdge* prevEdge = edge1;
6731 const int nbSteps = 10;
6732 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6734 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6735 neighbor->Is( _LayerEdge::MARKED ))
6737 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6738 if ( !eos ) continue;
6739 _LayerEdge* nextEdge = neighbor;
6740 if ( neighbor->_2neibors )
6743 nextEdge = neighbor->_2neibors->_edges[iNext];
6744 if ( nextEdge == prevEdge )
6745 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6747 double r = double(step-1)/nbSteps/(iter+1);
6748 if ( !nextEdge->_2neibors )
6751 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6752 newNorm.Normalize();
6753 if ( !isNewNormalOk( data, *neighbor, newNorm ))
6756 double len = neighbor->_len;
6757 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6758 neighbor->SetNormal( newNorm );
6759 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6760 if ( neighbor->_2neibors )
6761 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6762 neighbor->SetNewLength( len, *eos, helper );
6763 neighbor->Set( _LayerEdge::MARKED );
6764 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6765 edgesNoAnaSmooth.insert( eos );
6767 if ( !neighbor->_2neibors )
6768 break; // neighbor is on VERTEX
6770 // goto the next neighbor
6771 prevEdge = neighbor;
6772 neighbor = nextEdge;
6779 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6784 //================================================================================
6786 * \brief Check if a new normal is OK
6788 //================================================================================
6790 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
6792 const gp_XYZ& newNormal)
6794 // check a min angle between the newNormal and surrounding faces
6795 vector<_Simplex> simplices;
6796 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6797 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6798 double newMinDot = 1, curMinDot = 1;
6799 for ( size_t i = 0; i < simplices.size(); ++i )
6801 n1.Set( simplices[i]._nPrev );
6802 n2.Set( simplices[i]._nNext );
6803 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6804 double normLen2 = normFace.SquareModulus();
6805 if ( normLen2 < std::numeric_limits<double>::min() )
6807 normFace /= Sqrt( normLen2 );
6808 newMinDot = Min( newNormal * normFace, newMinDot );
6809 curMinDot = Min( edge._normal * normFace, curMinDot );
6812 if ( newMinDot < 0.5 )
6814 ok = ( newMinDot >= curMinDot * 0.9 );
6815 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6816 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6817 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6823 //================================================================================
6825 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6827 //================================================================================
6829 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
6830 SMESH_MesherHelper& helper,
6832 const double stepSize )
6834 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6835 return true; // no shapes needing smoothing
6837 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6839 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6840 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
6841 !eos._hyp.ToSmooth() ||
6842 eos.ShapeType() != TopAbs_FACE ||
6843 eos._edges.empty() )
6846 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6847 if ( !toSmooth ) continue;
6849 for ( size_t i = 0; i < eos._edges.size(); ++i )
6851 _LayerEdge* edge = eos._edges[i];
6852 if ( !edge->Is( _LayerEdge::SMOOTHED ))
6854 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6857 const gp_XYZ& pPrev = edge->PrevPos();
6858 const gp_XYZ& pLast = edge->_pos.back();
6859 gp_XYZ stepVec = pLast - pPrev;
6860 double realStepSize = stepVec.Modulus();
6861 if ( realStepSize < numeric_limits<double>::min() )
6864 edge->_lenFactor = realStepSize / stepSize;
6865 edge->_normal = stepVec / realStepSize;
6866 edge->Set( _LayerEdge::NORMAL_UPDATED );
6873 //================================================================================
6875 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6877 //================================================================================
6879 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6881 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6883 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6884 if ( eov._eosC1.empty() ||
6885 eov.ShapeType() != TopAbs_VERTEX ||
6886 eov._edges.empty() )
6889 gp_XYZ newNorm = eov._edges[0]->_normal;
6890 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6891 bool normChanged = false;
6893 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6895 _EdgesOnShape* eoe = eov._eosC1[i];
6896 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6897 const double eLen = SMESH_Algo::EdgeLength( e );
6898 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
6899 if ( oppV.IsSame( eov._shape ))
6900 oppV = SMESH_MesherHelper::IthVertex( 1, e );
6901 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6902 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6903 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6905 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6906 if ( curThickOpp + curThick < eLen )
6909 double wgt = 2. * curThick / eLen;
6910 newNorm += wgt * eovOpp->_edges[0]->_normal;
6915 eov._edges[0]->SetNormal( newNorm.Normalized() );
6916 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6921 //================================================================================
6923 * \brief Modify normals of _LayerEdge's on _ConvexFace's
6925 //================================================================================
6927 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
6928 SMESH_MesherHelper& helper,
6931 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6934 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6935 for ( ; id2face != data._convexFaces.end(); ++id2face )
6937 _ConvexFace & convFace = (*id2face).second;
6938 if ( convFace._normalsFixed )
6939 continue; // already fixed
6940 if ( convFace.CheckPrisms() )
6941 continue; // nothing to fix
6943 convFace._normalsFixed = true;
6945 BRepAdaptor_Surface surface ( convFace._face, false );
6946 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
6948 // check if the convex FACE is of spherical shape
6950 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6954 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6955 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6957 _EdgesOnShape& eos = *(id2eos->second);
6958 if ( eos.ShapeType() == TopAbs_VERTEX )
6960 _LayerEdge* ledge = eos._edges[ 0 ];
6961 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6962 centersBox.Add( center );
6964 for ( size_t i = 0; i < eos._edges.size(); ++i )
6965 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6967 if ( centersBox.IsVoid() )
6969 debugMsg( "Error: centersBox.IsVoid()" );
6972 const bool isSpherical =
6973 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6975 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6976 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6980 // set _LayerEdge::_normal as average of all normals
6982 // WARNING: different density of nodes on EDGEs is not taken into account that
6983 // can lead to an improper new normal
6985 gp_XYZ avgNormal( 0,0,0 );
6987 id2eos = convFace._subIdToEOS.begin();
6988 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6990 _EdgesOnShape& eos = *(id2eos->second);
6991 // set data of _CentralCurveOnEdge
6992 if ( eos.ShapeType() == TopAbs_EDGE )
6994 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6995 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6996 if ( !eos._sWOL.IsNull() )
6997 ceCurve._adjFace.Nullify();
6999 ceCurve._ledges.insert( ceCurve._ledges.end(),
7000 eos._edges.begin(), eos._edges.end());
7002 // summarize normals
7003 for ( size_t i = 0; i < eos._edges.size(); ++i )
7004 avgNormal += eos._edges[ i ]->_normal;
7006 double normSize = avgNormal.SquareModulus();
7007 if ( normSize < 1e-200 )
7009 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7012 avgNormal /= Sqrt( normSize );
7014 // compute new _LayerEdge::_cosin on EDGEs
7015 double avgCosin = 0;
7018 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7020 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7021 if ( ceCurve._adjFace.IsNull() )
7023 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7025 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7026 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7029 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7030 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7031 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7037 avgCosin /= nbCosin;
7039 // set _LayerEdge::_normal = avgNormal
7040 id2eos = convFace._subIdToEOS.begin();
7041 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7043 _EdgesOnShape& eos = *(id2eos->second);
7044 if ( eos.ShapeType() != TopAbs_EDGE )
7045 for ( size_t i = 0; i < eos._edges.size(); ++i )
7046 eos._edges[ i ]->_cosin = avgCosin;
7048 for ( size_t i = 0; i < eos._edges.size(); ++i )
7050 eos._edges[ i ]->SetNormal( avgNormal );
7051 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7055 else // if ( isSpherical )
7057 // We suppose that centers of curvature at all points of the FACE
7058 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7059 // having a common center of curvature we define the same new normal
7060 // as a sum of normals of _LayerEdge's on EDGEs among them.
7062 // get all centers of curvature for each EDGE
7064 helper.SetSubShape( convFace._face );
7065 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7067 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7068 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7070 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7072 // set adjacent FACE
7073 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7075 // get _LayerEdge's of the EDGE
7076 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7077 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7078 if ( !eos || eos->_edges.empty() )
7080 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7081 for ( int iV = 0; iV < 2; ++iV )
7083 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7084 TGeomID vID = meshDS->ShapeToIndex( v );
7085 eos = data.GetShapeEdges( vID );
7086 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7088 edgeLEdge = &vertexLEdges[0];
7089 edgeLEdgeEnd = edgeLEdge + 2;
7091 centerCurves[ iE ]._adjFace.Nullify();
7095 if ( ! eos->_toSmooth )
7096 data.SortOnEdge( edge, eos->_edges );
7097 edgeLEdge = &eos->_edges[ 0 ];
7098 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7099 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7100 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7102 if ( ! eos->_sWOL.IsNull() )
7103 centerCurves[ iE ]._adjFace.Nullify();
7106 // Get curvature centers
7110 if ( edgeLEdge[0]->IsOnEdge() &&
7111 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7113 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7114 centersBox.Add( center );
7116 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7117 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7118 { // EDGE or VERTEXes
7119 centerCurves[ iE ].Append( center, *edgeLEdge );
7120 centersBox.Add( center );
7122 if ( edgeLEdge[-1]->IsOnEdge() &&
7123 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7125 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7126 centersBox.Add( center );
7128 centerCurves[ iE ]._isDegenerated =
7129 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7131 } // loop on EDGES of convFace._face to set up data of centerCurves
7133 // Compute new normals for _LayerEdge's on EDGEs
7135 double avgCosin = 0;
7138 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7140 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7141 if ( ceCurve._isDegenerated )
7143 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7144 vector< gp_XYZ > & newNormals = ceCurve._normals;
7145 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7148 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7151 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7153 if ( isOK && !ceCurve._adjFace.IsNull() )
7155 // compute new _LayerEdge::_cosin
7156 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7157 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7160 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7161 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7162 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7168 // set new normals to _LayerEdge's of NOT degenerated central curves
7169 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7171 if ( centerCurves[ iE ]._isDegenerated )
7173 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7175 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7176 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7179 // set new normals to _LayerEdge's of degenerated central curves
7180 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7182 if ( !centerCurves[ iE ]._isDegenerated ||
7183 centerCurves[ iE ]._ledges.size() < 3 )
7185 // new normal is an average of new normals at VERTEXes that
7186 // was computed on non-degenerated _CentralCurveOnEdge's
7187 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7188 centerCurves[ iE ]._ledges.back ()->_normal );
7189 double sz = newNorm.Modulus();
7193 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7194 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7195 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7197 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7198 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7199 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7203 // Find new normals for _LayerEdge's based on FACE
7206 avgCosin /= nbCosin;
7207 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7208 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7209 if ( id2eos != convFace._subIdToEOS.end() )
7213 _EdgesOnShape& eos = * ( id2eos->second );
7214 for ( size_t i = 0; i < eos._edges.size(); ++i )
7216 _LayerEdge* ledge = eos._edges[ i ];
7217 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7219 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7221 iE = iE % centerCurves.size();
7222 if ( centerCurves[ iE ]._isDegenerated )
7224 newNorm.SetCoord( 0,0,0 );
7225 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7227 ledge->SetNormal( newNorm );
7228 ledge->_cosin = avgCosin;
7229 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7236 } // not a quasi-spherical FACE
7238 // Update _LayerEdge's data according to a new normal
7240 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7241 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7243 id2eos = convFace._subIdToEOS.begin();
7244 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7246 _EdgesOnShape& eos = * ( id2eos->second );
7247 for ( size_t i = 0; i < eos._edges.size(); ++i )
7249 _LayerEdge* & ledge = eos._edges[ i ];
7250 double len = ledge->_len;
7251 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7252 ledge->SetCosin( ledge->_cosin );
7253 ledge->SetNewLength( len, eos, helper );
7255 if ( eos.ShapeType() != TopAbs_FACE )
7256 for ( size_t i = 0; i < eos._edges.size(); ++i )
7258 _LayerEdge* ledge = eos._edges[ i ];
7259 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7261 _LayerEdge* neibor = ledge->_neibors[iN];
7262 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7264 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7265 neibor->Set( _LayerEdge::MOVED );
7266 neibor->SetSmooLen( neibor->_len );
7270 } // loop on sub-shapes of convFace._face
7272 // Find FACEs adjacent to convFace._face that got necessity to smooth
7273 // as a result of normals modification
7275 set< _EdgesOnShape* > adjFacesToSmooth;
7276 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7278 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7279 centerCurves[ iE ]._adjFaceToSmooth )
7281 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7283 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7285 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7290 data.AddShapesToSmooth( adjFacesToSmooth );
7295 } // loop on data._convexFaces
7300 //================================================================================
7302 * \brief Finds a center of curvature of a surface at a _LayerEdge
7304 //================================================================================
7306 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7307 BRepLProp_SLProps& surfProp,
7308 SMESH_MesherHelper& helper,
7309 gp_Pnt & center ) const
7311 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7312 surfProp.SetParameters( uv.X(), uv.Y() );
7313 if ( !surfProp.IsCurvatureDefined() )
7316 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7317 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7318 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7319 if ( surfCurvatureMin > surfCurvatureMax )
7320 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7322 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7327 //================================================================================
7329 * \brief Check that prisms are not distorted
7331 //================================================================================
7333 bool _ConvexFace::CheckPrisms() const
7336 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7338 const _LayerEdge* edge = _simplexTestEdges[i];
7339 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7340 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7341 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7343 debugMsg( "Bad simplex of _simplexTestEdges ("
7344 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7345 << " "<< edge->_simplices[j]._nPrev->GetID()
7346 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7353 //================================================================================
7355 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7356 * stored in this _CentralCurveOnEdge.
7357 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7358 * \param [in,out] newNormal - current normal at this point, to be redefined
7359 * \return bool - true if succeeded.
7361 //================================================================================
7363 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7365 if ( this->_isDegenerated )
7368 // find two centers the given one lies between
7370 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7372 double sl2 = 1.001 * _segLength2[ i ];
7374 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7378 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7379 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7384 double r = d1 / ( d1 + d2 );
7385 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7386 ( r ) * _ledges[ i+1 ]->_normal );
7390 double sz = newNormal.Modulus();
7399 //================================================================================
7401 * \brief Set shape members
7403 //================================================================================
7405 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7406 const _ConvexFace& convFace,
7408 SMESH_MesherHelper& helper)
7412 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7413 while ( const TopoDS_Shape* F = fIt->next())
7414 if ( !convFace._face.IsSame( *F ))
7416 _adjFace = TopoDS::Face( *F );
7417 _adjFaceToSmooth = false;
7418 // _adjFace already in a smoothing queue ?
7419 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7420 _adjFaceToSmooth = eos->_toSmooth;
7425 //================================================================================
7427 * \brief Looks for intersection of it's last segment with faces
7428 * \param distance - returns shortest distance from the last node to intersection
7430 //================================================================================
7432 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7434 const double& epsilon,
7436 const SMDS_MeshElement** intFace)
7438 vector< const SMDS_MeshElement* > suspectFaces;
7440 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7441 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7443 bool segmentIntersected = false;
7444 distance = Precision::Infinite();
7445 int iFace = -1; // intersected face
7446 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7448 const SMDS_MeshElement* face = suspectFaces[j];
7449 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7450 face->GetNodeIndex( _nodes[0] ) >= 0 )
7451 continue; // face sharing _LayerEdge node
7452 const int nbNodes = face->NbCornerNodes();
7453 bool intFound = false;
7455 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7458 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7462 const SMDS_MeshNode* tria[3];
7465 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7468 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7474 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7475 segmentIntersected = true;
7476 if ( distance > dist )
7477 distance = dist, iFace = j;
7480 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7484 if ( segmentIntersected )
7487 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7488 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7489 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7490 << ", intersection with face ("
7491 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7492 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7493 << ") distance = " << distance << endl;
7497 return segmentIntersected;
7500 //================================================================================
7502 * \brief Returns a point used to check orientation of _simplices
7504 //================================================================================
7506 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7508 size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7510 if ( !eos || eos->_sWOL.IsNull() )
7513 if ( eos->SWOLType() == TopAbs_EDGE )
7515 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7517 //else // TopAbs_FACE
7519 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7522 //================================================================================
7524 * \brief Returns size and direction of the last segment
7526 //================================================================================
7528 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7530 // find two non-coincident positions
7531 gp_XYZ orig = _pos.back();
7533 int iPrev = _pos.size() - 2;
7534 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7535 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7536 while ( iPrev >= 0 )
7538 vec = orig - _pos[iPrev];
7539 if ( vec.SquareModulus() > tol*tol )
7549 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7550 segDir.SetDirection( _normal );
7555 gp_Pnt pPrev = _pos[ iPrev ];
7556 if ( !eos._sWOL.IsNull() )
7558 TopLoc_Location loc;
7559 if ( eos.SWOLType() == TopAbs_EDGE )
7562 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7563 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7567 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7568 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7570 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7572 segDir.SetLocation( pPrev );
7573 segDir.SetDirection( vec );
7574 segLen = vec.Modulus();
7580 //================================================================================
7582 * \brief Return the last position of the target node on a FACE.
7583 * \param [in] F - the FACE this _LayerEdge is inflated along
7584 * \return gp_XY - result UV
7586 //================================================================================
7588 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7590 if ( F.IsSame( eos._sWOL )) // F is my FACE
7591 return gp_XY( _pos.back().X(), _pos.back().Y() );
7593 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7594 return gp_XY( 1e100, 1e100 );
7596 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7597 double f, l, u = _pos.back().X();
7598 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7599 if ( !C2d.IsNull() && f <= u && u <= l )
7600 return C2d->Value( u ).XY();
7602 return gp_XY( 1e100, 1e100 );
7605 //================================================================================
7607 * \brief Test intersection of the last segment with a given triangle
7608 * using Moller-Trumbore algorithm
7609 * Intersection is detected if distance to intersection is less than _LayerEdge._len
7611 //================================================================================
7613 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7614 const gp_XYZ& vert0,
7615 const gp_XYZ& vert1,
7616 const gp_XYZ& vert2,
7618 const double& EPSILON) const
7620 const gp_Pnt& orig = lastSegment.Location();
7621 const gp_Dir& dir = lastSegment.Direction();
7623 /* calculate distance from vert0 to ray origin */
7624 //gp_XYZ tvec = orig.XYZ() - vert0;
7626 //if ( tvec * dir > EPSILON )
7627 // intersected face is at back side of the temporary face this _LayerEdge belongs to
7630 gp_XYZ edge1 = vert1 - vert0;
7631 gp_XYZ edge2 = vert2 - vert0;
7633 /* begin calculating determinant - also used to calculate U parameter */
7634 gp_XYZ pvec = dir.XYZ() ^ edge2;
7636 /* if determinant is near zero, ray lies in plane of triangle */
7637 double det = edge1 * pvec;
7639 const double ANGL_EPSILON = 1e-12;
7640 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7643 /* calculate distance from vert0 to ray origin */
7644 gp_XYZ tvec = orig.XYZ() - vert0;
7646 /* calculate U parameter and test bounds */
7647 double u = ( tvec * pvec ) / det;
7648 //if (u < 0.0 || u > 1.0)
7649 if ( u < -EPSILON || u > 1.0 + EPSILON )
7652 /* prepare to test V parameter */
7653 gp_XYZ qvec = tvec ^ edge1;
7655 /* calculate V parameter and test bounds */
7656 double v = (dir.XYZ() * qvec) / det;
7657 //if ( v < 0.0 || u + v > 1.0 )
7658 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7661 /* calculate t, ray intersects triangle */
7662 t = (edge2 * qvec) / det;
7668 //================================================================================
7670 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7671 * neighbor _LayerEdge's by it's own inflation vector.
7672 * \param [in] eov - EOS of the VERTEX
7673 * \param [in] eos - EOS of the FACE
7674 * \param [in] step - inflation step
7675 * \param [in,out] badSmooEdges - not untangled _LayerEdge's
7677 //================================================================================
7679 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
7680 const _EdgesOnShape* eos,
7682 vector< _LayerEdge* > & badSmooEdges )
7684 // check if any of _neibors is in badSmooEdges
7685 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7686 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7689 // get all edges to move
7691 set< _LayerEdge* > edges;
7693 // find a distance between _LayerEdge on VERTEX and its neighbors
7694 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
7696 for ( size_t i = 0; i < _neibors.size(); ++i )
7698 _LayerEdge* nEdge = _neibors[i];
7699 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7701 edges.insert( nEdge );
7702 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7705 // add _LayerEdge's close to curPosV
7709 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7711 _LayerEdge* edgeF = *e;
7712 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7714 _LayerEdge* nEdge = edgeF->_neibors[i];
7715 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7716 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7717 edges.insert( nEdge );
7721 while ( nbE < edges.size() );
7723 // move the target node of the got edges
7725 gp_XYZ prevPosV = PrevPos();
7726 if ( eov->SWOLType() == TopAbs_EDGE )
7728 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7729 prevPosV = curve.Value( prevPosV.X() ).XYZ();
7731 else if ( eov->SWOLType() == TopAbs_FACE )
7733 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7734 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7737 SMDS_FacePosition* fPos;
7738 //double r = 1. - Min( 0.9, step / 10. );
7739 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7741 _LayerEdge* edgeF = *e;
7742 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
7743 const gp_XYZ newPosF = curPosV + prevVF;
7744 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7745 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7746 edgeF->_pos.back() = newPosF;
7747 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7749 // set _curvature to make edgeF updated by putOnOffsetSurface()
7750 if ( !edgeF->_curvature )
7751 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7753 edgeF->_curvature = new _Curvature;
7754 edgeF->_curvature->_r = 0;
7755 edgeF->_curvature->_k = 0;
7756 edgeF->_curvature->_h2lenRatio = 0;
7757 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7760 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7761 // SMESH_TNodeXYZ( _nodes[0] ));
7762 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7764 // _LayerEdge* edgeF = *e;
7765 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7766 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7767 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7768 // edgeF->_pos.back() = newPosF;
7769 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7772 // smooth _LayerEdge's around moved nodes
7773 //size_t nbBadBefore = badSmooEdges.size();
7774 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7776 _LayerEdge* edgeF = *e;
7777 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7778 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7779 //&& !edges.count( edgeF->_neibors[j] ))
7781 _LayerEdge* edgeFN = edgeF->_neibors[j];
7782 edgeFN->Unset( SMOOTHED );
7783 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7786 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7787 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7788 // int nbBadAfter = edgeFN->_simplices.size();
7790 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7792 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7794 // if ( nbBadAfter <= nbBad )
7796 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7797 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7798 // edgeF->_pos.back() = newPosF;
7799 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7800 // nbBad = nbBadAfter;
7804 badSmooEdges.push_back( edgeFN );
7807 // move a bit not smoothed around moved nodes
7808 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7810 // _LayerEdge* edgeF = badSmooEdges[i];
7811 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7812 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7813 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7814 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7815 // edgeF->_pos.back() = newPosF;
7816 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7820 //================================================================================
7822 * \brief Perform smooth of _LayerEdge's based on EDGE's
7823 * \retval bool - true if node has been moved
7825 //================================================================================
7827 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7828 const TopoDS_Face& F,
7829 SMESH_MesherHelper& helper)
7831 ASSERT( IsOnEdge() );
7833 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7834 SMESH_TNodeXYZ oldPos( tgtNode );
7835 double dist01, distNewOld;
7837 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7838 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7839 dist01 = p0.Distance( _2neibors->tgtNode(1) );
7841 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7842 double lenDelta = 0;
7845 //lenDelta = _curvature->lenDelta( _len );
7846 lenDelta = _curvature->lenDeltaByDist( dist01 );
7847 newPos.ChangeCoord() += _normal * lenDelta;
7850 distNewOld = newPos.Distance( oldPos );
7854 if ( _2neibors->_plnNorm )
7856 // put newPos on the plane defined by source node and _plnNorm
7857 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7858 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7859 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7861 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7862 _pos.back() = newPos.XYZ();
7866 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7867 gp_XY uv( Precision::Infinite(), 0 );
7868 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7869 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7871 newPos = surface->Value( uv );
7872 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7875 // commented for IPAL0052478
7876 // if ( _curvature && lenDelta < 0 )
7878 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7879 // _len -= prevPos.Distance( oldPos );
7880 // _len += prevPos.Distance( newPos );
7882 bool moved = distNewOld > dist01/50;
7884 dumpMove( tgtNode ); // debug
7889 //================================================================================
7891 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7893 //================================================================================
7895 void _LayerEdge::SmoothWoCheck()
7897 if ( Is( DIFFICULT ))
7900 bool moved = Is( SMOOTHED );
7901 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
7902 moved = _neibors[i]->Is( SMOOTHED );
7906 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7908 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7909 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7910 _pos.back() = newPos;
7912 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7915 //================================================================================
7917 * \brief Checks validity of _neibors on EDGEs and VERTEXes
7919 //================================================================================
7921 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7923 if ( ! Is( NEAR_BOUNDARY ))
7928 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7930 _LayerEdge* eN = _neibors[iN];
7931 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7934 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7935 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7936 eN->_pos.size() != _pos.size() );
7938 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7939 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7940 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7941 if ( eN->_nodes.size() > 1 &&
7942 eN->_simplices[i].Includes( _nodes.back() ) &&
7943 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7948 badNeibors->push_back( eN );
7949 debugMsg("Bad boundary simplex ( "
7950 << " "<< eN->_nodes[0]->GetID()
7951 << " "<< eN->_nodes.back()->GetID()
7952 << " "<< eN->_simplices[i]._nPrev->GetID()
7953 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7964 //================================================================================
7966 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7967 * \retval int - nb of bad simplices around this _LayerEdge
7969 //================================================================================
7971 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7973 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7974 return 0; // shape of simplices not changed
7975 if ( _simplices.size() < 2 )
7976 return 0; // _LayerEdge inflated along EDGE or FACE
7978 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7981 const gp_XYZ& curPos = _pos.back();
7982 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7984 // quality metrics (orientation) of tetras around _tgtNode
7986 double vol, minVolBefore = 1e100;
7987 for ( size_t i = 0; i < _simplices.size(); ++i )
7989 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7990 minVolBefore = Min( minVolBefore, vol );
7992 int nbBad = _simplices.size() - nbOkBefore;
7994 bool bndNeedSmooth = false;
7996 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8000 // evaluate min angle
8001 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8003 size_t nbGoodAngles = _simplices.size();
8005 for ( size_t i = 0; i < _simplices.size(); ++i )
8007 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8010 if ( nbGoodAngles == _simplices.size() )
8016 if ( Is( ON_CONCAVE_FACE ))
8019 if ( step % 2 == 0 )
8022 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8024 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8025 _smooFunction = _funs[ FUN_CENTROIDAL ];
8027 _smooFunction = _funs[ FUN_LAPLACIAN ];
8030 // compute new position for the last _pos using different _funs
8033 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8036 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8037 else if ( _funs[ iFun ] == _smooFunction )
8038 continue; // _smooFunction again
8039 else if ( step > 1 )
8040 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8042 break; // let "easy" functions improve elements around distorted ones
8046 double delta = _curvature->lenDelta( _len );
8048 newPos += _normal * delta;
8051 double segLen = _normal * ( newPos - prevPos );
8052 if ( segLen + delta > 0 )
8053 newPos += _normal * delta;
8055 // double segLenChange = _normal * ( curPos - newPos );
8056 // newPos += 0.5 * _normal * segLenChange;
8060 double minVolAfter = 1e100;
8061 for ( size_t i = 0; i < _simplices.size(); ++i )
8063 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8064 minVolAfter = Min( minVolAfter, vol );
8067 if ( nbOkAfter < nbOkBefore )
8071 ( nbOkAfter == nbOkBefore ) &&
8072 ( minVolAfter <= minVolBefore ))
8075 nbBad = _simplices.size() - nbOkAfter;
8076 minVolBefore = minVolAfter;
8077 nbOkBefore = nbOkAfter;
8080 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8081 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8082 _pos.back() = newPos;
8084 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8085 << (nbBad ? " --BAD" : ""));
8089 continue; // look for a better function
8095 } // loop on smoothing functions
8097 if ( moved ) // notify _neibors
8100 for ( size_t i = 0; i < _neibors.size(); ++i )
8101 if ( !_neibors[i]->Is( MOVED ))
8103 _neibors[i]->Set( MOVED );
8104 toSmooth.push_back( _neibors[i] );
8111 //================================================================================
8113 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8114 * \retval int - nb of bad simplices around this _LayerEdge
8116 //================================================================================
8118 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8120 if ( !_smooFunction )
8121 return 0; // _LayerEdge inflated along EDGE or FACE
8123 return 0; // not inflated
8125 const gp_XYZ& curPos = _pos.back();
8126 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8128 // quality metrics (orientation) of tetras around _tgtNode
8130 double vol, minVolBefore = 1e100;
8131 for ( size_t i = 0; i < _simplices.size(); ++i )
8133 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8134 minVolBefore = Min( minVolBefore, vol );
8136 int nbBad = _simplices.size() - nbOkBefore;
8138 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8140 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8141 _smooFunction = _funs[ FUN_LAPLACIAN ];
8142 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8143 _smooFunction = _funs[ FUN_CENTROIDAL ];
8146 // compute new position for the last _pos using different _funs
8148 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8151 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8152 else if ( _funs[ iFun ] == _smooFunction )
8153 continue; // _smooFunction again
8154 else if ( step > 1 )
8155 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8157 break; // let "easy" functions improve elements around distorted ones
8161 double delta = _curvature->lenDelta( _len );
8163 newPos += _normal * delta;
8166 double segLen = _normal * ( newPos - prevPos );
8167 if ( segLen + delta > 0 )
8168 newPos += _normal * delta;
8170 // double segLenChange = _normal * ( curPos - newPos );
8171 // newPos += 0.5 * _normal * segLenChange;
8175 double minVolAfter = 1e100;
8176 for ( size_t i = 0; i < _simplices.size(); ++i )
8178 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8179 minVolAfter = Min( minVolAfter, vol );
8182 if ( nbOkAfter < nbOkBefore )
8184 if (( isConcaveFace || findBest ) &&
8185 ( nbOkAfter == nbOkBefore ) &&
8186 ( minVolAfter <= minVolBefore )
8190 nbBad = _simplices.size() - nbOkAfter;
8191 minVolBefore = minVolAfter;
8192 nbOkBefore = nbOkAfter;
8194 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8195 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8196 _pos.back() = newPos;
8198 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8199 << ( nbBad ? "--BAD" : ""));
8201 // commented for IPAL0052478
8202 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8203 // _len += prevPos.Distance(newPos);
8205 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8207 //_smooFunction = _funs[ iFun ];
8208 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8209 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8210 // << " minVol: " << minVolAfter
8211 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8213 continue; // look for a better function
8219 } // loop on smoothing functions
8224 //================================================================================
8226 * \brief Chooses a smoothing technic giving a position most close to an initial one.
8227 * For a correct result, _simplices must contain nodes lying on geometry.
8229 //================================================================================
8231 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8232 const TNode2Edge& n2eMap)
8234 if ( _smooFunction ) return;
8236 // use smoothNefPolygon() near concaveVertices
8237 if ( !concaveVertices.empty() )
8239 _smooFunction = _funs[ FUN_CENTROIDAL ];
8241 Set( ON_CONCAVE_FACE );
8243 for ( size_t i = 0; i < _simplices.size(); ++i )
8245 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8247 _smooFunction = _funs[ FUN_NEFPOLY ];
8249 // set FUN_CENTROIDAL to neighbor edges
8250 for ( i = 0; i < _neibors.size(); ++i )
8252 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8254 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8261 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8262 // // where the nodes are smoothed too far along a sphere thus creating
8263 // // inverted _simplices
8264 // double dist[theNbSmooFuns];
8265 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8266 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8268 // double minDist = Precision::Infinite();
8269 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8270 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8272 // gp_Pnt newP = (this->*_funs[i])();
8273 // dist[i] = p.SquareDistance( newP );
8274 // if ( dist[i]*coef[i] < minDist )
8276 // _smooFunction = _funs[i];
8277 // minDist = dist[i]*coef[i];
8283 _smooFunction = _funs[ FUN_LAPLACIAN ];
8286 // for ( size_t i = 0; i < _simplices.size(); ++i )
8287 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8288 // if ( minDim == 0 )
8289 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8290 // else if ( minDim == 1 )
8291 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8295 // for ( int i = 0; i < FUN_NB; ++i )
8297 // //cout << dist[i] << " ";
8298 // if ( _smooFunction == _funs[i] ) {
8300 // //debugMsg( fNames[i] );
8304 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8307 //================================================================================
8309 * \brief Returns a name of _SmooFunction
8311 //================================================================================
8313 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8316 fun = _smooFunction;
8317 for ( int i = 0; i < theNbSmooFuns; ++i )
8318 if ( fun == _funs[i] )
8321 return theNbSmooFuns;
8324 //================================================================================
8326 * \brief Computes a new node position using Laplacian smoothing
8328 //================================================================================
8330 gp_XYZ _LayerEdge::smoothLaplacian()
8332 gp_XYZ newPos (0,0,0);
8333 for ( size_t i = 0; i < _simplices.size(); ++i )
8334 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8335 newPos /= _simplices.size();
8340 //================================================================================
8342 * \brief Computes a new node position using angular-based smoothing
8344 //================================================================================
8346 gp_XYZ _LayerEdge::smoothAngular()
8348 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8349 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8350 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8352 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8354 for ( size_t i = 0; i < _simplices.size(); ++i )
8356 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8357 edgeDir.push_back( p - pPrev );
8358 edgeSize.push_back( edgeDir.back().Magnitude() );
8359 if ( edgeSize.back() < numeric_limits<double>::min() )
8362 edgeSize.pop_back();
8366 edgeDir.back() /= edgeSize.back();
8367 points.push_back( p );
8372 edgeDir.push_back ( edgeDir[0] );
8373 edgeSize.push_back( edgeSize[0] );
8374 pN /= points.size();
8376 gp_XYZ newPos(0,0,0);
8378 for ( size_t i = 0; i < points.size(); ++i )
8380 gp_Vec toN = pN - points[i];
8381 double toNLen = toN.Magnitude();
8382 if ( toNLen < numeric_limits<double>::min() )
8387 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8388 double bisecLen = bisec.SquareMagnitude();
8389 if ( bisecLen < numeric_limits<double>::min() )
8391 gp_Vec norm = edgeDir[i] ^ toN;
8392 bisec = norm ^ edgeDir[i];
8393 bisecLen = bisec.SquareMagnitude();
8395 bisecLen = Sqrt( bisecLen );
8399 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8400 sumSize += bisecLen;
8402 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8403 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8409 // project newPos to an average plane
8411 gp_XYZ norm(0,0,0); // plane normal
8412 points.push_back( points[0] );
8413 for ( size_t i = 1; i < points.size(); ++i )
8415 gp_XYZ vec1 = points[ i-1 ] - pN;
8416 gp_XYZ vec2 = points[ i ] - pN;
8417 gp_XYZ cross = vec1 ^ vec2;
8420 if ( cross * norm < numeric_limits<double>::min() )
8421 norm += cross.Reversed();
8425 catch (Standard_Failure) { // if |cross| == 0.
8428 gp_XYZ vec = newPos - pN;
8429 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8430 newPos = newPos - r * norm;
8435 //================================================================================
8437 * \brief Computes a new node position using weigthed node positions
8439 //================================================================================
8441 gp_XYZ _LayerEdge::smoothLengthWeighted()
8443 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8444 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8446 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8447 for ( size_t i = 0; i < _simplices.size(); ++i )
8449 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8450 edgeSize.push_back( ( p - pPrev ).Modulus() );
8451 if ( edgeSize.back() < numeric_limits<double>::min() )
8453 edgeSize.pop_back();
8457 points.push_back( p );
8461 edgeSize.push_back( edgeSize[0] );
8463 gp_XYZ newPos(0,0,0);
8465 for ( size_t i = 0; i < points.size(); ++i )
8467 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8468 sumSize += edgeSize[i] + edgeSize[i+1];
8474 //================================================================================
8476 * \brief Computes a new node position using angular-based smoothing
8478 //================================================================================
8480 gp_XYZ _LayerEdge::smoothCentroidal()
8482 gp_XYZ newPos(0,0,0);
8483 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8485 for ( size_t i = 0; i < _simplices.size(); ++i )
8487 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8488 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8489 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8490 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8493 newPos += gc * size;
8500 //================================================================================
8502 * \brief Computes a new node position located inside a Nef polygon
8504 //================================================================================
8506 gp_XYZ _LayerEdge::smoothNefPolygon()
8507 #ifdef OLD_NEF_POLYGON
8509 gp_XYZ newPos(0,0,0);
8511 // get a plane to seach a solution on
8513 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8515 const double tol = numeric_limits<double>::min();
8516 gp_XYZ center(0,0,0);
8517 for ( i = 0; i < _simplices.size(); ++i )
8519 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8520 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8521 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8523 vecs.back() = vecs[0];
8524 center /= _simplices.size();
8526 gp_XYZ zAxis(0,0,0);
8527 for ( i = 0; i < _simplices.size(); ++i )
8528 zAxis += vecs[i] ^ vecs[i+1];
8531 for ( i = 0; i < _simplices.size(); ++i )
8534 if ( yAxis.SquareModulus() > tol )
8537 gp_XYZ xAxis = yAxis ^ zAxis;
8538 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8539 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8540 // p0.Distance( _simplices[2]._nPrev ));
8541 // gp_XYZ center = smoothLaplacian();
8542 // gp_XYZ xAxis, yAxis, zAxis;
8543 // for ( i = 0; i < _simplices.size(); ++i )
8545 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8546 // if ( xAxis.SquareModulus() > tol*tol )
8549 // for ( i = 1; i < _simplices.size(); ++i )
8551 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8552 // zAxis = xAxis ^ yAxis;
8553 // if ( zAxis.SquareModulus() > tol*tol )
8556 // if ( i == _simplices.size() ) return newPos;
8558 yAxis = zAxis ^ xAxis;
8559 xAxis /= xAxis.Modulus();
8560 yAxis /= yAxis.Modulus();
8562 // get half-planes of _simplices
8564 vector< _halfPlane > halfPlns( _simplices.size() );
8566 for ( size_t i = 0; i < _simplices.size(); ++i )
8568 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8569 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8570 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8571 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8572 gp_XY vec12 = p2 - p1;
8573 double dist12 = vec12.Modulus();
8577 halfPlns[ nbHP ]._pos = p1;
8578 halfPlns[ nbHP ]._dir = vec12;
8579 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8583 // intersect boundaries of half-planes, define state of intersection points
8584 // in relation to all half-planes and calculate internal point of a 2D polygon
8587 gp_XY newPos2D (0,0);
8589 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8590 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8591 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8593 vector< vector< TIntPntState > > allIntPnts( nbHP );
8594 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8596 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8597 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8599 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8600 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8603 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8605 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8607 if ( iHP1 == iHP2 ) continue;
8609 TIntPntState & ips1 = intPnts1[ iHP2 ];
8610 if ( ips1.second == UNDEF )
8612 // find an intersection point of boundaries of iHP1 and iHP2
8614 if ( iHP2 == iPrev ) // intersection with neighbors is known
8615 ips1.first = halfPlns[ iHP1 ]._pos;
8616 else if ( iHP2 == iNext )
8617 ips1.first = halfPlns[ iHP2 ]._pos;
8618 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8619 ips1.second = NO_INT;
8621 // classify the found intersection point
8622 if ( ips1.second != NO_INT )
8624 ips1.second = NOT_OUT;
8625 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8626 if ( i != iHP1 && i != iHP2 &&
8627 halfPlns[ i ].IsOut( ips1.first, tol ))
8628 ips1.second = IS_OUT;
8630 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8631 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8632 TIntPntState & ips2 = intPnts2[ iHP1 ];
8635 if ( ips1.second == NOT_OUT )
8638 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8642 // find a NOT_OUT segment of boundary which is located between
8643 // two NOT_OUT int points
8646 continue; // no such a segment
8650 // sort points along the boundary
8651 map< double, TIntPntState* > ipsByParam;
8652 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8654 TIntPntState & ips1 = intPnts1[ iHP2 ];
8655 if ( ips1.second != NO_INT )
8657 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8658 double param = op * halfPlns[ iHP1 ]._dir;
8659 ipsByParam.insert( make_pair( param, & ips1 ));
8662 // look for two neighboring NOT_OUT points
8664 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8665 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8667 TIntPntState & ips1 = *(u2ips->second);
8668 if ( ips1.second == NOT_OUT )
8669 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8670 else if ( nbNotOut >= 2 )
8677 if ( nbNotOut >= 2 )
8679 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8682 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8689 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8698 #else // OLD_NEF_POLYGON
8699 { ////////////////////////////////// NEW
8700 gp_XYZ newPos(0,0,0);
8702 // get a plane to seach a solution on
8705 gp_XYZ center(0,0,0);
8706 for ( i = 0; i < _simplices.size(); ++i )
8707 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8708 center /= _simplices.size();
8710 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8711 for ( i = 0; i < _simplices.size(); ++i )
8712 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8713 vecs.back() = vecs[0];
8715 const double tol = numeric_limits<double>::min();
8716 gp_XYZ zAxis(0,0,0);
8717 for ( i = 0; i < _simplices.size(); ++i )
8719 gp_XYZ cross = vecs[i] ^ vecs[i+1];
8722 if ( cross * zAxis < tol )
8723 zAxis += cross.Reversed();
8727 catch (Standard_Failure) { // if |cross| == 0.
8732 for ( i = 0; i < _simplices.size(); ++i )
8735 if ( yAxis.SquareModulus() > tol )
8738 gp_XYZ xAxis = yAxis ^ zAxis;
8739 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8740 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8741 // p0.Distance( _simplices[2]._nPrev ));
8742 // gp_XYZ center = smoothLaplacian();
8743 // gp_XYZ xAxis, yAxis, zAxis;
8744 // for ( i = 0; i < _simplices.size(); ++i )
8746 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8747 // if ( xAxis.SquareModulus() > tol*tol )
8750 // for ( i = 1; i < _simplices.size(); ++i )
8752 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8753 // zAxis = xAxis ^ yAxis;
8754 // if ( zAxis.SquareModulus() > tol*tol )
8757 // if ( i == _simplices.size() ) return newPos;
8759 yAxis = zAxis ^ xAxis;
8760 xAxis /= xAxis.Modulus();
8761 yAxis /= yAxis.Modulus();
8763 // get half-planes of _simplices
8765 vector< _halfPlane > halfPlns( _simplices.size() );
8767 for ( size_t i = 0; i < _simplices.size(); ++i )
8769 const gp_XYZ& OP1 = vecs[ i ];
8770 const gp_XYZ& OP2 = vecs[ i+1 ];
8771 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8772 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8773 gp_XY vec12 = p2 - p1;
8774 double dist12 = vec12.Modulus();
8778 halfPlns[ nbHP ]._pos = p1;
8779 halfPlns[ nbHP ]._dir = vec12;
8780 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8784 // intersect boundaries of half-planes, define state of intersection points
8785 // in relation to all half-planes and calculate internal point of a 2D polygon
8788 gp_XY newPos2D (0,0);
8790 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8791 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8792 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8794 vector< vector< TIntPntState > > allIntPnts( nbHP );
8795 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8797 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8798 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8800 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8801 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8804 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8806 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8808 if ( iHP1 == iHP2 ) continue;
8810 TIntPntState & ips1 = intPnts1[ iHP2 ];
8811 if ( ips1.second == UNDEF )
8813 // find an intersection point of boundaries of iHP1 and iHP2
8815 if ( iHP2 == iPrev ) // intersection with neighbors is known
8816 ips1.first = halfPlns[ iHP1 ]._pos;
8817 else if ( iHP2 == iNext )
8818 ips1.first = halfPlns[ iHP2 ]._pos;
8819 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8820 ips1.second = NO_INT;
8822 // classify the found intersection point
8823 if ( ips1.second != NO_INT )
8825 ips1.second = NOT_OUT;
8826 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8827 if ( i != iHP1 && i != iHP2 &&
8828 halfPlns[ i ].IsOut( ips1.first, tol ))
8829 ips1.second = IS_OUT;
8831 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8832 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8833 TIntPntState & ips2 = intPnts2[ iHP1 ];
8836 if ( ips1.second == NOT_OUT )
8839 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8843 // find a NOT_OUT segment of boundary which is located between
8844 // two NOT_OUT int points
8847 continue; // no such a segment
8851 // sort points along the boundary
8852 map< double, TIntPntState* > ipsByParam;
8853 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8855 TIntPntState & ips1 = intPnts1[ iHP2 ];
8856 if ( ips1.second != NO_INT )
8858 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8859 double param = op * halfPlns[ iHP1 ]._dir;
8860 ipsByParam.insert( make_pair( param, & ips1 ));
8863 // look for two neighboring NOT_OUT points
8865 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8866 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8868 TIntPntState & ips1 = *(u2ips->second);
8869 if ( ips1.second == NOT_OUT )
8870 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8871 else if ( nbNotOut >= 2 )
8878 if ( nbNotOut >= 2 )
8880 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8883 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8890 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8899 #endif // OLD_NEF_POLYGON
8901 //================================================================================
8903 * \brief Add a new segment to _LayerEdge during inflation
8905 //================================================================================
8907 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8912 if ( len > _maxLen )
8915 Block( eos.GetData() );
8917 const double lenDelta = len - _len;
8918 if ( lenDelta < len * 1e-3 )
8920 Block( eos.GetData() );
8924 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8925 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8927 if ( eos._hyp.IsOffsetMethod() )
8931 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8932 while ( faceIt->more() )
8934 const SMDS_MeshElement* face = faceIt->next();
8935 if ( !eos.GetNormal( face, faceNorm ))
8938 // translate plane of a face
8939 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8941 // find point of intersection of the face plane located at baryCenter
8942 // and _normal located at newXYZ
8943 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8944 double dot = ( faceNorm.XYZ() * _normal );
8945 if ( dot < std::numeric_limits<double>::min() )
8946 dot = lenDelta * 1e-3;
8947 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8948 newXYZ += step * _normal;
8950 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8954 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8957 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8958 _pos.push_back( newXYZ );
8960 if ( !eos._sWOL.IsNull() )
8964 if ( eos.SWOLType() == TopAbs_EDGE )
8966 double u = Precision::Infinite(); // to force projection w/o distance check
8967 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8968 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8969 _pos.back().SetCoord( u, 0, 0 );
8970 if ( _nodes.size() > 1 && uvOK )
8972 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8973 pos->SetUParameter( u );
8978 gp_XY uv( Precision::Infinite(), 0 );
8979 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8980 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8981 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8982 if ( _nodes.size() > 1 && uvOK )
8984 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8985 pos->SetUParameter( uv.X() );
8986 pos->SetVParameter( uv.Y() );
8991 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8995 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8997 Block( eos.GetData() );
9005 if ( eos.ShapeType() != TopAbs_FACE )
9007 for ( size_t i = 0; i < _neibors.size(); ++i )
9008 //if ( _len > _neibors[i]->GetSmooLen() )
9009 _neibors[i]->Set( MOVED );
9013 dumpMove( n ); //debug
9016 //================================================================================
9018 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9020 //================================================================================
9022 void _LayerEdge::Block( _SolidData& data )
9024 //if ( Is( BLOCKED )) return;
9028 std::queue<_LayerEdge*> queue;
9031 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9032 while ( !queue.empty() )
9034 _LayerEdge* edge = queue.front(); queue.pop();
9035 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9036 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9037 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9039 _LayerEdge* neibor = edge->_neibors[iN];
9040 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9042 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9043 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9044 double minDist = pSrc.SquareDistance( pSrcN );
9045 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9046 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9047 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9048 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9049 if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9051 newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9053 if ( neibor->_maxLen > newMaxLen )
9055 neibor->_maxLen = newMaxLen;
9056 if ( neibor->_maxLen < neibor->_len )
9058 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9059 while ( neibor->_len > neibor->_maxLen &&
9060 neibor->NbSteps() > 1 )
9061 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9062 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9063 //neibor->Block( data );
9065 queue.push( neibor );
9071 //================================================================================
9073 * \brief Remove last inflation step
9075 //================================================================================
9077 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9079 if ( _pos.size() > curStep && _nodes.size() > 1 )
9081 _pos.resize( curStep );
9083 gp_Pnt nXYZ = _pos.back();
9084 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9085 SMESH_TNodeXYZ curXYZ( n );
9086 if ( !eos._sWOL.IsNull() )
9088 TopLoc_Location loc;
9089 if ( eos.SWOLType() == TopAbs_EDGE )
9091 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9092 pos->SetUParameter( nXYZ.X() );
9094 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9095 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9099 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9100 pos->SetUParameter( nXYZ.X() );
9101 pos->SetVParameter( nXYZ.Y() );
9102 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9103 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9106 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9109 if ( restoreLength )
9111 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9116 //================================================================================
9118 * \brief Return index of a _pos distant from _normal
9120 //================================================================================
9122 int _LayerEdge::GetSmoothedPos( const double tol )
9125 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9127 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9128 if ( normDist > tol * tol )
9134 //================================================================================
9136 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9138 //================================================================================
9140 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9142 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9145 // find the 1st smoothed _pos
9146 int iSmoothed = GetSmoothedPos( tol );
9147 if ( !iSmoothed ) return;
9149 //if ( 1 || Is( DISTORTED ))
9151 gp_XYZ normal = _normal;
9152 if ( Is( NORMAL_UPDATED ))
9153 for ( size_t i = 1; i < _pos.size(); ++i )
9155 normal = _pos[i] - _pos[0];
9156 double size = normal.Modulus();
9157 if ( size > RealSmall() )
9163 const double r = 0.2;
9164 for ( int iter = 0; iter < 50; ++iter )
9167 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9169 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9170 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9172 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9173 double newLen = ( 1-r ) * midLen + r * segLen[i];
9174 const_cast< double& >( segLen[i] ) = newLen;
9175 // check angle between normal and (_pos[i+1], _pos[i] )
9176 gp_XYZ posDir = _pos[i+1] - _pos[i];
9177 double size = posDir.SquareModulus();
9178 if ( size > RealSmall() )
9179 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9181 if ( minDot > 0.5 * 0.5 )
9187 // for ( size_t i = 1; i < _pos.size()-1; ++i )
9189 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
9192 // double wgt = segLen[i] / segLen.back();
9193 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9194 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
9195 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
9196 // _pos[i] = newPos;
9201 //================================================================================
9203 * \brief Print flags
9205 //================================================================================
9207 std::string _LayerEdge::DumpFlags() const
9210 for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9211 if ( _flags & flag )
9213 EFlags f = (EFlags) flag;
9215 case TO_SMOOTH: dump << "TO_SMOOTH"; break;
9216 case MOVED: dump << "MOVED"; break;
9217 case SMOOTHED: dump << "SMOOTHED"; break;
9218 case DIFFICULT: dump << "DIFFICULT"; break;
9219 case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9220 case BLOCKED: dump << "BLOCKED"; break;
9221 case INTERSECTED: dump << "INTERSECTED"; break;
9222 case NORMAL_UPDATED: dump << "NORMAL_UPDATED"; break;
9223 case MARKED: dump << "MARKED"; break;
9224 case MULTI_NORMAL: dump << "MULTI_NORMAL"; break;
9225 case NEAR_BOUNDARY: dump << "NEAR_BOUNDARY"; break;
9226 case SMOOTHED_C1: dump << "SMOOTHED_C1"; break;
9227 case DISTORTED: dump << "DISTORTED"; break;
9228 case RISKY_SWOL: dump << "RISKY_SWOL"; break;
9229 case SHRUNK: dump << "SHRUNK"; break;
9230 case UNUSED_FLAG: dump << "UNUSED_FLAG"; break;
9234 cout << dump << endl;
9238 //================================================================================
9243 //================================================================================
9245 bool _ViscousBuilder::refine(_SolidData& data)
9247 SMESH_MesherHelper& helper = data.GetHelper();
9248 helper.SetElementsOnShape(false);
9250 Handle(Geom_Curve) curve;
9251 Handle(ShapeAnalysis_Surface) surface;
9252 TopoDS_Edge geomEdge;
9253 TopoDS_Face geomFace;
9254 TopLoc_Location loc;
9257 vector< gp_XYZ > pos3D;
9259 TGeomID prevBaseId = -1;
9260 TNode2Edge* n2eMap = 0;
9261 TNode2Edge::iterator n2e;
9263 // Create intermediate nodes on each _LayerEdge
9265 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9267 _EdgesOnShape& eos = data._edgesOnShape[iS];
9268 if ( eos._edges.empty() ) continue;
9270 if ( eos._edges[0]->_nodes.size() < 2 )
9271 continue; // on _noShrinkShapes
9273 // get data of a shrink shape
9275 geomEdge.Nullify(); geomFace.Nullify();
9276 curve.Nullify(); surface.Nullify();
9277 if ( !eos._sWOL.IsNull() )
9279 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9282 geomEdge = TopoDS::Edge( eos._sWOL );
9283 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9287 geomFace = TopoDS::Face( eos._sWOL );
9288 surface = helper.GetSurface( geomFace );
9291 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9293 geomFace = TopoDS::Face( eos._shape );
9294 surface = helper.GetSurface( geomFace );
9295 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9296 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9298 eos._eosC1[ i ]->_toSmooth = true;
9299 for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9300 eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9304 vector< double > segLen;
9305 for ( size_t i = 0; i < eos._edges.size(); ++i )
9307 _LayerEdge& edge = *eos._edges[i];
9308 if ( edge._pos.size() < 2 )
9311 // get accumulated length of segments
9312 segLen.resize( edge._pos.size() );
9314 if ( eos._sWOL.IsNull() )
9316 bool useNormal = true;
9317 bool usePos = false;
9318 bool smoothed = false;
9319 double preci = 0.1 * edge._len;
9320 if ( eos._toSmooth && edge._pos.size() > 2 )
9322 smoothed = edge.GetSmoothedPos( preci );
9326 if ( !surface.IsNull() &&
9327 !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9329 useNormal = usePos = false;
9330 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9331 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9333 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9334 if ( surface->Gap() < 2. * edge._len )
9335 segLen[j] = surface->Gap();
9341 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9343 #ifndef __NODES_AT_POS
9344 useNormal = usePos = false;
9345 edge._pos[1] = edge._pos.back();
9346 edge._pos.resize( 2 );
9348 segLen[ 1 ] = edge._len;
9351 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9353 useNormal = usePos = false;
9354 _LayerEdge tmpEdge; // get original _normal
9355 tmpEdge._nodes.push_back( edge._nodes[0] );
9356 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9359 for ( size_t j = 1; j < edge._pos.size(); ++j )
9360 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9364 for ( size_t j = 1; j < edge._pos.size(); ++j )
9365 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9369 for ( size_t j = 1; j < edge._pos.size(); ++j )
9370 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9374 bool swapped = ( edge._pos.size() > 2 );
9378 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9379 if ( segLen[j] > segLen.back() )
9381 segLen.erase( segLen.begin() + j );
9382 edge._pos.erase( edge._pos.begin() + j );
9385 else if ( segLen[j] < segLen[j-1] )
9387 std::swap( segLen[j], segLen[j-1] );
9388 std::swap( edge._pos[j], edge._pos[j-1] );
9393 // smooth a path formed by edge._pos
9394 #ifndef __NODES_AT_POS
9395 if (( smoothed ) /*&&
9396 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9397 edge.SmoothPos( segLen, preci );
9400 else if ( eos._isRegularSWOL ) // usual SWOL
9402 for ( size_t j = 1; j < edge._pos.size(); ++j )
9403 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9405 else if ( !surface.IsNull() ) // SWOL surface with singularities
9407 pos3D.resize( edge._pos.size() );
9408 for ( size_t j = 0; j < edge._pos.size(); ++j )
9409 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9411 for ( size_t j = 1; j < edge._pos.size(); ++j )
9412 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9415 // allocate memory for new nodes if it is not yet refined
9416 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9417 if ( edge._nodes.size() == 2 )
9419 #ifdef __NODES_AT_POS
9420 int nbNodes = edge._pos.size();
9422 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9424 edge._nodes.resize( nbNodes, 0 );
9426 edge._nodes.back() = tgtNode;
9428 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9429 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9430 if ( baseShapeId != prevBaseId )
9432 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9433 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9434 prevBaseId = baseShapeId;
9436 _LayerEdge* edgeOnSameNode = 0;
9437 bool useExistingPos = false;
9438 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9440 edgeOnSameNode = n2e->second;
9441 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9442 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9443 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9446 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9447 epos->SetUParameter( otherTgtPos.X() );
9451 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9452 fpos->SetUParameter( otherTgtPos.X() );
9453 fpos->SetVParameter( otherTgtPos.Y() );
9456 // calculate height of the first layer
9458 const double T = segLen.back(); //data._hyp.GetTotalThickness();
9459 const double f = eos._hyp.GetStretchFactor();
9460 const int N = eos._hyp.GetNumberLayers();
9461 const double fPowN = pow( f, N );
9462 if ( fPowN - 1 <= numeric_limits<double>::min() )
9465 h0 = T * ( f - 1 )/( fPowN - 1 );
9467 const double zeroLen = std::numeric_limits<double>::min();
9469 // create intermediate nodes
9470 double hSum = 0, hi = h0/f;
9472 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9474 // compute an intermediate position
9477 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9479 int iPrevSeg = iSeg-1;
9480 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9482 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9483 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9484 #ifdef __NODES_AT_POS
9485 pos = edge._pos[ iStep ];
9487 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9488 if ( !eos._sWOL.IsNull() )
9490 // compute XYZ by parameters <pos>
9495 pos = curve->Value( u ).Transformed(loc);
9497 else if ( eos._isRegularSWOL )
9499 uv.SetCoord( pos.X(), pos.Y() );
9501 pos = surface->Value( pos.X(), pos.Y() );
9505 uv.SetCoord( pos.X(), pos.Y() );
9506 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9507 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9509 pos = surface->Value( uv );
9512 // create or update the node
9515 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9516 if ( !eos._sWOL.IsNull() )
9519 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9521 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9525 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9530 if ( !eos._sWOL.IsNull() )
9532 // make average pos from new and current parameters
9535 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9536 if ( useExistingPos )
9537 u = helper.GetNodeU( geomEdge, node );
9538 pos = curve->Value( u ).Transformed(loc);
9540 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9541 epos->SetUParameter( u );
9545 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9546 if ( useExistingPos )
9547 uv = helper.GetNodeUV( geomFace, node );
9548 pos = surface->Value( uv );
9550 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9551 fpos->SetUParameter( uv.X() );
9552 fpos->SetVParameter( uv.Y() );
9555 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9557 } // loop on edge._nodes
9559 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9562 edge._pos.back().SetCoord( u, 0,0);
9564 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9566 if ( edgeOnSameNode )
9567 edgeOnSameNode->_pos.back() = edge._pos.back();
9570 } // loop on eos._edges to create nodes
9573 if ( !getMeshDS()->IsEmbeddedMode() )
9574 // Log node movement
9575 for ( size_t i = 0; i < eos._edges.size(); ++i )
9577 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9578 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9585 helper.SetElementsOnShape(true);
9587 vector< vector<const SMDS_MeshNode*>* > nnVec;
9588 set< vector<const SMDS_MeshNode*>* > nnSet;
9589 set< int > degenEdgeInd;
9590 vector<const SMDS_MeshElement*> degenVols;
9592 TopExp_Explorer exp( data._solid, TopAbs_FACE );
9593 for ( ; exp.More(); exp.Next() )
9595 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9596 if ( data._ignoreFaceIds.count( faceID ))
9598 const bool isReversedFace = data._reversedFaceIds.count( faceID );
9599 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
9600 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
9601 while ( fIt->more() )
9603 const SMDS_MeshElement* face = fIt->next();
9604 const int nbNodes = face->NbCornerNodes();
9605 nnVec.resize( nbNodes );
9607 degenEdgeInd.clear();
9608 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9609 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9610 for ( int iN = 0; iN < nbNodes; ++iN )
9612 const SMDS_MeshNode* n = nIt->next();
9613 _LayerEdge* edge = data._n2eMap[ n ];
9614 const int i = isReversedFace ? nbNodes-1-iN : iN;
9615 nnVec[ i ] = & edge->_nodes;
9616 maxZ = std::max( maxZ, nnVec[ i ]->size() );
9617 minZ = std::min( minZ, nnVec[ i ]->size() );
9619 if ( helper.HasDegeneratedEdges() )
9620 nnSet.insert( nnVec[ i ]);
9625 if ( 0 < nnSet.size() && nnSet.size() < 3 )
9633 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9634 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9635 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
9637 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9639 for ( int iN = 0; iN < nbNodes; ++iN )
9640 if ( nnVec[ iN ]->size() < iZ+1 )
9641 degenEdgeInd.insert( iN );
9643 if ( degenEdgeInd.size() == 1 ) // PYRAM
9645 int i2 = *degenEdgeInd.begin();
9646 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9647 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9648 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9649 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
9653 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9654 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9655 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9656 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9657 (*nnVec[ i3 ])[ iZ ]);
9665 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9666 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9667 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9668 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
9669 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
9671 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9673 for ( int iN = 0; iN < nbNodes; ++iN )
9674 if ( nnVec[ iN ]->size() < iZ+1 )
9675 degenEdgeInd.insert( iN );
9677 switch ( degenEdgeInd.size() )
9681 int i2 = *degenEdgeInd.begin();
9682 int i3 = *degenEdgeInd.rbegin();
9683 bool ok = ( i3 - i2 == 1 );
9684 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9685 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9686 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9688 const SMDS_MeshElement* vol =
9689 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9690 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9692 degenVols.push_back( vol );
9696 default: // degen HEX
9698 const SMDS_MeshElement* vol =
9699 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9700 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9701 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9702 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9703 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
9704 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
9705 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
9706 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
9707 degenVols.push_back( vol );
9714 return error("Not supported type of element", data._index);
9716 } // switch ( nbNodes )
9717 } // while ( fIt->more() )
9720 if ( !degenVols.empty() )
9722 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9723 if ( !err || err->IsOK() )
9725 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9726 "Bad quality volumes created" ));
9727 err->myBadElements.insert( err->myBadElements.end(),
9728 degenVols.begin(),degenVols.end() );
9735 //================================================================================
9737 * \brief Shrink 2D mesh on faces to let space for inflated layers
9739 //================================================================================
9741 bool _ViscousBuilder::shrink(_SolidData& theData)
9743 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9744 // _LayerEdge's inflated along FACE or EDGE)
9745 map< TGeomID, list< _SolidData* > > f2sdMap;
9746 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9748 _SolidData& data = _sdVec[i];
9749 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9750 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9751 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9753 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9755 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9756 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9757 // by StdMeshers_QuadToTriaAdaptor
9758 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9760 SMESH_ProxyMesh::SubMesh* proxySub =
9761 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9762 if ( proxySub->NbElements() == 0 )
9764 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9765 while ( fIt->more() )
9767 const SMDS_MeshElement* f = fIt->next();
9768 // as a result 3D algo will use elements from proxySub and not from smDS
9769 proxySub->AddElement( f );
9770 f->setIsMarked( true );
9772 // Mark nodes on the FACE to discriminate them from nodes
9773 // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
9774 for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
9776 const SMDS_MeshNode* n = f->GetNode( iN );
9777 if ( n->GetPosition()->GetDim() == 2 )
9778 n->setIsMarked( true );
9786 SMESH_MesherHelper helper( *_mesh );
9787 helper.ToFixNodeParameters( true );
9790 map< TGeomID, _Shrinker1D > e2shrMap;
9791 vector< _EdgesOnShape* > subEOS;
9792 vector< _LayerEdge* > lEdges;
9794 // loop on FACEs to srink mesh on
9795 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9796 for ( ; f2sd != f2sdMap.end(); ++f2sd )
9798 list< _SolidData* > & dataList = f2sd->second;
9799 if ( dataList.front()->_n2eMap.empty() ||
9800 dataList.back() ->_n2eMap.empty() )
9801 continue; // not yet computed
9802 if ( dataList.front() != &theData &&
9803 dataList.back() != &theData )
9806 _SolidData& data = *dataList.front();
9807 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9808 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
9809 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9811 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9813 _shrinkedFaces.Add( F );
9814 helper.SetSubShape( F );
9816 // ===========================
9817 // Prepare data for shrinking
9818 // ===========================
9820 // Collect nodes to smooth, they are marked at the beginning of this method
9821 vector < const SMDS_MeshNode* > smoothNodes;
9823 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9824 while ( nIt->more() )
9826 const SMDS_MeshNode* n = nIt->next();
9827 if ( n->isMarked() )
9828 smoothNodes.push_back( n );
9831 // Find out face orientation
9833 const set<TGeomID> ignoreShapes;
9835 if ( !smoothNodes.empty() )
9837 vector<_Simplex> simplices;
9838 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9839 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9840 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9841 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9842 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9846 // Find _LayerEdge's inflated along F
9850 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9851 /*complexFirst=*/true); //!!!
9852 while ( subIt->more() )
9854 const TGeomID subID = subIt->next()->GetId();
9855 if ( data._noShrinkShapes.count( subID ))
9857 _EdgesOnShape* eos = data.GetShapeEdges( subID );
9858 if ( !eos || eos->_sWOL.IsNull() ) continue;
9860 subEOS.push_back( eos );
9862 for ( size_t i = 0; i < eos->_edges.size(); ++i )
9864 lEdges.push_back( eos->_edges[ i ] );
9865 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9870 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9871 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9872 while ( fIt->more() )
9873 if ( const SMDS_MeshElement* f = fIt->next() )
9874 dumpChangeNodes( f );
9877 // Replace source nodes by target nodes in mesh faces to shrink
9878 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9879 const SMDS_MeshNode* nodes[20];
9880 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9882 _EdgesOnShape& eos = * subEOS[ iS ];
9883 for ( size_t i = 0; i < eos._edges.size(); ++i )
9885 _LayerEdge& edge = *eos._edges[i];
9886 const SMDS_MeshNode* srcNode = edge._nodes[0];
9887 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9888 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9889 while ( fIt->more() )
9891 const SMDS_MeshElement* f = fIt->next();
9892 if ( !smDS->Contains( f ) || !f->isMarked() )
9894 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9895 for ( int iN = 0; nIt->more(); ++iN )
9897 const SMDS_MeshNode* n = nIt->next();
9898 nodes[iN] = ( n == srcNode ? tgtNode : n );
9900 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9901 dumpChangeNodes( f );
9907 // find out if a FACE is concave
9908 const bool isConcaveFace = isConcave( F, helper );
9910 // Create _SmoothNode's on face F
9911 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9913 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9914 const bool sortSimplices = isConcaveFace;
9915 for ( size_t i = 0; i < smoothNodes.size(); ++i )
9917 const SMDS_MeshNode* n = smoothNodes[i];
9918 nodesToSmooth[ i ]._node = n;
9919 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9920 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9921 // fix up incorrect uv of nodes on the FACE
9922 helper.GetNodeUV( F, n, 0, &isOkUV);
9927 //if ( nodesToSmooth.empty() ) continue;
9929 // Find EDGE's to shrink and set simpices to LayerEdge's
9930 set< _Shrinker1D* > eShri1D;
9932 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9934 _EdgesOnShape& eos = * subEOS[ iS ];
9935 if ( eos.SWOLType() == TopAbs_EDGE )
9937 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9938 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
9939 eShri1D.insert( & srinker );
9940 srinker.AddEdge( eos._edges[0], eos, helper );
9941 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9942 // restore params of nodes on EGDE if the EDGE has been already
9943 // srinked while srinking other FACE
9944 srinker.RestoreParams();
9946 for ( size_t i = 0; i < eos._edges.size(); ++i )
9948 _LayerEdge& edge = * eos._edges[i];
9949 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9951 // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
9952 // not-marked nodes are those added by refine()
9953 edge._nodes.back()->setIsMarked( true );
9958 bool toFixTria = false; // to improve quality of trias by diagonal swap
9959 if ( isConcaveFace )
9961 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9962 if ( hasTria != hasQuad ) {
9963 toFixTria = hasTria;
9966 set<int> nbNodesSet;
9967 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9968 while ( fIt->more() && nbNodesSet.size() < 2 )
9969 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9970 toFixTria = ( *nbNodesSet.begin() == 3 );
9974 // ==================
9975 // Perform shrinking
9976 // ==================
9978 bool shrinked = true;
9979 int nbBad, shriStep=0, smooStep=0;
9980 _SmoothNode::SmoothType smoothType
9981 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9982 SMESH_Comment errMsg;
9986 // Move boundary nodes (actually just set new UV)
9987 // -----------------------------------------------
9988 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9990 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9992 _EdgesOnShape& eos = * subEOS[ iS ];
9993 for ( size_t i = 0; i < eos._edges.size(); ++i )
9995 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10000 // Move nodes on EDGE's
10001 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10002 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10003 for ( ; shr != eShri1D.end(); ++shr )
10004 (*shr)->Compute( /*set3D=*/false, helper );
10007 // -----------------
10008 int nbNoImpSteps = 0;
10011 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10013 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10015 int oldBadNb = nbBad;
10018 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10019 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10020 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10022 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10023 smooTy, /*set3D=*/isConcaveFace);
10025 if ( nbBad < oldBadNb )
10035 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10036 if ( shriStep > 200 )
10037 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10038 if ( !errMsg.empty() )
10041 // Fix narrow triangles by swapping diagonals
10042 // ---------------------------------------
10045 set<const SMDS_MeshNode*> usedNodes;
10046 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10048 // update working data
10049 set<const SMDS_MeshNode*>::iterator n;
10050 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10052 n = usedNodes.find( nodesToSmooth[ i ]._node );
10053 if ( n != usedNodes.end())
10055 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10056 nodesToSmooth[ i ]._simplices,
10057 ignoreShapes, NULL,
10058 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10059 usedNodes.erase( n );
10062 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10064 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10065 if ( n != usedNodes.end())
10067 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10068 lEdges[i]->_simplices,
10070 usedNodes.erase( n );
10074 // TODO: check effect of this additional smooth
10075 // additional laplacian smooth to increase allowed shrink step
10076 // for ( int st = 1; st; --st )
10078 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10079 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10081 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10082 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10086 } // while ( shrinked )
10088 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10090 debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10093 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10095 vector< const SMDS_MeshElement* > facesToRm;
10098 facesToRm.reserve( psm->NbElements() );
10099 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10100 facesToRm.push_back( ite->next() );
10102 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10103 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10106 for ( size_t i = 0; i < facesToRm.size(); ++i )
10107 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10111 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10112 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10113 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10114 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10115 subEOS[iS]->_edges[i]->_nodes.end() );
10117 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10118 while ( itn->more() ) {
10119 const SMDS_MeshNode* n = itn->next();
10120 if ( !nodesToKeep.count( n ))
10121 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10124 // restore position and UV of target nodes
10126 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10127 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10129 _LayerEdge* edge = subEOS[iS]->_edges[i];
10130 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10131 if ( edge->_pos.empty() ||
10132 edge->Is( _LayerEdge::SHRUNK )) continue;
10133 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10135 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10136 pos->SetUParameter( edge->_pos[0].X() );
10137 pos->SetVParameter( edge->_pos[0].Y() );
10138 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10142 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10143 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10144 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10146 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10147 dumpMove( tgtNode );
10149 // shrink EDGE sub-meshes and set proxy sub-meshes
10150 UVPtStructVec uvPtVec;
10151 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10152 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10154 _Shrinker1D* shr = (*shrIt);
10155 shr->Compute( /*set3D=*/true, helper );
10157 // set proxy mesh of EDGEs w/o layers
10158 map< double, const SMDS_MeshNode* > nodes;
10159 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10160 // remove refinement nodes
10161 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10162 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10163 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10164 if ( u2n->second == sn0 || u2n->second == sn1 )
10166 while ( u2n->second != tn0 && u2n->second != tn1 )
10168 nodes.erase( nodes.begin(), u2n );
10170 u2n = --nodes.end();
10171 if ( u2n->second == sn0 || u2n->second == sn1 )
10173 while ( u2n->second != tn0 && u2n->second != tn1 )
10175 nodes.erase( ++u2n, nodes.end() );
10177 // set proxy sub-mesh
10178 uvPtVec.resize( nodes.size() );
10179 u2n = nodes.begin();
10180 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10181 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10183 uvPtVec[ i ].node = u2n->second;
10184 uvPtVec[ i ].param = u2n->first;
10185 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10187 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10188 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10191 // set proxy mesh of EDGEs with layers
10192 vector< _LayerEdge* > edges;
10193 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10195 _EdgesOnShape& eos = * subEOS[ iS ];
10196 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10198 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10199 data.SortOnEdge( E, eos._edges );
10202 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10203 if ( !eov->_edges.empty() )
10204 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10206 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10208 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10209 if ( !eov->_edges.empty() )
10210 edges.push_back( eov->_edges[0] ); // on last VERTEX
10212 uvPtVec.resize( edges.size() );
10213 for ( size_t i = 0; i < edges.size(); ++i )
10215 uvPtVec[ i ].node = edges[i]->_nodes.back();
10216 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10217 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10219 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10220 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10221 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10223 // temporary clear the FACE sub-mesh from faces made by refine()
10224 vector< const SMDS_MeshElement* > elems;
10225 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10226 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10227 elems.push_back( ite->next() );
10228 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10229 elems.push_back( ite->next() );
10232 // compute the mesh on the FACE
10233 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10234 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10236 // re-fill proxy sub-meshes of the FACE
10237 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10238 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10239 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10240 psm->AddElement( ite->next() );
10243 for ( size_t i = 0; i < elems.size(); ++i )
10244 smDS->AddElement( elems[i] );
10246 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10247 return error( errMsg );
10249 } // end of re-meshing in case of failed smoothing
10252 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10253 bool isStructuredFixed = false;
10254 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10255 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10256 if ( !isStructuredFixed )
10258 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10259 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10261 for ( int st = 3; st; --st )
10264 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10265 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10266 case 3: smoothType = _SmoothNode::ANGULAR; break;
10268 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10269 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10271 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10272 smoothType,/*set3D=*/st==1 );
10277 if ( !getMeshDS()->IsEmbeddedMode() )
10278 // Log node movement
10279 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10281 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10282 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10286 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10287 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10289 } // loop on FACES to srink mesh on
10292 // Replace source nodes by target nodes in shrinked mesh edges
10294 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10295 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10296 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10301 //================================================================================
10303 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10305 //================================================================================
10307 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10308 _EdgesOnShape& eos,
10309 SMESH_MesherHelper& helper,
10310 const SMESHDS_SubMesh* faceSubMesh)
10312 const SMDS_MeshNode* srcNode = edge._nodes[0];
10313 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10315 if ( eos.SWOLType() == TopAbs_FACE )
10317 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10320 edge.Set( _LayerEdge::SHRUNK );
10321 return srcNode == tgtNode;
10323 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10324 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10325 gp_Vec2d uvDir( srcUV, tgtUV );
10326 double uvLen = uvDir.Magnitude();
10328 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10331 //edge._pos.resize(1);
10332 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10334 // set UV of source node to target node
10335 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10336 pos->SetUParameter( srcUV.X() );
10337 pos->SetVParameter( srcUV.Y() );
10339 else // _sWOL is TopAbs_EDGE
10341 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10344 edge.Set( _LayerEdge::SHRUNK );
10345 return srcNode == tgtNode;
10347 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10348 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10349 if ( !edgeSM || edgeSM->NbElements() == 0 )
10350 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10352 const SMDS_MeshNode* n2 = 0;
10353 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10354 while ( eIt->more() && !n2 )
10356 const SMDS_MeshElement* e = eIt->next();
10357 if ( !edgeSM->Contains(e)) continue;
10358 n2 = e->GetNode( 0 );
10359 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10362 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10364 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10365 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10366 double u2 = helper.GetNodeU( E, n2, srcNode );
10368 //edge._pos.clear();
10370 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10372 // tgtNode is located so that it does not make faces with wrong orientation
10373 edge.Set( _LayerEdge::SHRUNK );
10376 //edge._pos.resize(1);
10377 edge._pos[0].SetCoord( U_TGT, uTgt );
10378 edge._pos[0].SetCoord( U_SRC, uSrc );
10379 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10381 edge._simplices.resize( 1 );
10382 edge._simplices[0]._nPrev = n2;
10384 // set U of source node to the target node
10385 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10386 pos->SetUParameter( uSrc );
10391 //================================================================================
10393 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10395 //================================================================================
10397 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10399 if ( edge._nodes.size() == 1 )
10404 const SMDS_MeshNode* srcNode = edge._nodes[0];
10405 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10406 if ( S.IsNull() ) return;
10410 switch ( S.ShapeType() )
10415 TopLoc_Location loc;
10416 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10417 if ( curve.IsNull() ) return;
10418 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10419 p = curve->Value( ePos->GetUParameter() );
10422 case TopAbs_VERTEX:
10424 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10429 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10430 dumpMove( srcNode );
10434 //================================================================================
10436 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10438 //================================================================================
10440 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10441 SMESH_MesherHelper& helper,
10444 set<const SMDS_MeshNode*> * involvedNodes)
10446 SMESH::Controls::AspectRatio qualifier;
10447 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10448 const double maxAspectRatio = is2D ? 4. : 2;
10449 _NodeCoordHelper xyz( F, helper, is2D );
10451 // find bad triangles
10453 vector< const SMDS_MeshElement* > badTrias;
10454 vector< double > badAspects;
10455 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
10456 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10457 while ( fIt->more() )
10459 const SMDS_MeshElement * f = fIt->next();
10460 if ( f->NbCornerNodes() != 3 ) continue;
10461 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10462 double aspect = qualifier.GetValue( points );
10463 if ( aspect > maxAspectRatio )
10465 badTrias.push_back( f );
10466 badAspects.push_back( aspect );
10471 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10472 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10473 while ( fIt->more() )
10475 const SMDS_MeshElement * f = fIt->next();
10476 if ( f->NbCornerNodes() == 3 )
10477 dumpChangeNodes( f );
10481 if ( badTrias.empty() )
10484 // find couples of faces to swap diagonal
10486 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10487 vector< T2Trias > triaCouples;
10489 TIDSortedElemSet involvedFaces, emptySet;
10490 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10493 double aspRatio [3];
10496 if ( !involvedFaces.insert( badTrias[iTia] ).second )
10498 for ( int iP = 0; iP < 3; ++iP )
10499 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10501 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10502 int bestCouple = -1;
10503 for ( int iSide = 0; iSide < 3; ++iSide )
10505 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10506 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10507 trias [iSide].first = badTrias[iTia];
10508 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10510 if (( ! trias[iSide].second ) ||
10511 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10512 ( ! sm->Contains( trias[iSide].second )))
10515 // aspect ratio of an adjacent tria
10516 for ( int iP = 0; iP < 3; ++iP )
10517 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10518 double aspectInit = qualifier.GetValue( points2 );
10520 // arrange nodes as after diag-swaping
10521 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10522 i3 = helper.WrapIndex( i1-1, 3 );
10524 i3 = helper.WrapIndex( i1+1, 3 );
10526 points1( 1+ iSide ) = points2( 1+ i3 );
10527 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
10529 // aspect ratio after diag-swaping
10530 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10531 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10534 // prevent inversion of a triangle
10535 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10536 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10537 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10540 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10541 bestCouple = iSide;
10544 if ( bestCouple >= 0 )
10546 triaCouples.push_back( trias[bestCouple] );
10547 involvedFaces.insert ( trias[bestCouple].second );
10551 involvedFaces.erase( badTrias[iTia] );
10554 if ( triaCouples.empty() )
10559 SMESH_MeshEditor editor( helper.GetMesh() );
10560 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10561 for ( size_t i = 0; i < triaCouples.size(); ++i )
10563 dumpChangeNodes( triaCouples[i].first );
10564 dumpChangeNodes( triaCouples[i].second );
10565 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10568 if ( involvedNodes )
10569 for ( size_t i = 0; i < triaCouples.size(); ++i )
10571 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10572 triaCouples[i].first->end_nodes() );
10573 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10574 triaCouples[i].second->end_nodes() );
10577 // just for debug dump resulting triangles
10578 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10579 for ( size_t i = 0; i < triaCouples.size(); ++i )
10581 dumpChangeNodes( triaCouples[i].first );
10582 dumpChangeNodes( triaCouples[i].second );
10586 //================================================================================
10588 * \brief Move target node to it's final position on the FACE during shrinking
10590 //================================================================================
10592 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10593 const TopoDS_Face& F,
10594 _EdgesOnShape& eos,
10595 SMESH_MesherHelper& helper )
10598 return false; // already at the target position
10600 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10602 if ( eos.SWOLType() == TopAbs_FACE )
10604 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
10605 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10606 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10607 const double uvLen = tgtUV.Distance( curUV );
10608 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10610 // Select shrinking step such that not to make faces with wrong orientation.
10611 double stepSize = 1e100;
10612 for ( size_t i = 0; i < _simplices.size(); ++i )
10614 if ( !_simplices[i]._nPrev->isMarked() ||
10615 !_simplices[i]._nNext->isMarked() )
10616 continue; // simplex of quadrangle created by addBoundaryElements()
10618 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10619 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10620 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10621 gp_XY dirN = uvN2 - uvN1;
10622 double det = uvDir.Crossed( dirN );
10623 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
10624 gp_XY dirN2Cur = curUV - uvN1;
10625 double step = dirN.Crossed( dirN2Cur ) / det;
10627 stepSize = Min( step, stepSize );
10630 if ( uvLen <= stepSize )
10636 else if ( stepSize > 0 )
10638 newUV = curUV + uvDir.XY() * stepSize * kSafe;
10644 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10645 pos->SetUParameter( newUV.X() );
10646 pos->SetVParameter( newUV.Y() );
10649 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10650 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10651 dumpMove( tgtNode );
10654 else // _sWOL is TopAbs_EDGE
10656 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10657 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
10658 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10660 const double u2 = helper.GetNodeU( E, n2, tgtNode );
10661 const double uSrc = _pos[0].Coord( U_SRC );
10662 const double lenTgt = _pos[0].Coord( LEN_TGT );
10664 double newU = _pos[0].Coord( U_TGT );
10665 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10667 Set( _LayerEdge::SHRUNK );
10672 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10674 tgtPos->SetUParameter( newU );
10676 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10677 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10678 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10679 dumpMove( tgtNode );
10686 //================================================================================
10688 * \brief Perform smooth on the FACE
10689 * \retval bool - true if the node has been moved
10691 //================================================================================
10693 bool _SmoothNode::Smooth(int& nbBad,
10694 Handle(Geom_Surface)& surface,
10695 SMESH_MesherHelper& helper,
10696 const double refSign,
10700 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10702 // get uv of surrounding nodes
10703 vector<gp_XY> uv( _simplices.size() );
10704 for ( size_t i = 0; i < _simplices.size(); ++i )
10705 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10707 // compute new UV for the node
10708 gp_XY newPos (0,0);
10709 if ( how == TFI && _simplices.size() == 4 )
10712 for ( size_t i = 0; i < _simplices.size(); ++i )
10713 if ( _simplices[i]._nOpp )
10714 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10716 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10718 newPos = helper.calcTFI ( 0.5, 0.5,
10719 corners[0], corners[1], corners[2], corners[3],
10720 uv[1], uv[2], uv[3], uv[0] );
10722 else if ( how == ANGULAR )
10724 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10726 else if ( how == CENTROIDAL && _simplices.size() > 3 )
10728 // average centers of diagonals wieghted with their reciprocal lengths
10729 if ( _simplices.size() == 4 )
10731 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10732 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10733 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10737 double sumWeight = 0;
10738 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10739 for ( int i = 0; i < nb; ++i )
10742 int iTo = i + _simplices.size() - 1;
10743 for ( int j = iFrom; j < iTo; ++j )
10745 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10746 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10748 newPos += w * ( uv[i]+uv[i2] );
10751 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10756 // Laplacian smooth
10757 for ( size_t i = 0; i < _simplices.size(); ++i )
10759 newPos /= _simplices.size();
10762 // count quality metrics (orientation) of triangles around the node
10763 int nbOkBefore = 0;
10764 gp_XY tgtUV = helper.GetNodeUV( face, _node );
10765 for ( size_t i = 0; i < _simplices.size(); ++i )
10766 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10769 for ( size_t i = 0; i < _simplices.size(); ++i )
10770 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10772 if ( nbOkAfter < nbOkBefore )
10774 nbBad += _simplices.size() - nbOkBefore;
10778 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10779 pos->SetUParameter( newPos.X() );
10780 pos->SetVParameter( newPos.Y() );
10787 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10788 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10792 nbBad += _simplices.size() - nbOkAfter;
10793 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10796 //================================================================================
10798 * \brief Computes new UV using angle based smoothing technic
10800 //================================================================================
10802 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10803 const gp_XY& uvToFix,
10804 const double refSign)
10806 uv.push_back( uv.front() );
10808 vector< gp_XY > edgeDir ( uv.size() );
10809 vector< double > edgeSize( uv.size() );
10810 for ( size_t i = 1; i < edgeDir.size(); ++i )
10812 edgeDir [i-1] = uv[i] - uv[i-1];
10813 edgeSize[i-1] = edgeDir[i-1].Modulus();
10814 if ( edgeSize[i-1] < numeric_limits<double>::min() )
10815 edgeDir[i-1].SetX( 100 );
10817 edgeDir[i-1] /= edgeSize[i-1] * refSign;
10819 edgeDir.back() = edgeDir.front();
10820 edgeSize.back() = edgeSize.front();
10824 double sumSize = 0;
10825 for ( size_t i = 1; i < edgeDir.size(); ++i )
10827 if ( edgeDir[i-1].X() > 1. ) continue;
10829 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10830 if ( i == edgeDir.size() ) break;
10832 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10833 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
10834 gp_XY bisec = norm1 + norm2;
10835 double bisecSize = bisec.Modulus();
10836 if ( bisecSize < numeric_limits<double>::min() )
10838 bisec = -edgeDir[i1] + edgeDir[i];
10839 bisecSize = bisec.Modulus();
10841 bisec /= bisecSize;
10843 gp_XY dirToN = uvToFix - p;
10844 double distToN = dirToN.Modulus();
10845 if ( bisec * dirToN < 0 )
10846 distToN = -distToN;
10848 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10850 sumSize += edgeSize[i1] + edgeSize[i];
10852 newPos /= /*nbEdges * */sumSize;
10856 //================================================================================
10858 * \brief Delete _SolidData
10860 //================================================================================
10862 _SolidData::~_SolidData()
10864 TNode2Edge::iterator n2e = _n2eMap.begin();
10865 for ( ; n2e != _n2eMap.end(); ++n2e )
10867 _LayerEdge* & e = n2e->second;
10870 delete e->_curvature;
10871 if ( e->_2neibors )
10872 delete e->_2neibors->_plnNorm;
10873 delete e->_2neibors;
10884 //================================================================================
10886 * \brief Keep a _LayerEdge inflated along the EDGE
10888 //================================================================================
10890 void _Shrinker1D::AddEdge( const _LayerEdge* e,
10891 _EdgesOnShape& eos,
10892 SMESH_MesherHelper& helper )
10895 if ( _nodes.empty() )
10897 _edges[0] = _edges[1] = 0;
10900 // check _LayerEdge
10901 if ( e == _edges[0] || e == _edges[1] )
10903 if ( eos.SWOLType() != TopAbs_EDGE )
10904 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10905 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10906 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10908 // store _LayerEdge
10909 _geomEdge = TopoDS::Edge( eos._sWOL );
10911 BRep_Tool::Range( _geomEdge, f,l );
10912 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10913 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10917 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10918 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10920 if ( _nodes.empty() )
10922 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10923 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10925 TopLoc_Location loc;
10926 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10927 GeomAdaptor_Curve aCurve(C, f,l);
10928 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10930 int nbExpectNodes = eSubMesh->NbNodes();
10931 _initU .reserve( nbExpectNodes );
10932 _normPar.reserve( nbExpectNodes );
10933 _nodes .reserve( nbExpectNodes );
10934 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10935 while ( nIt->more() )
10937 const SMDS_MeshNode* node = nIt->next();
10939 // skip refinement nodes
10940 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10941 node == tgtNode0 || node == tgtNode1 )
10943 bool hasMarkedFace = false;
10944 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
10945 while ( fIt->more() && !hasMarkedFace )
10946 hasMarkedFace = fIt->next()->isMarked();
10947 if ( !hasMarkedFace )
10950 _nodes.push_back( node );
10951 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10952 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10953 _normPar.push_back( len / totLen );
10958 // remove target node of the _LayerEdge from _nodes
10959 size_t nbFound = 0;
10960 for ( size_t i = 0; i < _nodes.size(); ++i )
10961 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10962 _nodes[i] = 0, nbFound++;
10963 if ( nbFound == _nodes.size() )
10968 //================================================================================
10970 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10972 //================================================================================
10974 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10976 if ( _done || _nodes.empty())
10978 const _LayerEdge* e = _edges[0];
10979 if ( !e ) e = _edges[1];
10982 _done = (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
10983 ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
10986 if ( set3D || _done )
10988 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10989 GeomAdaptor_Curve aCurve(C, f,l);
10992 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10994 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10995 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10997 for ( size_t i = 0; i < _nodes.size(); ++i )
10999 if ( !_nodes[i] ) continue;
11000 double len = totLen * _normPar[i];
11001 GCPnts_AbscissaPoint discret( aCurve, len, f );
11002 if ( !discret.IsDone() )
11003 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11004 double u = discret.Parameter();
11005 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11006 pos->SetUParameter( u );
11007 gp_Pnt p = C->Value( u );
11008 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11013 BRep_Tool::Range( _geomEdge, f,l );
11015 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11017 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11019 for ( size_t i = 0; i < _nodes.size(); ++i )
11021 if ( !_nodes[i] ) continue;
11022 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11023 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11024 pos->SetUParameter( u );
11029 //================================================================================
11031 * \brief Restore initial parameters of nodes on EDGE
11033 //================================================================================
11035 void _Shrinker1D::RestoreParams()
11038 for ( size_t i = 0; i < _nodes.size(); ++i )
11040 if ( !_nodes[i] ) continue;
11041 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11042 pos->SetUParameter( _initU[i] );
11047 //================================================================================
11049 * \brief Replace source nodes by target nodes in shrinked mesh edges
11051 //================================================================================
11053 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11055 const SMDS_MeshNode* nodes[3];
11056 for ( int i = 0; i < 2; ++i )
11058 if ( !_edges[i] ) continue;
11060 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11061 if ( !eSubMesh ) return;
11062 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11063 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11064 const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11065 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11066 while ( eIt->more() )
11068 const SMDS_MeshElement* e = eIt->next();
11069 if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11071 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11072 for ( int iN = 0; iN < e->NbNodes(); ++iN )
11074 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11075 nodes[iN] = ( n == srcNode ? tgtNode : n );
11077 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11082 //================================================================================
11084 * \brief Creates 2D and 1D elements on boundaries of new prisms
11086 //================================================================================
11088 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11090 SMESH_MesherHelper helper( *_mesh );
11092 vector< const SMDS_MeshNode* > faceNodes;
11094 //for ( size_t i = 0; i < _sdVec.size(); ++i )
11096 //_SolidData& data = _sdVec[i];
11097 TopTools_IndexedMapOfShape geomEdges;
11098 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11099 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11101 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11102 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
11105 // Get _LayerEdge's based on E
11107 map< double, const SMDS_MeshNode* > u2nodes;
11108 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11111 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11112 TNode2Edge & n2eMap = data._n2eMap;
11113 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11115 //check if 2D elements are needed on E
11116 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11117 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11118 ledges.push_back( n2e->second );
11120 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11121 continue; // no layers on E
11122 ledges.push_back( n2eMap[ u2n->second ]);
11124 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11125 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11126 int nbSharedPyram = 0;
11127 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11128 while ( vIt->more() )
11130 const SMDS_MeshElement* v = vIt->next();
11131 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11133 if ( nbSharedPyram > 1 )
11134 continue; // not free border of the pyramid
11137 faceNodes.push_back( ledges[0]->_nodes[0] );
11138 faceNodes.push_back( ledges[1]->_nodes[0] );
11139 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11140 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11142 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11143 continue; // faces already created
11145 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11146 ledges.push_back( n2eMap[ u2n->second ]);
11148 // Find out orientation and type of face to create
11150 bool reverse = false, isOnFace;
11152 map< TGeomID, TopoDS_Shape >::iterator e2f =
11153 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
11155 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11157 F = e2f->second.Oriented( TopAbs_FORWARD );
11158 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11159 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11160 reverse = !reverse, F.Reverse();
11161 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11162 reverse = !reverse;
11164 else if ( !data._ignoreFaceIds.count( e2f->first ))
11166 // find FACE with layers sharing E
11167 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11169 F = *( fIt->next() );
11171 // Find the sub-mesh to add new faces
11172 SMESHDS_SubMesh* sm = 0;
11174 sm = getMeshDS()->MeshElements( F );
11176 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11178 return error("error in addBoundaryElements()", data._index);
11181 const int dj1 = reverse ? 0 : 1;
11182 const int dj2 = reverse ? 1 : 0;
11183 for ( size_t j = 1; j < ledges.size(); ++j )
11185 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11186 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11187 if ( nn1.size() == nn2.size() )
11190 for ( size_t z = 1; z < nn1.size(); ++z )
11191 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11193 for ( size_t z = 1; z < nn1.size(); ++z )
11194 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11196 else if ( nn1.size() == 1 )
11199 for ( size_t z = 1; z < nn2.size(); ++z )
11200 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11202 for ( size_t z = 1; z < nn2.size(); ++z )
11203 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11208 for ( size_t z = 1; z < nn1.size(); ++z )
11209 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11211 for ( size_t z = 1; z < nn1.size(); ++z )
11212 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11217 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11219 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11220 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11221 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11223 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11224 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11226 helper.SetSubShape( eos->_sWOL );
11227 helper.SetElementsOnShape( true );
11228 for ( size_t z = 1; z < nn.size(); ++z )
11229 helper.AddEdge( nn[z-1], nn[z] );
11233 } // loop on EDGE's
11234 } // loop on _SolidData's