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 UNUSED_FLAG = 0x0100000
444 bool Is ( int flag ) const { return _flags & flag; }
445 void Set ( int flag ) { _flags |= flag; }
446 void Unset( int flag ) { _flags &= ~flag; }
448 void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
449 bool SetNewLength2d( Handle(Geom_Surface)& surface,
450 const TopoDS_Face& F,
452 SMESH_MesherHelper& helper );
453 void SetDataByNeighbors( const SMDS_MeshNode* n1,
454 const SMDS_MeshNode* n2,
455 const _EdgesOnShape& eos,
456 SMESH_MesherHelper& helper);
457 void Block( _SolidData& data );
458 void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
459 void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
460 const TNode2Edge& n2eMap);
461 void SmoothPos( const vector< double >& segLen, const double tol );
462 int GetSmoothedPos( const double tol );
463 int Smooth(const int step, const bool isConcaveFace, bool findBest);
464 int Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
465 int CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
466 void SmoothWoCheck();
467 bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
468 const TopoDS_Face& F,
469 SMESH_MesherHelper& helper);
470 void MoveNearConcaVer( const _EdgesOnShape* eov,
471 const _EdgesOnShape* eos,
473 vector< _LayerEdge* > & badSmooEdges);
474 bool FindIntersection( SMESH_ElementSearcher& searcher,
476 const double& epsilon,
478 const SMDS_MeshElement** face = 0);
479 bool SegTriaInter( const gp_Ax1& lastSegment,
484 const double& epsilon) const;
485 bool SegTriaInter( const gp_Ax1& lastSegment,
486 const SMDS_MeshNode* n0,
487 const SMDS_MeshNode* n1,
488 const SMDS_MeshNode* n2,
490 const double& epsilon) const
491 { return SegTriaInter( lastSegment,
492 SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
495 const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
496 gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
497 gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
498 gp_XY LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
499 bool IsOnEdge() const { return _2neibors; }
500 gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
501 void SetCosin( double cosin );
502 void SetNormal( const gp_XYZ& n ) { _normal = n; }
503 int NbSteps() const { return _pos.size() - 1; } // nb inlation steps
504 bool IsNeiborOnEdge( const _LayerEdge* edge ) const;
505 void SetSmooLen( double len ) { // set _len at which smoothing is needed
506 _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
508 double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
510 gp_XYZ smoothLaplacian();
511 gp_XYZ smoothAngular();
512 gp_XYZ smoothLengthWeighted();
513 gp_XYZ smoothCentroidal();
514 gp_XYZ smoothNefPolygon();
516 enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
517 static const int theNbSmooFuns = FUN_NB;
518 static PSmooFun _funs[theNbSmooFuns];
519 static const char* _funNames[theNbSmooFuns+1];
520 int smooFunID( PSmooFun fun=0) const;
522 _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
523 &_LayerEdge::smoothLengthWeighted,
524 &_LayerEdge::smoothCentroidal,
525 &_LayerEdge::smoothNefPolygon,
526 &_LayerEdge::smoothAngular };
527 const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
535 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
537 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
538 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
541 //--------------------------------------------------------------------------------
543 * A 2D half plane used by _LayerEdge::smoothNefPolygon()
547 gp_XY _pos, _dir, _inNorm;
548 bool IsOut( const gp_XY p, const double tol ) const
550 return _inNorm * ( p - _pos ) < -tol;
552 bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
554 //const double eps = 1e-10;
555 double D = _dir.Crossed( hp._dir );
556 if ( fabs(D) < std::numeric_limits<double>::min())
558 gp_XY vec21 = _pos - hp._pos;
559 double u = hp._dir.Crossed( vec21 ) / D;
560 intPnt = _pos + _dir * u;
564 //--------------------------------------------------------------------------------
566 * Structure used to smooth a _LayerEdge based on an EDGE.
570 double _wgt [2]; // weights of _nodes
571 _LayerEdge* _edges[2];
573 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
576 _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
577 const SMDS_MeshNode* tgtNode(bool is2nd) {
578 return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
580 const SMDS_MeshNode* srcNode(bool is2nd) {
581 return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
584 std::swap( _wgt [0], _wgt [1] );
585 std::swap( _edges[0], _edges[1] );
587 void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
588 _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
590 bool include( const _LayerEdge* e ) {
591 return ( _edges[0] == e || _edges[1] == e );
596 //--------------------------------------------------------------------------------
598 * \brief Layers parameters got by averaging several hypotheses
602 AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
603 :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
607 void Add( const StdMeshers_ViscousLayers* hyp )
612 _nbLayers = hyp->GetNumberLayers();
613 //_thickness += hyp->GetTotalThickness();
614 _thickness = Max( _thickness, hyp->GetTotalThickness() );
615 _stretchFactor += hyp->GetStretchFactor();
616 _method = hyp->GetMethod();
619 double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620 double GetStretchFactor() const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621 int GetNumberLayers() const { return _nbLayers; }
622 int GetMethod() const { return _method; }
624 bool UseSurfaceNormal() const
625 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
626 bool ToSmooth() const
627 { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628 bool IsOffsetMethod() const
629 { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
632 int _nbLayers, _nbHyps, _method;
633 double _thickness, _stretchFactor;
636 //--------------------------------------------------------------------------------
638 * \brief _LayerEdge's on a shape and other shape data
642 vector< _LayerEdge* > _edges;
646 SMESH_subMesh * _subMesh;
647 // face or edge w/o layer along or near which _edges are inflated
649 bool _isRegularSWOL; // w/o singularities
650 // averaged StdMeshers_ViscousLayers parameters
653 _Smoother1D* _edgeSmoother;
654 vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
655 vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
657 vector< gp_XYZ > _faceNormals; // if _shape is FACE
658 vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
660 Handle(ShapeAnalysis_Surface) _offsetSurf;
661 _LayerEdge* _edgeForOffset;
663 _SolidData* _data; // parent SOLID
665 TopAbs_ShapeEnum ShapeType() const
666 { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
667 TopAbs_ShapeEnum SWOLType() const
668 { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
669 bool HasC1( const _EdgesOnShape* other ) const
670 { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
671 bool GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
672 _SolidData& GetData() const { return *_data; }
674 _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
677 //--------------------------------------------------------------------------------
679 * \brief Convex FACE whose radius of curvature is less than the thickness of
680 * layers. It is used to detect distortion of prisms based on a convex
681 * FACE and to update normals to enable further increasing the thickness
687 // edges whose _simplices are used to detect prism distortion
688 vector< _LayerEdge* > _simplexTestEdges;
690 // map a sub-shape to _SolidData::_edgesOnShape
691 map< TGeomID, _EdgesOnShape* > _subIdToEOS;
695 bool GetCenterOfCurvature( _LayerEdge* ledge,
696 BRepLProp_SLProps& surfProp,
697 SMESH_MesherHelper& helper,
698 gp_Pnt & center ) const;
699 bool CheckPrisms() const;
702 //--------------------------------------------------------------------------------
704 * \brief Structure holding _LayerEdge's based on EDGEs that will collide
705 * at inflation up to the full thickness. A detected collision
706 * is fixed in updateNormals()
708 struct _CollisionEdges
711 vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
712 const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
713 const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
716 //--------------------------------------------------------------------------------
718 * \brief Data of a SOLID
722 typedef const StdMeshers_ViscousLayers* THyp;
724 TopTools_MapOfShape _before; // SOLIDs to be computed before _solid
725 TGeomID _index; // SOLID id
726 _MeshOfSolid* _proxyMesh;
728 list< TopoDS_Shape > _hypShapes;
729 map< TGeomID, THyp > _face2hyp; // filled if _hyps.size() > 1
730 set< TGeomID > _reversedFaceIds;
731 set< TGeomID > _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
733 double _stepSize, _stepSizeCoeff, _geomSize;
734 const SMDS_MeshNode* _stepSizeNodes[2];
736 TNode2Edge _n2eMap; // nodes and _LayerEdge's based on them
738 // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
739 map< TGeomID, TNode2Edge* > _s2neMap;
740 // _LayerEdge's with underlying shapes
741 vector< _EdgesOnShape > _edgesOnShape;
743 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
744 // layers and a FACE w/o layers
745 // value: the shape (FACE or EDGE) to shrink mesh on.
746 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
747 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
749 // Convex FACEs whose radius of curvature is less than the thickness of layers
750 map< TGeomID, _ConvexFace > _convexFaces;
752 // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
753 // the adjacent SOLID
754 set< TGeomID > _noShrinkShapes;
756 int _nbShapesToSmooth;
758 //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
760 vector< _CollisionEdges > _collisionEdges;
761 set< TGeomID > _concaveFaces;
763 double _maxThickness; // of all _hyps
764 double _minThickness; // of all _hyps
766 double _epsilon; // precision for SegTriaInter()
768 SMESH_MesherHelper* _helper;
770 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
772 :_solid(s), _proxyMesh(m), _helper(0) {}
775 void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
776 void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
778 _ConvexFace* GetConvexFace( const TGeomID faceID ) {
779 map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
780 return id2face == _convexFaces.end() ? 0 : & id2face->second;
782 _EdgesOnShape* GetShapeEdges(const TGeomID shapeID );
783 _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
784 _EdgesOnShape* GetShapeEdges(const _LayerEdge* edge )
785 { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
787 SMESH_MesherHelper& GetHelper() const { return *_helper; }
789 void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
790 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
791 for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
792 _edgesOnShape[i]._edges[j]->Unset( flag );
794 void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
795 const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
797 void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
799 //--------------------------------------------------------------------------------
801 * \brief Offset plane used in getNormalByOffset()
807 int _faceIndexNext[2];
808 gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
811 _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
813 void ComputeIntersectionLine( _OffsetPlane& pln,
814 const TopoDS_Edge& E,
815 const TopoDS_Vertex& V );
816 gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
817 int NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
819 //--------------------------------------------------------------------------------
821 * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
823 struct _CentralCurveOnEdge
826 vector< gp_Pnt > _curvaCenters;
827 vector< _LayerEdge* > _ledges;
828 vector< gp_XYZ > _normals; // new normal for each of _ledges
829 vector< double > _segLength2;
832 TopoDS_Face _adjFace;
833 bool _adjFaceToSmooth;
835 void Append( const gp_Pnt& center, _LayerEdge* ledge )
837 if ( _curvaCenters.size() > 0 )
838 _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
839 _curvaCenters.push_back( center );
840 _ledges.push_back( ledge );
841 _normals.push_back( ledge->_normal );
843 bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
844 void SetShapes( const TopoDS_Edge& edge,
845 const _ConvexFace& convFace,
847 SMESH_MesherHelper& helper);
849 //--------------------------------------------------------------------------------
851 * \brief Data of node on a shrinked FACE
855 const SMDS_MeshNode* _node;
856 vector<_Simplex> _simplices; // for quality check
858 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
860 bool Smooth(int& badNb,
861 Handle(Geom_Surface)& surface,
862 SMESH_MesherHelper& helper,
863 const double refSign,
867 gp_XY computeAngularPos(vector<gp_XY>& uv,
868 const gp_XY& uvToFix,
869 const double refSign );
871 //--------------------------------------------------------------------------------
873 * \brief Builder of viscous layers
875 class _ViscousBuilder
880 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
881 const TopoDS_Shape& shape);
882 // check validity of hypotheses
883 SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh& mesh,
884 const TopoDS_Shape& shape );
886 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
887 void RestoreListeners();
889 // computes SMESH_ProxyMesh::SubMesh::_n2n;
890 bool MakeN2NMap( _MeshOfSolid* pm );
894 bool findSolidsWithLayers();
895 bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
896 bool findFacesWithLayers(const bool onlyWith=false);
897 void getIgnoreFaces(const TopoDS_Shape& solid,
898 const StdMeshers_ViscousLayers* hyp,
899 const TopoDS_Shape& hypShape,
900 set<TGeomID>& ignoreFaces);
901 bool makeLayer(_SolidData& data);
902 void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
903 bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
904 SMESH_MesherHelper& helper, _SolidData& data);
905 gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
906 const TopoDS_Face& face,
907 SMESH_MesherHelper& helper,
909 bool shiftInside=false);
910 bool getFaceNormalAtSingularity(const gp_XY& uv,
911 const TopoDS_Face& face,
912 SMESH_MesherHelper& helper,
914 gp_XYZ getWeigthedNormal( const _LayerEdge* edge );
915 gp_XYZ getNormalByOffset( _LayerEdge* edge,
916 std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
918 bool lastNoOffset = false);
919 bool findNeiborsOnEdge(const _LayerEdge* edge,
920 const SMDS_MeshNode*& n1,
921 const SMDS_MeshNode*& n2,
924 void findSimplexTestEdges( _SolidData& data,
925 vector< vector<_LayerEdge*> >& edgesByGeom);
926 void computeGeomSize( _SolidData& data );
927 bool findShapesToSmooth( _SolidData& data);
928 void limitStepSizeByCurvature( _SolidData& data );
929 void limitStepSize( _SolidData& data,
930 const SMDS_MeshElement* face,
931 const _LayerEdge* maxCosinEdge );
932 void limitStepSize( _SolidData& data, const double minSize);
933 bool inflate(_SolidData& data);
934 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
935 int invalidateBadSmooth( _SolidData& data,
936 SMESH_MesherHelper& helper,
937 vector< _LayerEdge* >& badSmooEdges,
938 vector< _EdgesOnShape* >& eosC1,
940 void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
941 void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
942 vector< _EdgesOnShape* >& eosC1,
943 int smooStep=0, bool moveAll=false );
944 void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
945 void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
946 void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
947 _EdgesOnShape& eos1, _EdgesOnShape& eos2,
948 SMESH_MesherHelper& helper );
949 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
950 bool updateNormalsOfConvexFaces( _SolidData& data,
951 SMESH_MesherHelper& helper,
953 void updateNormalsOfC1Vertices( _SolidData& data );
954 bool updateNormalsOfSmoothed( _SolidData& data,
955 SMESH_MesherHelper& helper,
957 const double stepSize );
958 bool isNewNormalOk( _SolidData& data,
960 const gp_XYZ& newNormal);
961 bool refine(_SolidData& data);
962 bool shrink(_SolidData& data);
963 bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
964 SMESH_MesherHelper& helper,
965 const SMESHDS_SubMesh* faceSubMesh );
966 void restoreNoShrink( _LayerEdge& edge ) const;
967 void fixBadFaces(const TopoDS_Face& F,
968 SMESH_MesherHelper& helper,
971 set<const SMDS_MeshNode*> * involvedNodes=NULL);
972 bool addBoundaryElements(_SolidData& data);
974 bool error( const string& text, int solidID=-1 );
975 SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
978 void makeGroupOfLE();
981 SMESH_ComputeErrorPtr _error;
983 vector< _SolidData > _sdVec;
984 TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
985 TopTools_MapOfShape _shrinkedFaces;
989 //--------------------------------------------------------------------------------
991 * \brief Shrinker of nodes on the EDGE
995 TopoDS_Edge _geomEdge;
996 vector<double> _initU;
997 vector<double> _normPar;
998 vector<const SMDS_MeshNode*> _nodes;
999 const _LayerEdge* _edges[2];
1002 void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1003 void Compute(bool set3D, SMESH_MesherHelper& helper);
1004 void RestoreParams();
1005 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1006 const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1007 const SMDS_MeshNode* TgtNode( bool is2nd ) const
1008 { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1009 const SMDS_MeshNode* SrcNode( bool is2nd ) const
1010 { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1012 //--------------------------------------------------------------------------------
1014 * \brief Smoother of _LayerEdge's on EDGE.
1018 struct OffPnt // point of the offsetted EDGE
1020 gp_XYZ _xyz; // coord of a point inflated from EDGE w/o smooth
1021 double _len; // length reached at previous inflation step
1022 double _param; // on EDGE
1023 _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1024 gp_XYZ _edgeDir;// EDGE tangent at _param
1025 double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1027 vector< OffPnt > _offPoints;
1028 vector< double > _leParams; // normalized param of _eos._edges on EDGE
1029 Handle(Geom_Curve) _anaCurve; // for analytic smooth
1030 _LayerEdge _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1031 gp_XYZ _edgeDir[2]; // tangent at VERTEXes
1032 size_t _iSeg[2]; // index of segment where extreme tgt node is projected
1033 _EdgesOnShape& _eos;
1034 double _curveLen; // length of the EDGE
1036 static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
1038 SMESH_MesherHelper& helper);
1040 _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1041 _EdgesOnShape& eos )
1042 : _anaCurve( curveForSmooth ), _eos( eos )
1045 bool Perform(_SolidData& data,
1046 Handle(ShapeAnalysis_Surface)& surface,
1047 const TopoDS_Face& F,
1048 SMESH_MesherHelper& helper )
1050 if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1054 return smoothAnalyticEdge( data, surface, F, helper );
1056 return smoothComplexEdge ( data, surface, F, helper );
1058 void prepare(_SolidData& data );
1060 bool smoothAnalyticEdge( _SolidData& data,
1061 Handle(ShapeAnalysis_Surface)& surface,
1062 const TopoDS_Face& F,
1063 SMESH_MesherHelper& helper);
1065 bool smoothComplexEdge( _SolidData& data,
1066 Handle(ShapeAnalysis_Surface)& surface,
1067 const TopoDS_Face& F,
1068 SMESH_MesherHelper& helper);
1070 gp_XYZ getNormalNormal( const gp_XYZ & normal,
1071 const gp_XYZ& edgeDir);
1073 _LayerEdge* getLEdgeOnV( bool is2nd )
1075 return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1077 bool isAnalytic() const { return !_anaCurve.IsNull(); }
1079 //--------------------------------------------------------------------------------
1081 * \brief Class of temporary mesh face.
1082 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1083 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1085 struct _TmpMeshFace : public SMDS_MeshElement
1087 vector<const SMDS_MeshNode* > _nn;
1088 _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1089 int id, int faceID=-1, int idInFace=-1):
1090 SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1091 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1092 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
1093 virtual vtkIdType GetVtkType() const { return -1; }
1094 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
1095 virtual SMDSAbs_GeometryType GetGeomType() const
1096 { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1097 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1098 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1100 //--------------------------------------------------------------------------------
1102 * \brief Class of temporary mesh face storing _LayerEdge it's based on
1104 struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1106 _LayerEdge *_le1, *_le2;
1107 _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1108 _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1110 _nn[0]=_le1->_nodes[0];
1111 _nn[1]=_le1->_nodes.back();
1112 _nn[2]=_le2->_nodes.back();
1113 _nn[3]=_le2->_nodes[0];
1115 gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1117 SMESH_TNodeXYZ p0s( _nn[0] );
1118 SMESH_TNodeXYZ p0t( _nn[1] );
1119 SMESH_TNodeXYZ p1t( _nn[2] );
1120 SMESH_TNodeXYZ p1s( _nn[3] );
1121 gp_XYZ v0 = p0t - p0s;
1122 gp_XYZ v1 = p1t - p1s;
1123 gp_XYZ v01 = p1s - p0s;
1124 gp_XYZ n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1129 gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1131 _nn[0]=le1->_nodes[0];
1132 _nn[1]=le1->_nodes.back();
1133 _nn[2]=le2->_nodes.back();
1134 _nn[3]=le2->_nodes[0];
1138 //--------------------------------------------------------------------------------
1140 * \brief Retriever of node coordinates either directly or from a surface by node UV.
1141 * \warning Location of a surface is ignored
1143 struct _NodeCoordHelper
1145 SMESH_MesherHelper& _helper;
1146 const TopoDS_Face& _face;
1147 Handle(Geom_Surface) _surface;
1148 gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1150 _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1151 : _helper( helper ), _face( F )
1155 TopLoc_Location loc;
1156 _surface = BRep_Tool::Surface( _face, loc );
1158 if ( _surface.IsNull() )
1159 _fun = & _NodeCoordHelper::direct;
1161 _fun = & _NodeCoordHelper::byUV;
1163 gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1166 gp_XYZ direct(const SMDS_MeshNode* n) const
1168 return SMESH_TNodeXYZ( n );
1170 gp_XYZ byUV (const SMDS_MeshNode* n) const
1172 gp_XY uv = _helper.GetNodeUV( _face, n );
1173 return _surface->Value( uv.X(), uv.Y() ).XYZ();
1177 //================================================================================
1179 * \brief Check angle between vectors
1181 //================================================================================
1183 inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1185 double dot = v1 * v2; // cos * |v1| * |v2|
1186 double l1 = v1.SquareMagnitude();
1187 double l2 = v2.SquareMagnitude();
1188 return (( dot * cos >= 0 ) &&
1189 ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1192 } // namespace VISCOUS_3D
1196 //================================================================================
1197 // StdMeshers_ViscousLayers hypothesis
1199 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1200 :SMESH_Hypothesis(hypId, studyId, gen),
1201 _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1202 _method( SURF_OFFSET_SMOOTH )
1204 _name = StdMeshers_ViscousLayers::GetHypType();
1205 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1206 } // --------------------------------------------------------------------------------
1207 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1209 if ( faceIds != _shapeIds )
1210 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1211 if ( _isToIgnoreShapes != toIgnore )
1212 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1213 } // --------------------------------------------------------------------------------
1214 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1216 if ( thickness != _thickness )
1217 _thickness = thickness, NotifySubMeshesHypothesisModification();
1218 } // --------------------------------------------------------------------------------
1219 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1221 if ( _nbLayers != nb )
1222 _nbLayers = nb, NotifySubMeshesHypothesisModification();
1223 } // --------------------------------------------------------------------------------
1224 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1226 if ( _stretchFactor != factor )
1227 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1231 if ( _method != method )
1232 _method = method, NotifySubMeshesHypothesisModification();
1233 } // --------------------------------------------------------------------------------
1234 SMESH_ProxyMesh::Ptr
1235 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
1236 const TopoDS_Shape& theShape,
1237 const bool toMakeN2NMap) const
1239 using namespace VISCOUS_3D;
1240 _ViscousBuilder builder;
1241 SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1242 if ( err && !err->IsOK() )
1243 return SMESH_ProxyMesh::Ptr();
1245 vector<SMESH_ProxyMesh::Ptr> components;
1246 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1247 for ( ; exp.More(); exp.Next() )
1249 if ( _MeshOfSolid* pm =
1250 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1252 if ( toMakeN2NMap && !pm->_n2nMapComputed )
1253 if ( !builder.MakeN2NMap( pm ))
1254 return SMESH_ProxyMesh::Ptr();
1255 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1256 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1258 if ( pm->_warning && !pm->_warning->IsOK() )
1260 SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1261 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1262 if ( !smError || smError->IsOK() )
1263 smError = pm->_warning;
1266 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1268 switch ( components.size() )
1272 case 1: return components[0];
1274 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1276 return SMESH_ProxyMesh::Ptr();
1277 } // --------------------------------------------------------------------------------
1278 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1280 save << " " << _nbLayers
1281 << " " << _thickness
1282 << " " << _stretchFactor
1283 << " " << _shapeIds.size();
1284 for ( size_t i = 0; i < _shapeIds.size(); ++i )
1285 save << " " << _shapeIds[i];
1286 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1287 save << " " << _method;
1289 } // --------------------------------------------------------------------------------
1290 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1292 int nbFaces, faceID, shapeToTreat, method;
1293 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1294 while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1295 _shapeIds.push_back( faceID );
1296 if ( load >> shapeToTreat ) {
1297 _isToIgnoreShapes = !shapeToTreat;
1298 if ( load >> method )
1299 _method = (ExtrusionMethod) method;
1302 _isToIgnoreShapes = true; // old behavior
1305 } // --------------------------------------------------------------------------------
1306 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
1307 const TopoDS_Shape& theShape)
1311 } // --------------------------------------------------------------------------------
1312 SMESH_ComputeErrorPtr
1313 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh& theMesh,
1314 const TopoDS_Shape& theShape,
1315 SMESH_Hypothesis::Hypothesis_Status& theStatus)
1317 VISCOUS_3D::_ViscousBuilder builder;
1318 SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1319 if ( err && !err->IsOK() )
1320 theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1322 theStatus = SMESH_Hypothesis::HYP_OK;
1326 // --------------------------------------------------------------------------------
1327 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1330 ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1331 return IsToIgnoreShapes() ? !isIn : isIn;
1333 // END StdMeshers_ViscousLayers hypothesis
1334 //================================================================================
1336 namespace VISCOUS_3D
1338 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1342 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1343 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1344 gp_Pnt p = BRep_Tool::Pnt( fromV );
1345 double distF = p.SquareDistance( c->Value( f ));
1346 double distL = p.SquareDistance( c->Value( l ));
1347 c->D1(( distF < distL ? f : l), p, dir );
1348 if ( distL < distF ) dir.Reverse();
1351 //--------------------------------------------------------------------------------
1352 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1353 SMESH_MesherHelper& helper)
1356 double f,l; gp_Pnt p;
1357 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1358 if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1359 double u = helper.GetNodeU( E, atNode );
1363 //--------------------------------------------------------------------------------
1364 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1365 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1367 //--------------------------------------------------------------------------------
1368 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1369 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1372 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1375 TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1376 return getFaceDir( F, v, node, helper, ok );
1378 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1379 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1380 gp_Pnt p; gp_Vec du, dv, norm;
1381 surface->D1( uv.X(),uv.Y(), p, du,dv );
1384 double u = helper.GetNodeU( fromE, node, 0, &ok );
1386 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1387 if ( o == TopAbs_REVERSED )
1390 gp_Vec dir = norm ^ du;
1392 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1393 helper.IsClosedEdge( fromE ))
1395 if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1396 else c->D1( f, p, dv );
1397 if ( o == TopAbs_REVERSED )
1399 gp_Vec dir2 = norm ^ dv;
1400 dir = dir.Normalized() + dir2.Normalized();
1404 //--------------------------------------------------------------------------------
1405 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1406 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1407 bool& ok, double* cosin)
1409 TopoDS_Face faceFrw = F;
1410 faceFrw.Orientation( TopAbs_FORWARD );
1411 //double f,l; TopLoc_Location loc;
1412 TopoDS_Edge edges[2]; // sharing a vertex
1415 TopoDS_Vertex VV[2];
1416 TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1417 for ( ; exp.More() && nbEdges < 2; exp.Next() )
1419 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1420 if ( SMESH_Algo::isDegenerated( e )) continue;
1421 TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1422 if ( VV[1].IsSame( fromV )) {
1423 nbEdges += edges[ 0 ].IsNull();
1426 else if ( VV[0].IsSame( fromV )) {
1427 nbEdges += edges[ 1 ].IsNull();
1432 gp_XYZ dir(0,0,0), edgeDir[2];
1435 // get dirs of edges going fromV
1437 for ( size_t i = 0; i < nbEdges && ok; ++i )
1439 edgeDir[i] = getEdgeDir( edges[i], fromV );
1440 double size2 = edgeDir[i].SquareModulus();
1441 if (( ok = size2 > numeric_limits<double>::min() ))
1442 edgeDir[i] /= sqrt( size2 );
1444 if ( !ok ) return dir;
1446 // get angle between the 2 edges
1448 double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1449 if ( Abs( angle ) < 5 * M_PI/180 )
1451 dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1455 dir = edgeDir[0] + edgeDir[1];
1460 double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1461 *cosin = Cos( angle );
1464 else if ( nbEdges == 1 )
1466 dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1467 if ( cosin ) *cosin = 1.;
1477 //================================================================================
1479 * \brief Finds concave VERTEXes of a FACE
1481 //================================================================================
1483 bool getConcaveVertices( const TopoDS_Face& F,
1484 SMESH_MesherHelper& helper,
1485 set< TGeomID >* vertices = 0)
1487 // check angles at VERTEXes
1489 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1490 for ( size_t iW = 0; iW < wires.size(); ++iW )
1492 const int nbEdges = wires[iW]->NbEdges();
1493 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1495 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1497 if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1498 int iE2 = ( iE1 + 1 ) % nbEdges;
1499 while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1500 iE2 = ( iE2 + 1 ) % nbEdges;
1501 TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1502 double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1503 wires[iW]->Edge( iE2 ), F, V );
1504 if ( angle < -5. * M_PI / 180. )
1508 vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1512 return vertices ? !vertices->empty() : false;
1515 //================================================================================
1517 * \brief Returns true if a FACE is bound by a concave EDGE
1519 //================================================================================
1521 bool isConcave( const TopoDS_Face& F,
1522 SMESH_MesherHelper& helper,
1523 set< TGeomID >* vertices = 0 )
1525 bool isConcv = false;
1526 // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1528 gp_Vec2d drv1, drv2;
1530 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1531 for ( ; eExp.More(); eExp.Next() )
1533 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1534 if ( SMESH_Algo::isDegenerated( E )) continue;
1535 // check if 2D curve is concave
1536 BRepAdaptor_Curve2d curve( E, F );
1537 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1538 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1539 curve.Intervals( intervals, GeomAbs_C2 );
1540 bool isConvex = true;
1541 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1543 double u1 = intervals( i );
1544 double u2 = intervals( i+1 );
1545 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1546 double cross = drv1 ^ drv2;
1547 if ( E.Orientation() == TopAbs_REVERSED )
1549 isConvex = ( cross > -1e-9 ); // 0.1 );
1553 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1562 // check angles at VERTEXes
1563 if ( getConcaveVertices( F, helper, vertices ))
1569 //================================================================================
1571 * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1572 * \param [in] face - the mesh face to treat
1573 * \param [in] nodeOnEdge - a node on the EDGE
1574 * \param [out] faceSize - the computed distance
1575 * \return bool - true if faceSize computed
1577 //================================================================================
1579 bool getDistFromEdge( const SMDS_MeshElement* face,
1580 const SMDS_MeshNode* nodeOnEdge,
1583 faceSize = Precision::Infinite();
1586 int nbN = face->NbCornerNodes();
1587 int iOnE = face->GetNodeIndex( nodeOnEdge );
1588 int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1589 SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1590 const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1591 face->GetNode( iNext[1] ) };
1592 gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1593 double segLen = -1.;
1594 // look for two neighbor not in-FACE nodes of face
1595 for ( int i = 0; i < 2; ++i )
1597 if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1598 nNext[i]->GetID() < nodeOnEdge->GetID() )
1600 // look for an in-FACE node
1601 for ( int iN = 0; iN < nbN; ++iN )
1603 if ( iN == iOnE || iN == iNext[i] )
1605 SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1606 gp_XYZ v = pInFace - segEnd;
1609 segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1610 segLen = segVec.Modulus();
1612 double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1613 faceSize = Min( faceSize, distToSeg );
1621 //================================================================================
1623 * \brief Return direction of axis or revolution of a surface
1625 //================================================================================
1627 bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1630 switch ( surface.GetType() ) {
1633 gp_Cone cone = surface.Cone();
1634 axis = cone.Axis().Direction();
1637 case GeomAbs_Sphere:
1639 gp_Sphere sphere = surface.Sphere();
1640 axis = sphere.Position().Direction();
1643 case GeomAbs_SurfaceOfRevolution:
1645 axis = surface.AxeOfRevolution().Direction();
1648 //case GeomAbs_SurfaceOfExtrusion:
1649 case GeomAbs_OffsetSurface:
1651 Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1652 return getRovolutionAxis( base->Surface(), axis );
1654 default: return false;
1659 //--------------------------------------------------------------------------------
1660 // DEBUG. Dump intermediate node positions into a python script
1661 // HOWTO use: run python commands written in a console to see
1662 // construction steps of viscous layers
1667 PyDump(SMESH_Mesh& m) {
1668 int tag = 3 + m.GetId();
1669 const char* fname = "/tmp/viscous.py";
1670 cout << "execfile('"<<fname<<"')"<<endl;
1671 py = new ofstream(fname);
1672 *py << "import SMESH" << endl
1673 << "from salome.smesh import smeshBuilder" << endl
1674 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
1675 << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1676 << "mesh = smesh.Mesh( meshSO.GetObject() )"<<endl;
1681 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1682 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1683 *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1684 "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1688 ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1690 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1691 #define dumpMove(n) { _dumpMove(n, __LINE__);}
1692 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1693 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
1694 void _dumpFunction(const string& fun, int ln)
1695 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1696 void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1697 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1698 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1699 void _dumpCmd(const string& txt, int ln)
1700 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
1701 void dumpFunctionEnd()
1702 { if (py) *py<< " return"<< endl; }
1703 void dumpChangeNodes( const SMDS_MeshElement* f )
1704 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
1705 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1706 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1707 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1711 struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1712 #define dumpFunction(f) f
1714 #define dumpMoveComm(n,txt)
1715 #define dumpCmd(txt)
1716 #define dumpFunctionEnd()
1717 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1718 #define debugMsg( txt ) {}
1723 using namespace VISCOUS_3D;
1725 //================================================================================
1727 * \brief Constructor of _ViscousBuilder
1729 //================================================================================
1731 _ViscousBuilder::_ViscousBuilder()
1733 _error = SMESH_ComputeError::New(COMPERR_OK);
1737 //================================================================================
1739 * \brief Stores error description and returns false
1741 //================================================================================
1743 bool _ViscousBuilder::error(const string& text, int solidId )
1745 const string prefix = string("Viscous layers builder: ");
1746 _error->myName = COMPERR_ALGO_FAILED;
1747 _error->myComment = prefix + text;
1750 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1751 if ( !sm && !_sdVec.empty() )
1752 sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1753 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1755 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1756 if ( smError && smError->myAlgo )
1757 _error->myAlgo = smError->myAlgo;
1759 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1761 // set KO to all solids
1762 for ( size_t i = 0; i < _sdVec.size(); ++i )
1764 if ( _sdVec[i]._index == solidId )
1766 sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1767 if ( !sm->IsEmpty() )
1769 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1770 if ( !smError || smError->IsOK() )
1772 smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1773 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1777 makeGroupOfLE(); // debug
1782 //================================================================================
1784 * \brief At study restoration, restore event listeners used to clear an inferior
1785 * dim sub-mesh modified by viscous layers
1787 //================================================================================
1789 void _ViscousBuilder::RestoreListeners()
1794 //================================================================================
1796 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1798 //================================================================================
1800 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1802 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1803 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1804 for ( ; fExp.More(); fExp.Next() )
1806 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1807 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1809 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1811 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1814 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1815 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1817 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1818 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1819 while( prxIt->more() )
1821 const SMDS_MeshElement* fSrc = srcIt->next();
1822 const SMDS_MeshElement* fPrx = prxIt->next();
1823 if ( fSrc->NbNodes() != fPrx->NbNodes())
1824 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1825 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1826 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1829 pm->_n2nMapComputed = true;
1833 //================================================================================
1835 * \brief Does its job
1837 //================================================================================
1839 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
1840 const TopoDS_Shape& theShape)
1844 // check if proxy mesh already computed
1845 TopExp_Explorer exp( theShape, TopAbs_SOLID );
1847 return error("No SOLID's in theShape"), _error;
1849 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1850 return SMESH_ComputeErrorPtr(); // everything already computed
1852 PyDump debugDump( theMesh );
1854 // TODO: ignore already computed SOLIDs
1855 if ( !findSolidsWithLayers())
1858 if ( !findFacesWithLayers() )
1861 for ( size_t i = 0; i < _sdVec.size(); ++i )
1864 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1865 if ( _sdVec[iSD]._before.IsEmpty() &&
1866 _sdVec[iSD]._n2eMap.empty() )
1869 if ( ! makeLayer(_sdVec[iSD]) )
1872 if ( _sdVec[iSD]._n2eMap.size() == 0 )
1875 if ( ! inflate(_sdVec[iSD]) )
1878 if ( ! refine(_sdVec[iSD]) )
1881 if ( !shrink(_sdVec[iSD]) )
1884 addBoundaryElements(_sdVec[iSD]);
1886 const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1887 for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1888 _sdVec[iSD]._before.Remove( solid );
1891 makeGroupOfLE(); // debug
1897 //================================================================================
1899 * \brief Check validity of hypotheses
1901 //================================================================================
1903 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh& mesh,
1904 const TopoDS_Shape& shape )
1908 if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1909 return SMESH_ComputeErrorPtr(); // everything already computed
1912 findSolidsWithLayers();
1913 bool ok = findFacesWithLayers( true );
1915 // remove _MeshOfSolid's of _SolidData's
1916 for ( size_t i = 0; i < _sdVec.size(); ++i )
1917 _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1922 return SMESH_ComputeErrorPtr();
1925 //================================================================================
1927 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1929 //================================================================================
1931 bool _ViscousBuilder::findSolidsWithLayers()
1934 TopTools_IndexedMapOfShape allSolids;
1935 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1936 _sdVec.reserve( allSolids.Extent());
1938 SMESH_HypoFilter filter;
1939 for ( int i = 1; i <= allSolids.Extent(); ++i )
1941 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1942 SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1943 if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1944 continue; // solid is already meshed
1945 SMESH_Algo* algo = sm->GetAlgo();
1946 if ( !algo ) continue;
1947 // TODO: check if algo is hidden
1948 const list <const SMESHDS_Hypothesis *> & allHyps =
1949 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1950 _SolidData* soData = 0;
1951 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1952 const StdMeshers_ViscousLayers* viscHyp = 0;
1953 for ( ; hyp != allHyps.end(); ++hyp )
1954 if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1956 TopoDS_Shape hypShape;
1957 filter.Init( filter.Is( viscHyp ));
1958 _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1962 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1965 _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1966 soData = & _sdVec.back();
1967 soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1968 soData->_helper = new SMESH_MesherHelper( *_mesh );
1969 soData->_helper->SetSubShape( allSolids(i) );
1970 _solids.Add( allSolids(i) );
1972 soData->_hyps.push_back( viscHyp );
1973 soData->_hypShapes.push_back( hypShape );
1976 if ( _sdVec.empty() )
1978 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1983 //================================================================================
1985 * \brief Set a _SolidData to be computed before another
1987 //================================================================================
1989 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1991 // check possibility to set this order; get all solids before solidBefore
1992 TopTools_IndexedMapOfShape allSolidsBefore;
1993 allSolidsBefore.Add( solidBefore._solid );
1994 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1996 int iSD = _solids.FindIndex( allSolidsBefore(i) );
1999 TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2000 for ( ; soIt.More(); soIt.Next() )
2001 allSolidsBefore.Add( soIt.Value() );
2004 if ( allSolidsBefore.Contains( solidAfter._solid ))
2007 for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2008 solidAfter._before.Add( allSolidsBefore(i) );
2013 //================================================================================
2017 //================================================================================
2019 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2021 SMESH_MesherHelper helper( *_mesh );
2022 TopExp_Explorer exp;
2024 // collect all faces-to-ignore defined by hyp
2025 for ( size_t i = 0; i < _sdVec.size(); ++i )
2027 // get faces-to-ignore defined by each hyp
2028 typedef const StdMeshers_ViscousLayers* THyp;
2029 typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2030 list< TFacesOfHyp > ignoreFacesOfHyps;
2031 list< THyp >::iterator hyp = _sdVec[i]._hyps.begin();
2032 list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2033 for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2035 ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2036 getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2039 // fill _SolidData::_face2hyp and check compatibility of hypotheses
2040 const int nbHyps = _sdVec[i]._hyps.size();
2043 // check if two hypotheses define different parameters for the same FACE
2044 list< TFacesOfHyp >::iterator igFacesOfHyp;
2045 for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2047 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2049 igFacesOfHyp = ignoreFacesOfHyps.begin();
2050 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2051 if ( ! igFacesOfHyp->first.count( faceID ))
2054 return error(SMESH_Comment("Several hypotheses define "
2055 "Viscous Layers on the face #") << faceID );
2056 hyp = igFacesOfHyp->second;
2059 _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2061 _sdVec[i]._ignoreFaceIds.insert( faceID );
2064 // check if two hypotheses define different number of viscous layers for
2065 // adjacent faces of a solid
2066 set< int > nbLayersSet;
2067 igFacesOfHyp = ignoreFacesOfHyps.begin();
2068 for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2070 nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2072 if ( nbLayersSet.size() > 1 )
2074 for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2076 PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2077 THyp hyp1 = 0, hyp2 = 0;
2078 while( const TopoDS_Shape* face = fIt->next() )
2080 const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2081 map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2082 if ( f2h != _sdVec[i]._face2hyp.end() )
2084 ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2087 if ( hyp1 && hyp2 &&
2088 hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2090 return error("Two hypotheses define different number of "
2091 "viscous layers on adjacent faces");
2095 } // if ( nbHyps > 1 )
2098 _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2102 if ( onlyWith ) // is called to check hypotheses compatibility only
2105 // fill _SolidData::_reversedFaceIds
2106 for ( size_t i = 0; i < _sdVec.size(); ++i )
2108 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2109 for ( ; exp.More(); exp.Next() )
2111 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2112 const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2113 if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2114 helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2115 helper.IsReversedSubMesh( face ))
2117 _sdVec[i]._reversedFaceIds.insert( faceID );
2122 // Find faces to shrink mesh on (solution 2 in issue 0020832);
2123 TopTools_IndexedMapOfShape shapes;
2124 std::string structAlgoName = "Hexa_3D";
2125 for ( size_t i = 0; i < _sdVec.size(); ++i )
2128 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2129 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2131 const TopoDS_Shape& edge = shapes(iE);
2132 // find 2 faces sharing an edge
2134 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2135 while ( fIt->more())
2137 const TopoDS_Shape* f = fIt->next();
2138 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2139 FF[ int( !FF[0].IsNull()) ] = *f;
2141 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2142 // check presence of layers on them
2144 for ( int j = 0; j < 2; ++j )
2145 ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2146 if ( ignore[0] == ignore[1] )
2147 continue; // nothing interesting
2148 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2149 // check presence of layers on fWOL within an adjacent SOLID
2150 bool collision = false;
2151 PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2152 while ( const TopoDS_Shape* solid = sIt->next() )
2153 if ( !solid->IsSame( _sdVec[i]._solid ))
2155 int iSolid = _solids.FindIndex( *solid );
2156 int iFace = getMeshDS()->ShapeToIndex( fWOL );
2157 if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2159 // check if solid's mesh is unstructured and then try to set it
2160 // to be computed after the i-th solid
2161 SMESH_Algo* algo = _mesh->GetSubMesh( *solid )->GetAlgo();
2162 bool isStructured = ( algo->GetName() == structAlgoName );
2163 if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid-1 ] ))
2164 collision = true; // don't shrink fWOL
2169 if ( !fWOL.IsNull())
2171 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2172 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2175 // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2176 // on the edge but shrink won't be performed
2177 _sdVec[i]._noShrinkShapes.insert( edgeInd );
2178 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2179 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2184 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2185 // the algo of the SOLID sharing the FACE does not support it
2186 set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2187 for ( size_t i = 0; i < _sdVec.size(); ++i )
2189 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2190 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2192 const TopoDS_Shape& fWOL = e2f->second;
2193 const TGeomID edgeID = e2f->first;
2194 bool notShrinkFace = false;
2195 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2196 while ( soIt->more() )
2198 const TopoDS_Shape* solid = soIt->next();
2199 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2200 SMESH_Algo* algo = _mesh->GetSubMesh( *solid )->GetAlgo();
2201 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2202 notShrinkFace = true;
2204 for ( ; iSolid < _sdVec.size(); ++iSolid )
2206 if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2207 if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2208 notShrinkFace = false;
2212 if ( notShrinkFace )
2214 _sdVec[i]._noShrinkShapes.insert( edgeID );
2216 // add VERTEXes of the edge in _noShrinkShapes
2217 TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2218 for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2219 _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2221 // check if there is a collision with to-shrink-from EDGEs in iSolid
2222 if ( iSolid == _sdVec.size() )
2223 continue; // no VL in the solid
2225 TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2226 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2228 const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2229 const TGeomID eID = getMeshDS()->ShapeToIndex( E );
2230 if ( eID == edgeID ||
2231 !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2232 _sdVec[i]._noShrinkShapes.count( eID ))
2234 for ( int is1st = 0; is1st < 2; ++is1st )
2236 TopoDS_Vertex V = helper.IthVertex( is1st, E );
2237 if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2239 // _sdVec[i]._noShrinkShapes.insert( eID );
2240 // V = helper.IthVertex( !is1st, E );
2241 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2242 //iE = 0; // re-start the loop on EDGEs of fWOL
2243 return error("No way to make a conformal mesh with "
2244 "the given set of faces with layers", _sdVec[i]._index);
2250 } // while ( soIt->more() )
2251 } // loop on _sdVec[i]._shrinkShape2Shape
2252 } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2254 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2256 for ( size_t i = 0; i < _sdVec.size(); ++i )
2259 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2260 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2262 const TopoDS_Shape& vertex = shapes(iV);
2263 // find faces WOL sharing the vertex
2264 vector< TopoDS_Shape > facesWOL;
2265 size_t totalNbFaces = 0;
2266 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2267 while ( fIt->more())
2269 const TopoDS_Shape* f = fIt->next();
2270 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2273 const int fID = getMeshDS()->ShapeToIndex( *f );
2274 if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2275 !_sdVec[i]._noShrinkShapes.count( fID )*/)
2276 facesWOL.push_back( *f );
2279 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2280 continue; // no layers at this vertex or no WOL
2281 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2282 switch ( facesWOL.size() )
2286 helper.SetSubShape( facesWOL[0] );
2287 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2289 TopoDS_Shape seamEdge;
2290 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2291 while ( eIt->more() && seamEdge.IsNull() )
2293 const TopoDS_Shape* e = eIt->next();
2294 if ( helper.IsRealSeam( *e ) )
2297 if ( !seamEdge.IsNull() )
2299 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2303 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2308 // find an edge shared by 2 faces
2309 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2310 while ( eIt->more())
2312 const TopoDS_Shape* e = eIt->next();
2313 if ( helper.IsSubShape( *e, facesWOL[0]) &&
2314 helper.IsSubShape( *e, facesWOL[1]))
2316 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2322 return error("Not yet supported case", _sdVec[i]._index);
2327 // add FACEs of other SOLIDs to _ignoreFaceIds
2328 for ( size_t i = 0; i < _sdVec.size(); ++i )
2331 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2333 for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2335 if ( !shapes.Contains( exp.Current() ))
2336 _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2343 //================================================================================
2345 * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2347 //================================================================================
2349 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape& solid,
2350 const StdMeshers_ViscousLayers* hyp,
2351 const TopoDS_Shape& hypShape,
2352 set<TGeomID>& ignoreFaceIds)
2354 TopExp_Explorer exp;
2356 vector<TGeomID> ids = hyp->GetBndShapes();
2357 if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2359 for ( size_t ii = 0; ii < ids.size(); ++ii )
2361 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2362 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2363 ignoreFaceIds.insert( ids[ii] );
2366 else // FACEs with layers are given
2368 exp.Init( solid, TopAbs_FACE );
2369 for ( ; exp.More(); exp.Next() )
2371 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2372 if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2373 ignoreFaceIds.insert( faceInd );
2377 // ignore internal FACEs if inlets and outlets are specified
2378 if ( hyp->IsToIgnoreShapes() )
2380 TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2381 TopExp::MapShapesAndAncestors( hypShape,
2382 TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2384 for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2386 const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2387 if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2390 int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2392 ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2397 //================================================================================
2399 * \brief Create the inner surface of the viscous layer and prepare data for infation
2401 //================================================================================
2403 bool _ViscousBuilder::makeLayer(_SolidData& data)
2405 // get all sub-shapes to make layers on
2406 set<TGeomID> subIds, faceIds;
2407 subIds = data._noShrinkShapes;
2408 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2409 for ( ; exp.More(); exp.Next() )
2411 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2412 if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2413 faceIds.insert( fSubM->GetId() );
2416 // make a map to find new nodes on sub-shapes shared with other SOLID
2417 map< TGeomID, TNode2Edge* >::iterator s2ne;
2418 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2419 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2421 TGeomID shapeInd = s2s->first;
2422 for ( size_t i = 0; i < _sdVec.size(); ++i )
2424 if ( _sdVec[i]._index == data._index ) continue;
2425 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2426 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2427 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2429 data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2435 // Create temporary faces and _LayerEdge's
2437 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2439 data._stepSize = Precision::Infinite();
2440 data._stepSizeNodes[0] = 0;
2442 SMESH_MesherHelper helper( *_mesh );
2443 helper.SetSubShape( data._solid );
2444 helper.SetElementsOnShape( true );
2446 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2447 TNode2Edge::iterator n2e2;
2449 // collect _LayerEdge's of shapes they are based on
2450 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2451 const int nbShapes = getMeshDS()->MaxShapeIndex();
2452 edgesByGeom.resize( nbShapes+1 );
2454 // set data of _EdgesOnShape's
2455 if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2457 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2458 while ( smIt->more() )
2461 if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2462 !faceIds.count( sm->GetId() ))
2464 setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2467 // make _LayerEdge's
2468 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2470 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2471 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2472 SMESH_ProxyMesh::SubMesh* proxySub =
2473 data._proxyMesh->getFaceSubM( F, /*create=*/true);
2475 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2476 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2478 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2479 while ( eIt->more() )
2481 const SMDS_MeshElement* face = eIt->next();
2482 double faceMaxCosin = -1;
2483 _LayerEdge* maxCosinEdge = 0;
2484 int nbDegenNodes = 0;
2486 newNodes.resize( face->NbCornerNodes() );
2487 for ( size_t i = 0 ; i < newNodes.size(); ++i )
2489 const SMDS_MeshNode* n = face->GetNode( i );
2490 const int shapeID = n->getshapeId();
2491 const bool onDegenShap = helper.IsDegenShape( shapeID );
2492 const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2497 // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2498 const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2499 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2500 if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2510 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2511 if ( !(*n2e).second )
2514 _LayerEdge* edge = new _LayerEdge();
2515 edge->_nodes.push_back( n );
2517 edgesByGeom[ shapeID ]._edges.push_back( edge );
2518 const bool noShrink = data._noShrinkShapes.count( shapeID );
2520 SMESH_TNodeXYZ xyz( n );
2522 // set edge data or find already refined _LayerEdge and get data from it
2523 if (( !noShrink ) &&
2524 ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE ) &&
2525 (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2526 (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end() ))
2528 _LayerEdge* foundEdge = (*n2e2).second;
2529 gp_XYZ lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2530 foundEdge->_pos.push_back( lastPos );
2531 // location of the last node is modified and we restore it by foundEdge->_pos.back()
2532 const_cast< SMDS_MeshNode* >
2533 ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2539 edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2541 if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2544 if ( edge->_nodes.size() < 2 )
2545 edge->Block( data );
2546 //data._noShrinkShapes.insert( shapeID );
2548 dumpMove(edge->_nodes.back());
2550 if ( edge->_cosin > faceMaxCosin )
2552 faceMaxCosin = edge->_cosin;
2553 maxCosinEdge = edge;
2556 newNodes[ i ] = n2e->second->_nodes.back();
2559 data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2561 if ( newNodes.size() - nbDegenNodes < 2 )
2564 // create a temporary face
2565 const SMDS_MeshElement* newFace =
2566 new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2567 proxySub->AddElement( newFace );
2569 // compute inflation step size by min size of element on a convex surface
2570 if ( faceMaxCosin > theMinSmoothCosin )
2571 limitStepSize( data, face, maxCosinEdge );
2573 } // loop on 2D elements on a FACE
2574 } // loop on FACEs of a SOLID to create _LayerEdge's
2577 // Set _LayerEdge::_neibors
2578 TNode2Edge::iterator n2e;
2579 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2581 _EdgesOnShape& eos = data._edgesOnShape[iS];
2582 for ( size_t i = 0; i < eos._edges.size(); ++i )
2584 _LayerEdge* edge = eos._edges[i];
2585 TIDSortedNodeSet nearNodes;
2586 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2587 while ( fIt->more() )
2589 const SMDS_MeshElement* f = fIt->next();
2590 if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2591 nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2593 nearNodes.erase( edge->_nodes[0] );
2594 edge->_neibors.reserve( nearNodes.size() );
2595 TIDSortedNodeSet::iterator node = nearNodes.begin();
2596 for ( ; node != nearNodes.end(); ++node )
2597 if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2598 edge->_neibors.push_back( n2e->second );
2602 data._epsilon = 1e-7;
2603 if ( data._stepSize < 1. )
2604 data._epsilon *= data._stepSize;
2606 if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2609 // limit data._stepSize depending on surface curvature and fill data._convexFaces
2610 limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2612 // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2613 const SMDS_MeshNode* nn[2];
2614 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2616 _EdgesOnShape& eos = data._edgesOnShape[iS];
2617 for ( size_t i = 0; i < eos._edges.size(); ++i )
2619 _LayerEdge* edge = eos._edges[i];
2620 if ( edge->IsOnEdge() )
2622 // get neighbor nodes
2623 bool hasData = ( edge->_2neibors->_edges[0] );
2624 if ( hasData ) // _LayerEdge is a copy of another one
2626 nn[0] = edge->_2neibors->srcNode(0);
2627 nn[1] = edge->_2neibors->srcNode(1);
2629 else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2633 // set neighbor _LayerEdge's
2634 for ( int j = 0; j < 2; ++j )
2636 if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2637 return error("_LayerEdge not found by src node", data._index);
2638 edge->_2neibors->_edges[j] = n2e->second;
2641 edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2644 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2646 _Simplex& s = edge->_simplices[j];
2647 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2648 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2651 // For an _LayerEdge on a degenerated EDGE, copy some data from
2652 // a corresponding _LayerEdge on a VERTEX
2653 // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2654 if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2656 // Generally we should not get here
2657 if ( eos.ShapeType() != TopAbs_EDGE )
2659 TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2660 const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2661 if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2663 const _LayerEdge* vEdge = n2e->second;
2664 edge->_normal = vEdge->_normal;
2665 edge->_lenFactor = vEdge->_lenFactor;
2666 edge->_cosin = vEdge->_cosin;
2669 } // loop on data._edgesOnShape._edges
2670 } // loop on data._edgesOnShape
2672 // fix _LayerEdge::_2neibors on EDGEs to smooth
2673 // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2674 // for ( ; e2c != data._edge2curve.end(); ++e2c )
2675 // if ( !e2c->second.IsNull() )
2677 // if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2678 // data.Sort2NeiborsOnEdge( eos->_edges );
2685 //================================================================================
2687 * \brief Compute inflation step size by min size of element on a convex surface
2689 //================================================================================
2691 void _ViscousBuilder::limitStepSize( _SolidData& data,
2692 const SMDS_MeshElement* face,
2693 const _LayerEdge* maxCosinEdge )
2696 double minSize = 10 * data._stepSize;
2697 const int nbNodes = face->NbCornerNodes();
2698 for ( int i = 0; i < nbNodes; ++i )
2700 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2701 const SMDS_MeshNode* curN = face->GetNode( i );
2702 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2703 curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2705 double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2706 if ( dist < minSize )
2707 minSize = dist, iN = i;
2710 double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2711 if ( newStep < data._stepSize )
2713 data._stepSize = newStep;
2714 data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2715 data._stepSizeNodes[0] = face->GetNode( iN );
2716 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2720 //================================================================================
2722 * \brief Compute inflation step size by min size of element on a convex surface
2724 //================================================================================
2726 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2728 if ( minSize < data._stepSize )
2730 data._stepSize = minSize;
2731 if ( data._stepSizeNodes[0] )
2734 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2735 data._stepSizeCoeff = data._stepSize / dist;
2740 //================================================================================
2742 * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2744 //================================================================================
2746 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2748 SMESH_MesherHelper helper( *_mesh );
2750 const int nbTestPnt = 5; // on a FACE sub-shape
2752 BRepLProp_SLProps surfProp( 2, 1e-6 );
2753 data._convexFaces.clear();
2755 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2757 _EdgesOnShape& eof = data._edgesOnShape[iS];
2758 if ( eof.ShapeType() != TopAbs_FACE ||
2759 data._ignoreFaceIds.count( eof._shapeID ))
2762 TopoDS_Face F = TopoDS::Face( eof._shape );
2763 SMESH_subMesh * sm = eof._subMesh;
2764 const TGeomID faceID = eof._shapeID;
2766 BRepAdaptor_Surface surface( F, false );
2767 surfProp.SetSurface( surface );
2769 bool isTooCurved = false;
2771 _ConvexFace cnvFace;
2772 const double oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2773 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2774 while ( smIt->more() )
2777 const TGeomID subID = sm->GetId();
2778 // find _LayerEdge's of a sub-shape
2780 if (( eos = data.GetShapeEdges( subID )))
2781 cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2784 // check concavity and curvature and limit data._stepSize
2785 const double minCurvature =
2786 1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2787 size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2788 for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2790 gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2791 surfProp.SetParameters( uv.X(), uv.Y() );
2792 if ( !surfProp.IsCurvatureDefined() )
2794 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2796 limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2799 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2801 limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2805 } // loop on sub-shapes of the FACE
2807 if ( !isTooCurved ) continue;
2809 _ConvexFace & convFace =
2810 data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2813 convFace._normalsFixed = false;
2815 // skip a closed surface (data._convexFaces is useful anyway)
2816 bool isClosedF = false;
2817 helper.SetSubShape( F );
2818 if ( helper.HasRealSeam() )
2820 // in the closed surface there must be a closed EDGE
2821 for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2822 isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2826 // limit _LayerEdge::_maxLen on the FACE
2827 const double minCurvature =
2828 1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2829 map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2830 if ( id2eos != cnvFace._subIdToEOS.end() )
2832 _EdgesOnShape& eos = * id2eos->second;
2833 for ( size_t i = 0; i < eos._edges.size(); ++i )
2835 _LayerEdge* ledge = eos._edges[ i ];
2836 gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2837 surfProp.SetParameters( uv.X(), uv.Y() );
2838 if ( !surfProp.IsCurvatureDefined() )
2841 if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2842 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2844 if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2845 ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2851 // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2852 // prism distortion.
2853 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2854 if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2856 // there are _LayerEdge's on the FACE it-self;
2857 // select _LayerEdge's near EDGEs
2858 _EdgesOnShape& eos = * id2eos->second;
2859 for ( size_t i = 0; i < eos._edges.size(); ++i )
2861 _LayerEdge* ledge = eos._edges[ i ];
2862 for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2863 if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2865 convFace._simplexTestEdges.push_back( ledge );
2872 // where there are no _LayerEdge's on a _ConvexFace,
2873 // as e.g. on a fillet surface with no internal nodes - issue 22580,
2874 // so that collision of viscous internal faces is not detected by check of
2875 // intersection of _LayerEdge's with the viscous internal faces.
2877 set< const SMDS_MeshNode* > usedNodes;
2879 // look for _LayerEdge's with null _sWOL
2880 id2eos = convFace._subIdToEOS.begin();
2881 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2883 _EdgesOnShape& eos = * id2eos->second;
2884 if ( !eos._sWOL.IsNull() )
2886 for ( size_t i = 0; i < eos._edges.size(); ++i )
2888 _LayerEdge* ledge = eos._edges[ i ];
2889 const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2890 if ( !usedNodes.insert( srcNode ).second ) continue;
2892 for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2894 usedNodes.insert( ledge->_simplices[i]._nPrev );
2895 usedNodes.insert( ledge->_simplices[i]._nNext );
2897 convFace._simplexTestEdges.push_back( ledge );
2901 } // loop on FACEs of data._solid
2904 //================================================================================
2906 * \brief Detect shapes (and _LayerEdge's on them) to smooth
2908 //================================================================================
2910 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2912 // define allowed thickness
2913 computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2915 data._maxThickness = 0;
2916 data._minThickness = 1e100;
2917 list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2918 for ( ; hyp != data._hyps.end(); ++hyp )
2920 data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2921 data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2923 //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2925 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2926 // boundry inclined to the shape at a sharp angle
2928 //list< TGeomID > shapesToSmooth;
2929 TopTools_MapOfShape edgesOfSmooFaces;
2931 SMESH_MesherHelper helper( *_mesh );
2934 vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2935 data._nbShapesToSmooth = 0;
2937 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2939 _EdgesOnShape& eos = edgesByGeom[iS];
2940 eos._toSmooth = false;
2941 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2944 double tgtThick = eos._hyp.GetTotalThickness();
2945 TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2946 for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2948 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2949 vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2950 if ( eE.empty() ) continue;
2953 for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2954 if ( eE[i]->_cosin > theMinSmoothCosin )
2956 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2957 while ( fIt->more() && !eos._toSmooth )
2959 const SMDS_MeshElement* face = fIt->next();
2960 if ( face->getshapeId() == eos._shapeID &&
2961 getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2963 eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2968 if ( eos._toSmooth )
2970 for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2971 edgesOfSmooFaces.Add( eExp.Current() );
2973 data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2975 data._nbShapesToSmooth += eos._toSmooth;
2979 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2981 _EdgesOnShape& eos = edgesByGeom[iS];
2982 eos._edgeSmoother = NULL;
2983 if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2984 if ( !eos._hyp.ToSmooth() ) continue;
2986 const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2987 if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2990 double tgtThick = eos._hyp.GetTotalThickness();
2991 for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2993 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2994 vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2995 if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2996 gp_Vec eDir = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2997 double angle = eDir.Angle( eV[0]->_normal );
2998 double cosin = Cos( angle );
2999 double cosinAbs = Abs( cosin );
3000 if ( cosinAbs > theMinSmoothCosin )
3002 // always smooth analytic EDGEs
3003 Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3004 eos._toSmooth = ! curve.IsNull();
3006 // compare tgtThick with the length of an end segment
3007 SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3008 while ( eIt->more() && !eos._toSmooth )
3010 const SMDS_MeshElement* endSeg = eIt->next();
3011 if ( endSeg->getshapeId() == (int) iS )
3014 SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3015 eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3018 if ( eos._toSmooth )
3020 eos._edgeSmoother = new _Smoother1D( curve, eos );
3022 for ( size_t i = 0; i < eos._edges.size(); ++i )
3023 eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3027 data._nbShapesToSmooth += eos._toSmooth;
3031 // Reset _cosin if no smooth is allowed by the user
3032 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3034 _EdgesOnShape& eos = edgesByGeom[iS];
3035 if ( eos._edges.empty() ) continue;
3037 if ( !eos._hyp.ToSmooth() )
3038 for ( size_t i = 0; i < eos._edges.size(); ++i )
3039 eos._edges[i]->SetCosin( 0 );
3043 // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3045 TopTools_MapOfShape c1VV;
3047 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3049 _EdgesOnShape& eos = edgesByGeom[iS];
3050 if ( eos._edges.empty() ||
3051 eos.ShapeType() != TopAbs_FACE ||
3055 // check EDGEs of a FACE
3056 TopTools_MapOfShape checkedEE, allVV;
3057 list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3058 while ( !smQueue.empty() )
3060 SMESH_subMesh* sm = smQueue.front();
3061 smQueue.pop_front();
3062 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3063 while ( smIt->more() )
3066 if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3067 allVV.Add( sm->GetSubShape() );
3068 if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3069 !checkedEE.Add( sm->GetSubShape() ))
3072 _EdgesOnShape* eoe = data.GetShapeEdges( sm->GetId() );
3073 vector<_LayerEdge*>& eE = eoe->_edges;
3074 if ( eE.empty() || !eoe->_sWOL.IsNull() )
3077 bool isC1 = true; // check continuity along an EDGE
3078 for ( size_t i = 0; i < eE.size() && isC1; ++i )
3079 isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3083 // check that mesh faces are C1 as well
3085 gp_XYZ norm1, norm2;
3086 const SMDS_MeshNode* n = eE[ eE.size() / 2 ]->_nodes[0];
3087 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3088 if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3090 while ( fIt->more() && isC1 )
3091 isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3092 Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3097 // add the EDGE and an adjacent FACE to _eosC1
3098 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3099 while ( const TopoDS_Shape* face = fIt->next() )
3101 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3102 if ( !eof ) continue; // other solid
3103 if ( !eos.HasC1( eoe ))
3105 eos._eosC1.push_back( eoe );
3106 eoe->_toSmooth = false;
3107 data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3109 if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof ))
3111 eos._eosC1.push_back( eof );
3112 eof->_toSmooth = false;
3113 data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3114 smQueue.push_back( eof->_subMesh );
3119 if ( eos._eosC1.empty() )
3122 // check VERTEXes of C1 FACEs
3123 TopTools_MapIteratorOfMapOfShape vIt( allVV );
3124 for ( ; vIt.More(); vIt.Next() )
3126 _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3127 if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3130 bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3131 PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3132 while ( const TopoDS_Shape* face = fIt->next() )
3134 _EdgesOnShape* eof = data.GetShapeEdges( *face );
3135 if ( !eof ) continue; // other solid
3136 isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3142 eos._eosC1.push_back( eov );
3143 data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3144 c1VV.Add( eov->_shape );
3148 } // fill _eosC1 of FACEs
3153 vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3155 for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3157 _EdgesOnShape& eov = edgesByGeom[iS];
3158 if ( eov._edges.empty() ||
3159 eov.ShapeType() != TopAbs_VERTEX ||
3160 c1VV.Contains( eov._shape ))
3162 const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3164 // get directions of surrounding EDGEs
3166 PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3167 while ( const TopoDS_Shape* e = fIt->next() )
3169 _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3170 if ( !eoe ) continue; // other solid
3171 gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3172 if ( !Precision::IsInfinite( eDir.X() ))
3173 dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3176 // find EDGEs with C1 directions
3177 for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3178 for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3179 if ( dirOfEdges[i].first && dirOfEdges[j].first )
3181 double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3182 bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3185 double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3186 double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3187 double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3188 if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3189 if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3190 dirOfEdges[i].first = 0;
3191 dirOfEdges[j].first = 0;
3194 } // fill _eosC1 of VERTEXes
3201 //================================================================================
3203 * \brief initialize data of _EdgesOnShape
3205 //================================================================================
3207 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3211 if ( !eos._shape.IsNull() ||
3212 sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3215 SMESH_MesherHelper helper( *_mesh );
3218 eos._shapeID = sm->GetId();
3219 eos._shape = sm->GetSubShape();
3220 if ( eos.ShapeType() == TopAbs_FACE )
3221 eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3222 eos._toSmooth = false;
3226 map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3227 data._shrinkShape2Shape.find( eos._shapeID );
3228 if ( s2s != data._shrinkShape2Shape.end() )
3229 eos._sWOL = s2s->second;
3231 eos._isRegularSWOL = true;
3232 if ( eos.SWOLType() == TopAbs_FACE )
3234 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3235 Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3236 eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3240 if ( data._hyps.size() == 1 )
3242 eos._hyp = data._hyps.back();
3246 // compute average StdMeshers_ViscousLayers parameters
3247 map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3248 if ( eos.ShapeType() == TopAbs_FACE )
3250 if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3251 eos._hyp = f2hyp->second;
3255 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3256 while ( const TopoDS_Shape* face = fIt->next() )
3258 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3259 if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3260 eos._hyp.Add( f2hyp->second );
3266 if ( ! eos._hyp.UseSurfaceNormal() )
3268 if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3270 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3271 eos._faceNormals.resize( smDS->NbElements() );
3273 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3274 for ( int iF = 0; eIt->more(); ++iF )
3276 const SMDS_MeshElement* face = eIt->next();
3277 if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3278 eos._faceNormals[iF].SetCoord( 0,0,0 );
3281 if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3282 for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3283 eos._faceNormals[iF].Reverse();
3285 else // find EOS of adjacent FACEs
3287 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3288 while ( const TopoDS_Shape* face = fIt->next() )
3290 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3291 eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3292 if ( eos._faceEOS.back()->_shape.IsNull() )
3293 // avoid using uninitialised _shapeID in GetNormal()
3294 eos._faceEOS.back()->_shapeID = faceID;
3300 //================================================================================
3302 * \brief Returns normal of a face
3304 //================================================================================
3306 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3309 const _EdgesOnShape* eos = 0;
3311 if ( face->getshapeId() == _shapeID )
3317 for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3318 if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3319 eos = _faceEOS[ iF ];
3323 ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3325 norm = eos->_faceNormals[ face->getIdInShape() ];
3329 debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3330 << " on _shape #" << _shapeID );
3336 //================================================================================
3338 * \brief Set data of _LayerEdge needed for smoothing
3340 //================================================================================
3342 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
3344 SMESH_MesherHelper& helper,
3347 const SMDS_MeshNode* node = edge._nodes[0]; // source node
3350 edge._maxLen = Precision::Infinite();
3353 edge._curvature = 0;
3356 // --------------------------
3357 // Compute _normal and _cosin
3358 // --------------------------
3361 edge._lenFactor = 1.;
3362 edge._normal.SetCoord(0,0,0);
3363 _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3365 int totalNbFaces = 0;
3367 std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3371 const bool onShrinkShape = !eos._sWOL.IsNull();
3372 const bool useGeometry = (( eos._hyp.UseSurfaceNormal() ) ||
3373 ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3375 // get geom FACEs the node lies on
3376 //if ( useGeometry )
3378 set<TGeomID> faceIds;
3379 if ( eos.ShapeType() == TopAbs_FACE )
3381 faceIds.insert( eos._shapeID );
3385 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3386 while ( fIt->more() )
3387 faceIds.insert( fIt->next()->getshapeId() );
3389 set<TGeomID>::iterator id = faceIds.begin();
3390 for ( ; id != faceIds.end(); ++id )
3392 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3393 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3395 F = TopoDS::Face( s );
3396 face2Norm[ totalNbFaces ].first = F;
3404 bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3405 eos.SWOLType() == TopAbs_FACE &&
3408 if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3410 if ( eos.SWOLType() == TopAbs_EDGE )
3412 // inflate from VERTEX along EDGE
3413 edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3415 else if ( eos.ShapeType() == TopAbs_VERTEX )
3417 // inflate from VERTEX along FACE
3418 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3419 node, helper, normOK, &edge._cosin);
3423 // inflate from EDGE along FACE
3424 edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3425 node, helper, normOK);
3428 else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3431 face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3434 for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3436 F = face2Norm[ iF ].first;
3437 geomNorm = getFaceNormal( node, F, helper, normOK );
3438 if ( !normOK ) continue;
3441 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3443 face2Norm[ iF ].second = geomNorm.XYZ();
3444 edge._normal += geomNorm.XYZ();
3446 if ( nbOkNorms == 0 )
3447 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3449 if ( totalNbFaces >= 3 )
3451 edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3454 if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3456 // opposite normals, re-get normals at shifted positions (IPAL 52426)
3457 edge._normal.SetCoord( 0,0,0 );
3458 for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3460 const TopoDS_Face& F = face2Norm[iF].first;
3461 geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3462 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3465 face2Norm[ iF ].second = geomNorm.XYZ();
3466 edge._normal += face2Norm[ iF ].second;
3471 else // !useGeometry - get _normal using surrounding mesh faces
3473 edge._normal = getWeigthedNormal( &edge );
3475 // set<TGeomID> faceIds;
3477 // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3478 // while ( fIt->more() )
3480 // const SMDS_MeshElement* face = fIt->next();
3481 // if ( eos.GetNormal( face, geomNorm ))
3483 // if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3484 // continue; // use only one mesh face on FACE
3485 // edge._normal += geomNorm.XYZ();
3492 //if ( eos._hyp.UseSurfaceNormal() )
3494 switch ( eos.ShapeType() )
3501 TopoDS_Edge E = TopoDS::Edge( eos._shape );
3502 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3503 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3504 edge._cosin = Cos( angle );
3507 case TopAbs_VERTEX: {
3508 //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3510 TopoDS_Vertex V = TopoDS::Vertex( eos._shape );
3511 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3512 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
3513 edge._cosin = Cos( angle );
3514 if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3515 for ( int iF = totalNbFaces-2; iF >=0; --iF )
3517 F = face2Norm[ iF ].first;
3518 inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3520 double angle = inFaceDir.Angle( edge._normal );
3521 double cosin = Cos( angle );
3522 if ( Abs( cosin ) > Abs( edge._cosin ))
3523 edge._cosin = cosin;
3530 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3534 double normSize = edge._normal.SquareModulus();
3535 if ( normSize < numeric_limits<double>::min() )
3536 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3538 edge._normal /= sqrt( normSize );
3540 if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3542 getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3543 edge._nodes.resize( 1 );
3544 edge._normal.SetCoord( 0,0,0 );
3548 // Set the rest data
3549 // --------------------
3551 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3553 if ( onShrinkShape )
3555 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3556 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3557 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3559 // set initial position which is parameters on _sWOL in this case
3560 if ( eos.SWOLType() == TopAbs_EDGE )
3562 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3563 edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3564 if ( edge._nodes.size() > 1 )
3565 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3567 else // eos.SWOLType() == TopAbs_FACE
3569 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3570 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3571 if ( edge._nodes.size() > 1 )
3572 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3575 if ( edge._nodes.size() > 1 )
3577 // check if an angle between a FACE with layers and SWOL is sharp,
3578 // else the edge should not inflate
3580 for ( int iF = 0; iF < totalNbFaces && F.IsNull(); ++iF ) // find a FACE with VL
3581 if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3582 F = face2Norm[iF].first;
3585 geomNorm = getFaceNormal( node, F, helper, normOK );
3586 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3587 geomNorm.Reverse(); // inside the SOLID
3588 if ( geomNorm * edge._normal < -0.001 )
3590 getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3591 edge._nodes.resize( 1 );
3593 else if ( edge._lenFactor > 3 )
3595 edge._lenFactor = 2;
3596 edge.Set( _LayerEdge::RISKY_SWOL );
3603 edge._pos.push_back( SMESH_TNodeXYZ( node ));
3605 if ( eos.ShapeType() == TopAbs_FACE )
3608 for ( size_t i = 0; i < edge._simplices.size(); ++i )
3610 edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3611 edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3616 // Set neighbor nodes for a _LayerEdge based on EDGE
3618 if ( eos.ShapeType() == TopAbs_EDGE /*||
3619 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3621 edge._2neibors = new _2NearEdges;
3622 // target nodes instead of source ones will be set later
3628 //================================================================================
3630 * \brief Return normal to a FACE at a node
3631 * \param [in] n - node
3632 * \param [in] face - FACE
3633 * \param [in] helper - helper
3634 * \param [out] isOK - true or false
3635 * \param [in] shiftInside - to find normal at a position shifted inside the face
3636 * \return gp_XYZ - normal
3638 //================================================================================
3640 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3641 const TopoDS_Face& face,
3642 SMESH_MesherHelper& helper,
3649 // get a shifted position
3650 gp_Pnt p = SMESH_TNodeXYZ( node );
3651 gp_XYZ shift( 0,0,0 );
3652 TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3653 switch ( S.ShapeType() ) {
3656 shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3661 shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3669 p.Translate( shift * 1e-5 );
3671 TopLoc_Location loc;
3672 GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3674 if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3676 projector.Perform( p );
3677 if ( !projector.IsDone() || projector.NbPoints() < 1 )
3682 Quantity_Parameter U,V;
3683 projector.LowerDistanceParameters(U,V);
3688 uv = helper.GetNodeUV( face, node, 0, &isOK );
3694 Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3696 if ( !shiftInside &&
3697 helper.IsDegenShape( node->getshapeId() ) &&
3698 getFaceNormalAtSingularity( uv, face, helper, normal ))
3701 return normal.XYZ();
3704 int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3705 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3707 if ( pointKind == IMPOSSIBLE &&
3708 node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3710 // probably NormEstim() failed due to a too high tolerance
3711 pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3712 isOK = ( pointKind < IMPOSSIBLE );
3714 if ( pointKind < IMPOSSIBLE )
3716 if ( pointKind != REGULAR &&
3718 node->GetPosition()->GetDim() < 2 ) // FACE boundary
3720 gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3721 if ( normShift * normal.XYZ() < 0. )
3727 if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3729 const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3731 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3732 while ( fIt->more() )
3734 const SMDS_MeshElement* f = fIt->next();
3735 if ( f->getshapeId() == faceID )
3737 isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3740 TopoDS_Face ff = face;
3741 ff.Orientation( TopAbs_FORWARD );
3742 if ( helper.IsReversedSubMesh( ff ))
3749 return normal.XYZ();
3752 //================================================================================
3754 * \brief Try to get normal at a singularity of a surface basing on it's nature
3756 //================================================================================
3758 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY& uv,
3759 const TopoDS_Face& face,
3760 SMESH_MesherHelper& helper,
3763 BRepAdaptor_Surface surface( face );
3765 if ( !getRovolutionAxis( surface, axis ))
3768 double f,l, d, du, dv;
3769 f = surface.FirstUParameter();
3770 l = surface.LastUParameter();
3771 d = ( uv.X() - f ) / ( l - f );
3772 du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3773 f = surface.FirstVParameter();
3774 l = surface.LastVParameter();
3775 d = ( uv.Y() - f ) / ( l - f );
3776 dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3779 gp_Pnt2d testUV = uv;
3780 enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3782 Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3783 for ( int iLoop = 0; true ; ++iLoop )
3785 testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3786 if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3793 if ( axis * refDir < 0. )
3801 //================================================================================
3803 * \brief Return a normal at a node weighted with angles taken by faces
3805 //================================================================================
3807 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3809 const SMDS_MeshNode* n = edge->_nodes[0];
3811 gp_XYZ resNorm(0,0,0);
3812 SMESH_TNodeXYZ p0( n ), pP, pN;
3813 for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3815 pP.Set( edge->_simplices[i]._nPrev );
3816 pN.Set( edge->_simplices[i]._nNext );
3817 gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3818 double l0P = v0P.SquareMagnitude();
3819 double l0N = v0N.SquareMagnitude();
3820 double lPN = vPN.SquareMagnitude();
3821 if ( l0P < std::numeric_limits<double>::min() ||
3822 l0N < std::numeric_limits<double>::min() ||
3823 lPN < std::numeric_limits<double>::min() )
3825 double lNorm = norm.SquareMagnitude();
3826 double sin2 = lNorm / l0P / l0N;
3827 double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3829 double weight = sin2 * angle / lPN;
3830 resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3836 //================================================================================
3838 * \brief Return a normal at a node by getting a common point of offset planes
3839 * defined by the FACE normals
3841 //================================================================================
3843 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge* edge,
3844 std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3848 SMESH_TNodeXYZ p0 = edge->_nodes[0];
3850 gp_XYZ resNorm(0,0,0);
3851 TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3852 if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3854 for ( int i = 0; i < nbFaces; ++i )
3855 resNorm += f2Normal[i].second;
3859 // prepare _OffsetPlane's
3860 vector< _OffsetPlane > pln( nbFaces );
3861 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3863 pln[i]._faceIndex = i;
3864 pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3868 pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3869 pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3872 // intersect neighboring OffsetPlane's
3873 PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3874 while ( const TopoDS_Shape* edge = edgeIt->next() )
3876 int f1 = -1, f2 = -1;
3877 for ( int i = 0; i < nbFaces && f2 < 0; ++i )
3878 if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3879 (( f1 < 0 ) ? f1 : f2 ) = i;
3882 pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3885 // get a common point
3886 gp_XYZ commonPnt( 0, 0, 0 );
3889 for ( int i = 0; i < nbFaces; ++i )
3891 commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3892 nbPoints += isPointFound;
3894 gp_XYZ wgtNorm = getWeigthedNormal( edge );
3895 if ( nbPoints == 0 )
3898 commonPnt /= nbPoints;
3899 resNorm = commonPnt - p0;
3903 // choose the best among resNorm and wgtNorm
3904 resNorm.Normalize();
3905 wgtNorm.Normalize();
3906 double resMinDot = std::numeric_limits<double>::max();
3907 double wgtMinDot = std::numeric_limits<double>::max();
3908 for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3910 resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3911 wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3914 if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3916 edge->Set( _LayerEdge::MULTI_NORMAL );
3919 return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3922 //================================================================================
3924 * \brief Compute line of intersection of 2 planes
3926 //================================================================================
3928 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln,
3929 const TopoDS_Edge& E,
3930 const TopoDS_Vertex& V )
3932 int iNext = bool( _faceIndexNext[0] >= 0 );
3933 _faceIndexNext[ iNext ] = pln._faceIndex;
3935 gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3936 gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3938 gp_XYZ lineDir = n1 ^ n2;
3940 double x = Abs( lineDir.X() );
3941 double y = Abs( lineDir.Y() );
3942 double z = Abs( lineDir.Z() );
3944 int cooMax; // max coordinate
3946 if (x > z) cooMax = 1;
3950 if (y > z) cooMax = 2;
3955 if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3957 // parallel planes - intersection is an offset of the common EDGE
3958 gp_Pnt p = BRep_Tool::Pnt( V );
3959 linePos = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3960 lineDir = getEdgeDir( E, V );
3964 // the constants in the 2 plane equations
3965 double d1 = - ( _plane.Axis().Direction().XYZ() * _plane.Location().XYZ() );
3966 double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3971 linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3972 linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3975 linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3977 linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3980 linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3981 linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3985 gp_Lin& line = _lines[ iNext ];
3986 line.SetDirection( lineDir );
3987 line.SetLocation ( linePos );
3989 _isLineOK[ iNext ] = true;
3992 iNext = bool( pln._faceIndexNext[0] >= 0 );
3993 pln._lines [ iNext ] = line;
3994 pln._faceIndexNext[ iNext ] = this->_faceIndex;
3995 pln._isLineOK [ iNext ] = true;
3998 //================================================================================
4000 * \brief Computes intersection point of two _lines
4002 //================================================================================
4004 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound,
4005 const TopoDS_Vertex & V) const
4010 if ( NbLines() == 2 )
4012 gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4013 double dot01 = lPerp0 * _lines[1].Direction().XYZ();
4014 if ( Abs( dot01 ) > 0.05 )
4016 gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4017 double u1 = - ( lPerp0 * l0l1 ) / dot01;
4018 p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4023 gp_Pnt pV ( BRep_Tool::Pnt( V ));
4024 gp_Vec lv0( _lines[0].Location(), pV ), lv1(_lines[1].Location(), pV );
4025 double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4026 p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4027 p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4035 //================================================================================
4037 * \brief Find 2 neigbor nodes of a node on EDGE
4039 //================================================================================
4041 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
4042 const SMDS_MeshNode*& n1,
4043 const SMDS_MeshNode*& n2,
4047 const SMDS_MeshNode* node = edge->_nodes[0];
4048 const int shapeInd = eos._shapeID;
4049 SMESHDS_SubMesh* edgeSM = 0;
4050 if ( eos.ShapeType() == TopAbs_EDGE )
4052 edgeSM = eos._subMesh->GetSubMeshDS();
4053 if ( !edgeSM || edgeSM->NbElements() == 0 )
4054 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4058 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4059 while ( eIt->more() && !n2 )
4061 const SMDS_MeshElement* e = eIt->next();
4062 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
4063 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4066 if (!edgeSM->Contains(e)) continue;
4070 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4071 if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4073 ( iN++ ? n2 : n1 ) = nNeibor;
4076 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4080 //================================================================================
4082 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4084 //================================================================================
4086 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4087 const SMDS_MeshNode* n2,
4088 const _EdgesOnShape& eos,
4089 SMESH_MesherHelper& helper)
4091 if ( eos.ShapeType() != TopAbs_EDGE )
4094 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
4095 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4096 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4100 double sumLen = vec1.Modulus() + vec2.Modulus();
4101 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4102 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4103 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4104 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4105 if ( _curvature ) delete _curvature;
4106 _curvature = _Curvature::New( avgNormProj, avgLen );
4107 // if ( _curvature )
4108 // debugMsg( _nodes[0]->GetID()
4109 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4110 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4111 // << _curvature->lenDelta(0) );
4115 if ( eos._sWOL.IsNull() )
4117 TopoDS_Edge E = TopoDS::Edge( eos._shape );
4118 // if ( SMESH_Algo::isDegenerated( E ))
4120 gp_XYZ dirE = getEdgeDir( E, _nodes[0], helper );
4121 gp_XYZ plnNorm = dirE ^ _normal;
4122 double proj0 = plnNorm * vec1;
4123 double proj1 = plnNorm * vec2;
4124 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4126 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4127 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4132 //================================================================================
4134 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4135 * this and other _LayerEdge's are inflated along a FACE or an EDGE
4137 //================================================================================
4139 gp_XYZ _LayerEdge::Copy( _LayerEdge& other,
4141 SMESH_MesherHelper& helper )
4143 _nodes = other._nodes;
4144 _normal = other._normal;
4146 _lenFactor = other._lenFactor;
4147 _cosin = other._cosin;
4148 _2neibors = other._2neibors;
4149 _curvature = 0; std::swap( _curvature, other._curvature );
4150 _2neibors = 0; std::swap( _2neibors, other._2neibors );
4152 gp_XYZ lastPos( 0,0,0 );
4153 if ( eos.SWOLType() == TopAbs_EDGE )
4155 double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4156 _pos.push_back( gp_XYZ( u, 0, 0));
4158 u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4163 gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4164 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4166 uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4167 lastPos.SetX( uv.X() );
4168 lastPos.SetY( uv.Y() );
4173 //================================================================================
4175 * \brief Set _cosin and _lenFactor
4177 //================================================================================
4179 void _LayerEdge::SetCosin( double cosin )
4182 cosin = Abs( _cosin );
4183 //_lenFactor = ( cosin < 1.-1e-12 ) ? Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4184 _lenFactor = ( cosin < 1.-1e-12 ) ? 1./sqrt(1-cosin*cosin ) : 1.0;
4187 //================================================================================
4189 * \brief Check if another _LayerEdge is a neighbor on EDGE
4191 //================================================================================
4193 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4195 return (( this->_2neibors && this->_2neibors->include( edge )) ||
4196 ( edge->_2neibors && edge->_2neibors->include( this )));
4199 //================================================================================
4201 * \brief Fills a vector<_Simplex >
4203 //================================================================================
4205 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4206 vector<_Simplex>& simplices,
4207 const set<TGeomID>& ingnoreShapes,
4208 const _SolidData* dataToCheckOri,
4212 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4213 while ( fIt->more() )
4215 const SMDS_MeshElement* f = fIt->next();
4216 const TGeomID shapeInd = f->getshapeId();
4217 if ( ingnoreShapes.count( shapeInd )) continue;
4218 const int nbNodes = f->NbCornerNodes();
4219 const int srcInd = f->GetNodeIndex( node );
4220 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4221 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4222 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4223 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4224 std::swap( nPrev, nNext );
4225 simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4229 SortSimplices( simplices );
4232 //================================================================================
4234 * \brief Set neighbor simplices side by side
4236 //================================================================================
4238 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4240 vector<_Simplex> sortedSimplices( simplices.size() );
4241 sortedSimplices[0] = simplices[0];
4243 for ( size_t i = 1; i < simplices.size(); ++i )
4245 for ( size_t j = 1; j < simplices.size(); ++j )
4246 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4248 sortedSimplices[i] = simplices[j];
4253 if ( nbFound == simplices.size() - 1 )
4254 simplices.swap( sortedSimplices );
4257 //================================================================================
4259 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4261 //================================================================================
4263 void _ViscousBuilder::makeGroupOfLE()
4266 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4268 if ( _sdVec[i]._n2eMap.empty() ) continue;
4270 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4271 TNode2Edge::iterator n2e;
4272 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4274 _LayerEdge* le = n2e->second;
4275 // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4276 // dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4277 // << ", " << le->_nodes[iN]->GetID() <<"])");
4279 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4280 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4285 dumpFunction( SMESH_Comment("makeNormals") << i );
4286 for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4288 _LayerEdge* edge = n2e->second;
4289 SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4290 nXYZ += edge->_normal * _sdVec[i]._stepSize;
4291 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4292 << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4296 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4297 dumpCmd( "faceId1 = mesh.NbElements()" );
4298 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4299 for ( ; fExp.More(); fExp.Next() )
4301 if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4303 if ( sm->NbElements() == 0 ) continue;
4304 SMDS_ElemIteratorPtr fIt = sm->GetElements();
4305 while ( fIt->more())
4307 const SMDS_MeshElement* e = fIt->next();
4308 SMESH_Comment cmd("mesh.AddFace([");
4309 for ( int j = 0; j < e->NbCornerNodes(); ++j )
4310 cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4315 dumpCmd( "faceId2 = mesh.NbElements()" );
4316 dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4317 << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4318 << "'%s-%s' % (faceId1+1, faceId2))");
4324 //================================================================================
4326 * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4328 //================================================================================
4330 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4332 data._geomSize = Precision::Infinite();
4333 double intersecDist;
4334 const SMDS_MeshElement* face;
4335 SMESH_MesherHelper helper( *_mesh );
4337 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4338 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4339 data._proxyMesh->GetFaces( data._solid )));
4341 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4343 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4344 if ( eos._edges.empty() )
4346 // get neighbor faces intersection with which should not be considered since
4347 // collisions are avoided by means of smoothing
4348 set< TGeomID > neighborFaces;
4349 if ( eos._hyp.ToSmooth() )
4351 SMESH_subMeshIteratorPtr subIt =
4352 eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4353 while ( subIt->more() )
4355 SMESH_subMesh* sm = subIt->next();
4356 PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4357 while ( const TopoDS_Shape* face = fIt->next() )
4358 neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4361 // find intersections
4362 double thinkness = eos._hyp.GetTotalThickness();
4363 for ( size_t i = 0; i < eos._edges.size(); ++i )
4365 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4366 eos._edges[i]->_maxLen = thinkness;
4367 eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4368 if ( intersecDist > 0 && face )
4370 data._geomSize = Min( data._geomSize, intersecDist );
4371 if ( !neighborFaces.count( face->getshapeId() ))
4372 eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4378 //================================================================================
4380 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4382 //================================================================================
4384 bool _ViscousBuilder::inflate(_SolidData& data)
4386 SMESH_MesherHelper helper( *_mesh );
4388 // Limit inflation step size by geometry size found by itersecting
4389 // normals of _LayerEdge's with mesh faces
4390 if ( data._stepSize > 0.3 * data._geomSize )
4391 limitStepSize( data, 0.3 * data._geomSize );
4393 const double tgtThick = data._maxThickness;
4394 if ( data._stepSize > data._minThickness )
4395 limitStepSize( data, data._minThickness );
4397 if ( data._stepSize < 1. )
4398 data._epsilon = data._stepSize * 1e-7;
4400 debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4402 findCollisionEdges( data, helper );
4404 limitMaxLenByCurvature( data, helper );
4406 // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4407 for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4408 if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4409 data._edgesOnShape[i]._edges.size() > 0 &&
4410 data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4412 data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4413 data._edgesOnShape[i]._edges[0]->Block( data );
4416 const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4418 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4419 int nbSteps = 0, nbRepeats = 0;
4420 while ( avgThick < 0.99 )
4422 // new target length
4423 double prevThick = curThick;
4424 curThick += data._stepSize;
4425 if ( curThick > tgtThick )
4427 curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4431 double stepSize = curThick - prevThick;
4432 updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4434 // Elongate _LayerEdge's
4435 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4436 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4438 _EdgesOnShape& eos = data._edgesOnShape[iS];
4439 if ( eos._edges.empty() ) continue;
4441 const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4442 for ( size_t i = 0; i < eos._edges.size(); ++i )
4444 eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4449 if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4452 // Improve and check quality
4453 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4457 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4458 debugMsg("NOT INVALIDATED STEP!");
4459 return error("Smoothing failed", data._index);
4461 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4462 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4464 _EdgesOnShape& eos = data._edgesOnShape[iS];
4465 for ( size_t i = 0; i < eos._edges.size(); ++i )
4466 eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4470 break; // no more inflating possible
4474 // Evaluate achieved thickness
4476 int nbActiveEdges = 0;
4477 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4479 _EdgesOnShape& eos = data._edgesOnShape[iS];
4480 if ( eos._edges.empty() ) continue;
4482 const double shapeTgtThick = eos._hyp.GetTotalThickness();
4483 for ( size_t i = 0; i < eos._edges.size(); ++i )
4485 avgThick += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4486 nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4489 avgThick /= data._n2eMap.size();
4490 debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4492 #ifdef BLOCK_INFLATION
4493 if ( nbActiveEdges == 0 )
4495 debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4499 if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4501 debugMsg( "-- Stop inflation since "
4502 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4503 << tgtThick * avgThick << " ) * " << safeFactor );
4508 limitStepSize( data, 0.25 * distToIntersection );
4509 if ( data._stepSizeNodes[0] )
4510 data._stepSize = data._stepSizeCoeff *
4511 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4513 } // while ( avgThick < 0.99 )
4516 return error("failed at the very first inflation step", data._index);
4518 if ( avgThick < 0.99 )
4520 if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4522 data._proxyMesh->_warning.reset
4523 ( new SMESH_ComputeError (COMPERR_WARNING,
4524 SMESH_Comment("Thickness ") << tgtThick <<
4525 " of viscous layers not reached,"
4526 " average reached thickness is " << avgThick*tgtThick));
4530 // Restore position of src nodes moved by inflation on _noShrinkShapes
4531 dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4532 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4534 _EdgesOnShape& eos = data._edgesOnShape[iS];
4535 if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4536 for ( size_t i = 0; i < eos._edges.size(); ++i )
4538 restoreNoShrink( *eos._edges[ i ] );
4543 return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4546 //================================================================================
4548 * \brief Improve quality of layer inner surface and check intersection
4550 //================================================================================
4552 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4554 double & distToIntersection)
4556 if ( data._nbShapesToSmooth == 0 )
4557 return true; // no shapes needing smoothing
4559 bool moved, improved;
4561 vector< _LayerEdge* > movedEdges, badEdges;
4562 vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4563 vector< bool > isConcaveFace;
4565 SMESH_MesherHelper helper(*_mesh);
4566 Handle(ShapeAnalysis_Surface) surface;
4569 for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4571 const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4573 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4575 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4576 if ( !eos._toSmooth ||
4577 eos.ShapeType() != shapeType ||
4578 eos._edges.empty() )
4581 // already smoothed?
4582 // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4583 // if ( !toSmooth ) continue;
4585 if ( !eos._hyp.ToSmooth() )
4587 // smooth disabled by the user; check validy only
4588 if ( !isFace ) continue;
4590 for ( size_t i = 0; i < eos._edges.size(); ++i )
4592 _LayerEdge* edge = eos._edges[i];
4593 for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4594 if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4596 // debugMsg( "-- Stop inflation. Bad simplex ("
4597 // << " "<< edge->_nodes[0]->GetID()
4598 // << " "<< edge->_nodes.back()->GetID()
4599 // << " "<< edge->_simplices[iF]._nPrev->GetID()
4600 // << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4602 badEdges.push_back( edge );
4605 if ( !badEdges.empty() )
4609 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4613 continue; // goto the next EDGE or FACE
4617 if ( eos.SWOLType() == TopAbs_FACE )
4619 if ( !F.IsSame( eos._sWOL )) {
4620 F = TopoDS::Face( eos._sWOL );
4621 helper.SetSubShape( F );
4622 surface = helper.GetSurface( F );
4627 F.Nullify(); surface.Nullify();
4629 const TGeomID sInd = eos._shapeID;
4631 // perform smoothing
4633 if ( eos.ShapeType() == TopAbs_EDGE )
4635 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4637 if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4639 // smooth on EDGE's (normally we should not get here)
4643 for ( size_t i = 0; i < eos._edges.size(); ++i )
4645 moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4647 dumpCmd( SMESH_Comment("# end step ")<<step);
4649 while ( moved && step++ < 5 );
4654 else // smooth on FACE
4657 eosC1.push_back( & eos );
4658 eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4661 isConcaveFace.resize( eosC1.size() );
4662 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4664 isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID );
4665 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4666 for ( size_t i = 0; i < edges.size(); ++i )
4667 if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4668 edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4669 movedEdges.push_back( edges[i] );
4671 makeOffsetSurface( *eosC1[ iEOS ], helper );
4674 int step = 0, stepLimit = 5, nbBad = 0;
4675 while (( ++step <= stepLimit ) || improved )
4677 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4678 <<"_InfStep"<<infStep<<"_"<<step); // debug
4679 int oldBadNb = nbBad;
4682 #ifdef INCREMENTAL_SMOOTH
4683 bool findBest = false; // ( step == stepLimit );
4684 for ( size_t i = 0; i < movedEdges.size(); ++i )
4686 movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4687 if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4688 badEdges.push_back( movedEdges[i] );
4691 bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4692 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4694 vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4695 for ( size_t i = 0; i < edges.size(); ++i )
4697 edges[i]->Unset( _LayerEdge::SMOOTHED );
4698 if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4699 badEdges.push_back( eos._edges[i] );
4703 nbBad = badEdges.size();
4706 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4708 if ( !badEdges.empty() && step >= stepLimit / 2 )
4710 if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4713 // resolve hard smoothing situation around concave VERTEXes
4714 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4716 vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4717 for ( size_t i = 0; i < eosCoVe.size(); ++i )
4718 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4721 // look for the best smooth of _LayerEdge's neighboring badEdges
4723 for ( size_t i = 0; i < badEdges.size(); ++i )
4725 _LayerEdge* ledge = badEdges[i];
4726 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4728 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4729 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4731 ledge->Unset( _LayerEdge::SMOOTHED );
4732 nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4734 debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4737 if ( nbBad == oldBadNb &&
4739 step < stepLimit ) // smooth w/o chech of validity
4742 dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4743 <<"_InfStep"<<infStep<<"_"<<step); // debug
4744 for ( size_t i = 0; i < movedEdges.size(); ++i )
4746 movedEdges[i]->SmoothWoCheck();
4748 if ( stepLimit < 9 )
4752 improved = ( nbBad < oldBadNb );
4756 if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4757 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4759 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4762 } // smoothing steps
4764 // project -- to prevent intersections or fix bad simplices
4765 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4767 if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4768 putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4771 //if ( !badEdges.empty() )
4774 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4776 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4778 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4780 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4781 edge->CheckNeiborsOnBoundary( & badEdges );
4782 if (( nbBad > 0 ) ||
4783 ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4785 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4786 gp_XYZ prevXYZ = edge->PrevCheckPos();
4787 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4788 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4790 debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4791 << " "<< tgtXYZ._node->GetID()
4792 << " "<< edge->_simplices[j]._nPrev->GetID()
4793 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4794 badEdges.push_back( edge );
4801 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4802 nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4808 } // // smooth on FACE's
4810 } // smooth on [ EDGEs, FACEs ]
4812 // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4814 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4816 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4817 if ( eos.ShapeType() == TopAbs_FACE ||
4818 eos._edges.empty() ||
4819 !eos._sWOL.IsNull() )
4823 for ( size_t i = 0; i < eos._edges.size(); ++i )
4825 _LayerEdge* edge = eos._edges[i];
4826 if ( edge->_nodes.size() < 2 ) continue;
4827 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4828 gp_XYZ prevXYZ = edge->PrevCheckPos( &eos );
4829 //const gp_XYZ& prevXYZ = edge->PrevPos();
4830 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4831 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4833 debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4834 << " "<< tgtXYZ._node->GetID()
4835 << " "<< edge->_simplices[j]._nPrev->GetID()
4836 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4837 badEdges.push_back( edge );
4842 // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4844 int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4850 // Check if the last segments of _LayerEdge intersects 2D elements;
4851 // checked elements are either temporary faces or faces on surfaces w/o the layers
4853 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4854 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4855 data._proxyMesh->GetFaces( data._solid )) );
4857 #ifdef BLOCK_INFLATION
4858 const bool toBlockInfaltion = true;
4860 const bool toBlockInfaltion = false;
4862 distToIntersection = Precision::Infinite();
4864 const SMDS_MeshElement* intFace = 0;
4865 const SMDS_MeshElement* closestFace = 0;
4867 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4869 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4870 if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4872 for ( size_t i = 0; i < eos._edges.size(); ++i )
4874 if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4875 eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4877 if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4880 // commented due to "Illegal hash-positionPosition" error in NETGEN
4881 // on Debian60 on viscous_layers_01/B2 case
4882 // Collision; try to deflate _LayerEdge's causing it
4883 // badEdges.clear();
4884 // badEdges.push_back( eos._edges[i] );
4885 // eosC1[0] = & eos;
4886 // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4890 // badEdges.clear();
4891 // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4893 // if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4895 // const SMDS_MeshElement* srcFace =
4896 // eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4897 // SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4898 // while ( nIt->more() )
4900 // const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4901 // TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4902 // if ( n2e != data._n2eMap.end() )
4903 // badEdges.push_back( n2e->second );
4906 // nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4911 // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4918 SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4923 const bool isShorterDist = ( distToIntersection > dist );
4924 if ( toBlockInfaltion || isShorterDist )
4926 // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4927 // lying on this _ConvexFace
4928 if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4929 if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4932 // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4933 // ( avoid limiting the thickness on the case of issue 22576)
4934 if ( intFace->getshapeId() == eos._shapeID )
4937 // ignore intersection with intFace of an adjacent FACE
4940 bool toIgnore = false;
4941 if ( eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4943 const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4944 if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4946 TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4947 for ( ; !toIgnore && edge.More(); edge.Next() )
4948 // is adjacent - has a common EDGE
4949 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4951 if ( toIgnore ) // check angle between normals
4954 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4955 toIgnore = ( normal * eos._edges[i]->_normal > -0.5 );
4959 if ( !toIgnore ) // check if the edge is a neighbor of intFace
4961 for ( size_t iN = 0; !toIgnore && iN < eos._edges[i]->_neibors.size(); ++iN )
4963 int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4964 toIgnore = ( nInd >= 0 );
4971 // intersection not ignored
4973 if ( toBlockInfaltion &&
4974 dist < ( eos._edges[i]->_len * theThickToIntersection ))
4976 eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4977 eos._edges[i]->Block( data ); // not to inflate
4979 if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4981 // block _LayerEdge's, on top of which intFace is
4982 if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4984 const SMDS_MeshElement* srcFace =
4985 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4986 SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4987 while ( nIt->more() )
4989 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4990 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4991 if ( n2e != data._n2eMap.end() )
4992 n2e->second->Block( data );
4998 if ( isShorterDist )
5000 distToIntersection = dist;
5002 closestFace = intFace;
5005 } // if ( toBlockInfaltion || isShorterDist )
5006 } // loop on eos._edges
5007 } // loop on data._edgesOnShape
5009 if ( closestFace && le )
5012 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5013 cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5014 << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5015 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5016 << ") distance = " << distToIntersection<< endl;
5023 //================================================================================
5025 * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5026 * \param [in,out] badSmooEdges - _LayerEdge's to fix
5027 * \return int - resulting nb of bad _LayerEdge's
5029 //================================================================================
5031 int _ViscousBuilder::invalidateBadSmooth( _SolidData& data,
5032 SMESH_MesherHelper& helper,
5033 vector< _LayerEdge* >& badSmooEdges,
5034 vector< _EdgesOnShape* >& eosC1,
5037 if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5039 dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5042 INVALIDATED = _LayerEdge::UNUSED_FLAG,
5043 TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5044 ADDED = _LayerEdge::UNUSED_FLAG * 4
5046 data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5049 bool haveInvalidated = true;
5050 while ( haveInvalidated )
5052 haveInvalidated = false;
5053 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5055 _LayerEdge* edge = badSmooEdges[i];
5056 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5058 bool invalidated = false;
5059 if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5061 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5062 edge->Block( data );
5063 edge->Set( INVALIDATED );
5064 edge->Unset( TO_INVALIDATE );
5066 haveInvalidated = true;
5069 // look for _LayerEdge's of bad _simplices
5071 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5072 gp_XYZ prevXYZ1 = edge->PrevCheckPos( eos );
5073 //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5074 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5076 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5077 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5081 _LayerEdge* ee[2] = { 0,0 };
5082 for ( size_t iN = 0; iN < edge->_neibors.size() && !ee[1] ; ++iN )
5083 if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5084 ee[ ee[0] != 0 ] = edge->_neibors[iN];
5086 int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5087 while ( maxNbSteps > edge->NbSteps() && isBad )
5090 for ( int iE = 0; iE < 2; ++iE )
5092 if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5093 ee[ iE ]->NbSteps() > 1 )
5095 _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5096 ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5097 ee[ iE ]->Block( data );
5098 ee[ iE ]->Set( INVALIDATED );
5099 haveInvalidated = true;
5102 if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5103 ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5107 if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5108 if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5109 ee[0]->Set( ADDED );
5110 ee[1]->Set( ADDED );
5113 ee[0]->Set( TO_INVALIDATE );
5114 ee[1]->Set( TO_INVALIDATE );
5118 if ( !invalidated && nbBad > 0 && edge->NbSteps() > 1 )
5120 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5121 edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5122 edge->Block( data );
5123 edge->Set( INVALIDATED );
5124 edge->Unset( TO_INVALIDATE );
5125 haveInvalidated = true;
5127 } // loop on badSmooEdges
5128 } // while ( haveInvalidated )
5130 // re-smooth on analytical EDGEs
5131 for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5133 _LayerEdge* edge = badSmooEdges[i];
5134 if ( !edge->Is( INVALIDATED )) continue;
5136 _EdgesOnShape* eos = data.GetShapeEdges( edge );
5137 if ( eos->ShapeType() == TopAbs_VERTEX )
5139 PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5140 while ( const TopoDS_Shape* e = eIt->next() )
5141 if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5142 if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5144 // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5145 // if ( eoe->SWOLType() == TopAbs_FACE ) {
5146 // F = TopoDS::Face( eoe->_sWOL );
5147 // surface = helper.GetSurface( F );
5149 // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5150 eoe->_edgeSmoother->_anaCurve.Nullify();
5156 // check result of invalidation
5159 for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5161 for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5163 if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5164 _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5165 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5166 gp_XYZ prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5167 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5168 if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5171 debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5172 << " "<< tgtXYZ._node->GetID()
5173 << " "<< edge->_simplices[j]._nPrev->GetID()
5174 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5183 //================================================================================
5185 * \brief Create an offset surface
5187 //================================================================================
5189 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5191 if ( eos._offsetSurf.IsNull() ||
5192 eos._edgeForOffset == 0 ||
5193 eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5196 Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5199 gp_Pnt tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5200 /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5201 double offset = baseSurface->Gap();
5203 eos._offsetSurf.Nullify();
5207 BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5208 if ( !offsetMaker.IsDone() ) return;
5210 TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5211 if ( !fExp.More() ) return;
5213 TopoDS_Face F = TopoDS::Face( fExp.Current() );
5214 Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5215 if ( surf.IsNull() ) return;
5217 eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5219 catch ( Standard_Failure )
5224 //================================================================================
5226 * \brief Put nodes of a curved FACE to its offset surface
5228 //================================================================================
5230 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5232 vector< _EdgesOnShape* >& eosC1,
5236 _EdgesOnShape * eof = & eos;
5237 if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5240 for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5242 if ( eosC1[i]->_offsetSurf.IsNull() ||
5243 eosC1[i]->ShapeType() != TopAbs_FACE ||
5244 eosC1[i]->_edgeForOffset == 0 ||
5245 eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5247 if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5252 eof->_offsetSurf.IsNull() ||
5253 eof->ShapeType() != TopAbs_FACE ||
5254 eof->_edgeForOffset == 0 ||
5255 eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5258 double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5259 for ( size_t i = 0; i < eos._edges.size(); ++i )
5261 _LayerEdge* edge = eos._edges[i];
5262 edge->Unset( _LayerEdge::MARKED );
5263 if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5265 if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5268 int nbBlockedAround = 0;
5269 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5270 nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5271 if ( nbBlockedAround > 1 )
5274 gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5275 gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5276 if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5277 edge->_curvature->_uv = uv;
5278 if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5280 gp_XYZ newP = eof->_offsetSurf->Value( uv ).XYZ();
5281 gp_XYZ prevP = edge->PrevCheckPos();
5284 for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5286 ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5290 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5291 n->setXYZ( newP.X(), newP.Y(), newP.Z());
5292 edge->_pos.back() = newP;
5294 edge->Set( _LayerEdge::MARKED );
5299 // dumpMove() for debug
5301 for ( ; i < eos._edges.size(); ++i )
5302 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5304 if ( i < eos._edges.size() )
5306 dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5307 << "_InfStep" << infStep << "_" << smooStep );
5308 for ( ; i < eos._edges.size(); ++i )
5310 if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5311 dumpMove( eos._edges[i]->_nodes.back() );
5318 //================================================================================
5320 * \brief Return a curve of the EDGE to be used for smoothing and arrange
5321 * _LayerEdge's to be in a consequent order
5323 //================================================================================
5325 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge& E,
5327 SMESH_MesherHelper& helper)
5329 SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5331 TopLoc_Location loc; double f,l;
5333 Handle(Geom_Line) line;
5334 Handle(Geom_Circle) circle;
5335 bool isLine, isCirc;
5336 if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5338 // check if the EDGE is a line
5339 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5340 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5341 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5343 line = Handle(Geom_Line)::DownCast( curve );
5344 circle = Handle(Geom_Circle)::DownCast( curve );
5345 isLine = (!line.IsNull());
5346 isCirc = (!circle.IsNull());
5348 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5350 isLine = SMESH_Algo::IsStraight( E );
5353 line = new Geom_Line( gp::OX() ); // only type does matter
5355 if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5360 else //////////////////////////////////////////////////////////////////////// 2D case
5362 if ( !eos._isRegularSWOL ) // 23190
5365 const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5367 // check if the EDGE is a line
5368 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5369 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5370 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5372 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
5373 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5374 isLine = (!line2d.IsNull());
5375 isCirc = (!circle2d.IsNull());
5377 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5380 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5381 while ( nIt->more() )
5382 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5383 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5385 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5386 for ( int i = 0; i < 2 && !isLine; ++i )
5387 isLine = ( size.Coord( i+1 ) <= lineTol );
5389 if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5395 line = new Geom_Line( gp::OX() ); // only type does matter
5399 gp_Pnt2d p = circle2d->Location();
5400 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5401 circle = new Geom_Circle( ax, 1.); // only center position does matter
5410 return Handle(Geom_Curve)();
5413 //================================================================================
5415 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5417 //================================================================================
5419 bool _Smoother1D::smoothAnalyticEdge( _SolidData& data,
5420 Handle(ShapeAnalysis_Surface)& surface,
5421 const TopoDS_Face& F,
5422 SMESH_MesherHelper& helper)
5424 if ( !isAnalytic() ) return false;
5426 const size_t iFrom = 0, iTo = _eos._edges.size();
5428 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5430 if ( F.IsNull() ) // 3D
5432 SMESH_TNodeXYZ p0 ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5433 SMESH_TNodeXYZ p1 ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5434 SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5435 SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5436 gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5437 _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5438 _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5439 bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5440 vLE0->Is( _LayerEdge::BLOCKED ) ||
5441 vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5442 vLE1->Is( _LayerEdge::BLOCKED ));
5443 for ( size_t i = iFrom; i < iTo; ++i )
5445 _LayerEdge* edge = _eos._edges[i];
5446 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5447 newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5449 if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5451 gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5452 double shift = ( lineDir * ( newPos - pSrc0 ) -
5453 lineDir * ( curPos - pSrc0 ));
5454 newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5456 if ( edge->Is( _LayerEdge::BLOCKED ))
5458 SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5459 double curThick = pSrc.SquareDistance( tgtNode );
5460 double newThink = ( pSrc - newPos ).SquareModulus();
5461 if ( newThink > curThick )
5464 edge->_pos.back() = newPos;
5465 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5466 dumpMove( tgtNode );
5471 _LayerEdge* e0 = getLEdgeOnV( 0 );
5472 _LayerEdge* e1 = getLEdgeOnV( 1 );
5473 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5474 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5475 if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5477 int iPeriodic = helper.GetPeriodicIndex();
5478 if ( iPeriodic == 1 || iPeriodic == 2 )
5480 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5481 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5482 std::swap( uv0, uv1 );
5485 const gp_XY rangeUV = uv1 - uv0;
5486 for ( size_t i = iFrom; i < iTo; ++i )
5488 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5489 gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5490 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5492 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5493 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5494 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5495 dumpMove( tgtNode );
5497 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5498 pos->SetUParameter( newUV.X() );
5499 pos->SetVParameter( newUV.Y() );
5505 if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5507 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5508 gp_Pnt center3D = circle->Location();
5510 if ( F.IsNull() ) // 3D
5512 if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5513 return true; // closed EDGE - nothing to do
5515 // circle is a real curve of EDGE
5516 gp_Circ circ = circle->Circ();
5518 // new center is shifted along its axis
5519 const gp_Dir& axis = circ.Axis().Direction();
5520 _LayerEdge* e0 = getLEdgeOnV(0);
5521 _LayerEdge* e1 = getLEdgeOnV(1);
5522 SMESH_TNodeXYZ p0 = e0->_nodes.back();
5523 SMESH_TNodeXYZ p1 = e1->_nodes.back();
5524 double shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5525 double shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5526 gp_Pnt newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5528 double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5530 gp_Ax2 newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5531 gp_Circ newCirc( newAxis, newRadius );
5532 gp_Vec vecC1 ( newCenter, p1 );
5534 double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5538 for ( size_t i = iFrom; i < iTo; ++i )
5540 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5541 double u = uLast * _leParams[i];
5542 gp_Pnt p = ElCLib::Value( u, newCirc );
5543 _eos._edges[i]->_pos.back() = p.XYZ();
5545 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5546 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5547 dumpMove( tgtNode );
5553 const gp_XY center( center3D.X(), center3D.Y() );
5555 _LayerEdge* e0 = getLEdgeOnV(0);
5556 _LayerEdge* eM = _eos._edges[ 0 ];
5557 _LayerEdge* e1 = getLEdgeOnV(1);
5558 gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5559 gp_XY uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5560 gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5561 gp_Vec2d vec0( center, uv0 );
5562 gp_Vec2d vecM( center, uvM );
5563 gp_Vec2d vec1( center, uv1 );
5564 double uLast = vec0.Angle( vec1 ); // -PI - +PI
5565 double uMidl = vec0.Angle( vecM );
5566 if ( uLast * uMidl <= 0. )
5567 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5568 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5570 gp_Ax2d axis( center, vec0 );
5571 gp_Circ2d circ( axis, radius );
5572 for ( size_t i = iFrom; i < iTo; ++i )
5574 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5575 double newU = uLast * _leParams[i];
5576 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5577 _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5579 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5580 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5581 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5582 dumpMove( tgtNode );
5584 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5585 pos->SetUParameter( newUV.X() );
5586 pos->SetVParameter( newUV.Y() );
5595 //================================================================================
5597 * \brief smooth _LayerEdge's on a an EDGE
5599 //================================================================================
5601 bool _Smoother1D::smoothComplexEdge( _SolidData& data,
5602 Handle(ShapeAnalysis_Surface)& surface,
5603 const TopoDS_Face& F,
5604 SMESH_MesherHelper& helper)
5606 if ( _offPoints.empty() )
5609 // move _offPoints along normals of _LayerEdge's
5611 _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5612 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5613 _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5614 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED ))
5615 _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5616 _leOnV[0]._len = e[0]->_len;
5617 _leOnV[1]._len = e[1]->_len;
5618 for ( size_t i = 0; i < _offPoints.size(); i++ )
5620 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5621 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5622 const double w0 = _offPoints[i]._2edges._wgt[0];
5623 const double w1 = _offPoints[i]._2edges._wgt[1];
5624 gp_XYZ avgNorm = ( e0->_normal * w0 + e1->_normal * w1 ).Normalized();
5625 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5626 double avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5627 if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5628 e1->Is( _LayerEdge::NORMAL_UPDATED ))
5629 avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5631 _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5632 _offPoints[i]._len = avgLen;
5636 if ( !surface.IsNull() ) // project _offPoints to the FACE
5638 fTol = 100 * BRep_Tool::Tolerance( F );
5639 //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5641 gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5642 //if ( surface->Gap() < 0.5 * segLen )
5643 _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5645 for ( size_t i = 1; i < _offPoints.size(); ++i )
5647 uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5648 //if ( surface->Gap() < 0.5 * segLen )
5649 _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5653 // project tgt nodes of extreme _LayerEdge's to the offset segments
5655 if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5656 if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5658 gp_Pnt pExtreme[2], pProj[2];
5659 for ( int is2nd = 0; is2nd < 2; ++is2nd )
5661 pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5662 int i = _iSeg[ is2nd ];
5663 int di = is2nd ? -1 : +1;
5664 bool projected = false;
5665 double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5668 gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ] );
5669 gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5670 uOnSeg = ( v0p * v01 ) / v01.SquareMagnitude(); // param [0,1] along v01
5671 projected = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5672 dist = pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5673 if ( dist < distMin || projected )
5676 pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5679 else if ( dist > distPrev )
5681 if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5687 while ( !projected &&
5688 i >= 0 && i+1 < (int)_offPoints.size() );
5692 if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5695 _iSeg[1] = _offPoints.size()-2;
5696 debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5701 if ( _iSeg[0] > _iSeg[1] )
5703 debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5707 // adjust length of extreme LE (test viscous_layers_01/B7)
5708 gp_Vec vDiv0( pExtreme[0], pProj[0] );
5709 gp_Vec vDiv1( pExtreme[1], pProj[1] );
5710 double d0 = vDiv0.Magnitude();
5711 double d1 = vDiv1.Magnitude();
5712 if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5713 else e[0]->_len -= d0;
5714 if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5715 else e[1]->_len -= d1;
5717 // compute normalized length of the offset segments located between the projections
5719 size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5720 vector< double > len( nbSeg + 1 );
5722 len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5723 for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5725 len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5727 len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5729 // d0 *= e[0]->_lenFactor;
5730 // d1 *= e[1]->_lenFactor;
5731 double fullLen = len.back() - d0 - d1;
5732 for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5733 len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5735 // temporary replace extreme _offPoints by pExtreme
5736 gp_XYZ op[2] = { _offPoints[ _iSeg[0] ]._xyz,
5737 _offPoints[ _iSeg[1]+1 ]._xyz };
5738 _offPoints[ _iSeg[0] ]._xyz = pExtreme[0].XYZ();
5739 _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5741 // distribute tgt nodes of _LayerEdge's between the projections
5744 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5746 if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5747 while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5749 double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5750 gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0] ]._xyz * ( 1 - r ) +
5751 _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5753 if ( surface.IsNull() )
5755 _eos._edges[i]->_pos.back() = p;
5757 else // project a new node position to a FACE
5759 gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5760 gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5762 p = surface->Value( uv2 ).XYZ();
5763 _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5765 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5766 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5767 dumpMove( tgtNode );
5770 _offPoints[ _iSeg[0] ]._xyz = op[0];
5771 _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5776 //================================================================================
5778 * \brief Prepare for smoothing
5780 //================================================================================
5782 void _Smoother1D::prepare(_SolidData& data)
5784 const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5785 _curveLen = SMESH_Algo::EdgeLength( E );
5787 // sort _LayerEdge's by position on the EDGE
5788 data.SortOnEdge( E, _eos._edges );
5790 // compute normalized param of _eos._edges on EDGE
5791 _leParams.resize( _eos._edges.size() + 1 );
5794 gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5796 for ( size_t i = 0; i < _eos._edges.size(); ++i )
5798 gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5799 curLen = p.Distance( pPrev );
5800 _leParams[i+1] = _leParams[i] + curLen;
5803 double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5804 for ( size_t i = 0; i < _leParams.size()-1; ++i )
5805 _leParams[i] = _leParams[i+1] / fullLen;
5811 // divide E to have offset segments with low deflection
5812 BRepAdaptor_Curve c3dAdaptor( E );
5813 const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5814 const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5815 GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5816 if ( discret.NbPoints() <= 2 )
5818 _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5822 const double u0 = c3dAdaptor.FirstParameter();
5823 gp_Pnt p; gp_Vec tangent;
5824 _offPoints.resize( discret.NbPoints() );
5825 for ( size_t i = 0; i < _offPoints.size(); i++ )
5827 double u = discret.Parameter( i+1 );
5828 c3dAdaptor.D1( u, p, tangent );
5829 _offPoints[i]._xyz = p.XYZ();
5830 _offPoints[i]._edgeDir = tangent.XYZ();
5831 _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5834 _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5837 _offPoints [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5838 _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5839 _2NearEdges tmp2edges;
5840 tmp2edges._edges[1] = _eos._edges[0];
5841 _leOnV[0]._2neibors = & tmp2edges;
5842 _leOnV[0]._nodes = leOnV[0]->_nodes;
5843 _leOnV[1]._nodes = leOnV[1]->_nodes;
5844 _LayerEdge* eNext, *ePrev = & _leOnV[0];
5845 for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5847 // find _LayerEdge's located before and after an offset point
5848 // (_eos._edges[ iLE ] is next after ePrev)
5849 while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5850 ePrev = _eos._edges[ iLE++ ];
5851 eNext = ePrev->_2neibors->_edges[1];
5853 gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5854 gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5855 double r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5856 _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5859 // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5860 for ( size_t i = 0; i < _offPoints.size(); i++ )
5861 if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5862 _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5864 for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5865 if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5866 _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5869 // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5871 int iLBO = _offPoints.size() - 2; // last but one
5873 _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5874 _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5876 _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5877 _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5878 _leOnV[ 0 ]._len = 0;
5879 _leOnV[ 1 ]._len = 0;
5880 _leOnV[ 0 ]._lenFactor = _offPoints[1 ]._2edges._edges[1]->_lenFactor;
5881 _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5884 _iSeg[1] = _offPoints.size()-2;
5886 // initialize OffPnt::_len
5887 for ( size_t i = 0; i < _offPoints.size(); ++i )
5888 _offPoints[i]._len = 0;
5890 if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5892 _leOnV[0]._len = leOnV[0]->_len;
5893 _leOnV[1]._len = leOnV[1]->_len;
5894 for ( size_t i = 0; i < _offPoints.size(); i++ )
5896 _LayerEdge* e0 = _offPoints[i]._2edges._edges[0];
5897 _LayerEdge* e1 = _offPoints[i]._2edges._edges[1];
5898 const double w0 = _offPoints[i]._2edges._wgt[0];
5899 const double w1 = _offPoints[i]._2edges._wgt[1];
5900 double avgLen = ( e0->_len * w0 + e1->_len * w1 );
5901 gp_XYZ avgXYZ = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5902 SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5903 _offPoints[i]._xyz = avgXYZ;
5904 _offPoints[i]._len = avgLen;
5909 //================================================================================
5911 * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5913 //================================================================================
5915 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5916 const gp_XYZ& edgeDir)
5918 gp_XYZ cross = normal ^ edgeDir;
5919 gp_XYZ norm = edgeDir ^ cross;
5920 double size = norm.Modulus();
5925 //================================================================================
5927 * \brief Sort _LayerEdge's by a parameter on a given EDGE
5929 //================================================================================
5931 void _SolidData::SortOnEdge( const TopoDS_Edge& E,
5932 vector< _LayerEdge* >& edges)
5934 map< double, _LayerEdge* > u2edge;
5935 for ( size_t i = 0; i < edges.size(); ++i )
5936 u2edge.insert( u2edge.end(),
5937 make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5939 ASSERT( u2edge.size() == edges.size() );
5940 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5941 for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5942 edges[i] = u2e->second;
5944 Sort2NeiborsOnEdge( edges );
5947 //================================================================================
5949 * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5951 //================================================================================
5953 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5955 if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5957 for ( size_t i = 0; i < edges.size()-1; ++i )
5958 if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5959 edges[i]->_2neibors->reverse();
5961 const size_t iLast = edges.size() - 1;
5962 if ( edges.size() > 1 &&
5963 edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5964 edges[iLast]->_2neibors->reverse();
5967 //================================================================================
5969 * \brief Return _EdgesOnShape* corresponding to the shape
5971 //================================================================================
5973 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5975 if ( shapeID < (int)_edgesOnShape.size() &&
5976 _edgesOnShape[ shapeID ]._shapeID == shapeID )
5977 return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5979 for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5980 if ( _edgesOnShape[i]._shapeID == shapeID )
5981 return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5986 //================================================================================
5988 * \brief Return _EdgesOnShape* corresponding to the shape
5990 //================================================================================
5992 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5994 SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5995 return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5998 //================================================================================
6000 * \brief Prepare data of the _LayerEdge for smoothing on FACE
6002 //================================================================================
6004 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6006 SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6008 set< TGeomID > vertices;
6010 if ( eos->ShapeType() == TopAbs_FACE )
6012 // check FACE concavity and get concave VERTEXes
6013 F = TopoDS::Face( eos->_shape );
6014 if ( isConcave( F, helper, &vertices ))
6015 _concaveFaces.insert( eos->_shapeID );
6017 // set eos._eosConcaVer
6018 eos->_eosConcaVer.clear();
6019 eos->_eosConcaVer.reserve( vertices.size() );
6020 for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6022 _EdgesOnShape* eov = GetShapeEdges( *v );
6023 if ( eov && eov->_edges.size() == 1 )
6025 eos->_eosConcaVer.push_back( eov );
6026 for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6027 eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6031 // SetSmooLen() to _LayerEdge's on FACE
6032 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6034 eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6036 SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6037 while ( smIt->more() ) // loop on sub-shapes of the FACE
6039 _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6040 if ( !eoe ) continue;
6042 vector<_LayerEdge*>& eE = eoe->_edges;
6043 for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6045 if ( eE[iE]->_cosin <= theMinSmoothCosin )
6048 SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6049 while ( segIt->more() )
6051 const SMDS_MeshElement* seg = segIt->next();
6052 if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6054 if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6055 continue; // not to check a seg twice
6056 for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6058 _LayerEdge* eN = eE[iE]->_neibors[iN];
6059 if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6061 double dist = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6062 double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6063 eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6064 eN->Set( _LayerEdge::NEAR_BOUNDARY );
6069 } // if ( eos->ShapeType() == TopAbs_FACE )
6071 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6073 eos->_edges[i]->_smooFunction = 0;
6074 eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6076 bool isCurved = false;
6077 for ( size_t i = 0; i < eos->_edges.size(); ++i )
6079 _LayerEdge* edge = eos->_edges[i];
6081 // get simplices sorted
6082 _Simplex::SortSimplices( edge->_simplices );
6084 // smoothing function
6085 edge->ChooseSmooFunction( vertices, _n2eMap );
6088 double avgNormProj = 0, avgLen = 0;
6089 for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6091 _Simplex& s = edge->_simplices[iS];
6093 gp_XYZ vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6094 avgNormProj += edge->_normal * vec;
6095 avgLen += vec.Modulus();
6096 if ( substituteSrcNodes )
6098 s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6099 s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6102 avgNormProj /= edge->_simplices.size();
6103 avgLen /= edge->_simplices.size();
6104 if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6107 SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6109 for ( size_t iS = 0; iS < edge->_simplices.size() && !fPos; ++iS )
6110 fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6112 edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6116 // prepare for putOnOffsetSurface()
6117 if (( eos->ShapeType() == TopAbs_FACE ) &&
6118 ( isCurved || !eos->_eosConcaVer.empty() ))
6120 eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6121 eos->_edgeForOffset = 0;
6123 double maxCosin = -1;
6124 for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6126 _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6127 if ( !eoe || eoe->_edges.empty() ) continue;
6129 vector<_LayerEdge*>& eE = eoe->_edges;
6130 _LayerEdge* e = eE[ eE.size() / 2 ];
6131 if ( e->_cosin > maxCosin )
6133 eos->_edgeForOffset = e;
6134 maxCosin = e->_cosin;
6140 //================================================================================
6142 * \brief Add faces for smoothing
6144 //================================================================================
6146 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6147 const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6149 set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6150 for ( ; eos != eosToSmooth.end(); ++eos )
6152 if ( !*eos || (*eos)->_toSmooth ) continue;
6154 (*eos)->_toSmooth = true;
6156 if ( (*eos)->ShapeType() == TopAbs_FACE )
6158 PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6159 (*eos)->_toSmooth = true;
6163 // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6164 if ( edgesNoAnaSmooth )
6165 for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6167 if ( (*eos)->_edgeSmoother )
6168 (*eos)->_edgeSmoother->_anaCurve.Nullify();
6172 //================================================================================
6174 * \brief Limit _LayerEdge::_maxLen according to local curvature
6176 //================================================================================
6178 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6180 // find intersection of neighbor _LayerEdge's to limit _maxLen
6181 // according to local curvature (IPAL52648)
6183 // This method must be called after findCollisionEdges() where _LayerEdge's
6184 // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6186 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6188 _EdgesOnShape& eosI = data._edgesOnShape[iS];
6189 if ( eosI._edges.empty() ) continue;
6190 if ( !eosI._hyp.ToSmooth() )
6192 for ( size_t i = 0; i < eosI._edges.size(); ++i )
6194 _LayerEdge* eI = eosI._edges[i];
6195 for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6197 _LayerEdge* eN = eI->_neibors[iN];
6198 if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6200 _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6201 limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6206 else if ( eosI.ShapeType() == TopAbs_EDGE )
6208 const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6209 if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6211 _LayerEdge* e0 = eosI._edges[0];
6212 for ( size_t i = 1; i < eosI._edges.size(); ++i )
6214 _LayerEdge* eI = eosI._edges[i];
6215 limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6222 //================================================================================
6224 * \brief Limit _LayerEdge::_maxLen according to local curvature
6226 //================================================================================
6228 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge* e1,
6230 _EdgesOnShape& eos1,
6231 _EdgesOnShape& eos2,
6232 SMESH_MesherHelper& helper )
6234 gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6235 double norSize = plnNorm.SquareModulus();
6236 if ( norSize < std::numeric_limits<double>::min() )
6237 return; // parallel normals
6239 // find closest points of skew _LayerEdge's
6240 SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6241 gp_XYZ dir12 = src2 - src1;
6242 gp_XYZ perp1 = e1->_normal ^ plnNorm;
6243 gp_XYZ perp2 = e2->_normal ^ plnNorm;
6244 double dot1 = perp2 * e1->_normal;
6245 double dot2 = perp1 * e2->_normal;
6246 double u1 = ( perp2 * dir12 ) / dot1;
6247 double u2 = - ( perp1 * dir12 ) / dot2;
6248 if ( u1 > 0 && u2 > 0 )
6250 double ovl = ( u1 * e1->_normal * dir12 -
6251 u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6252 if ( ovl > theSmoothThickToElemSizeRatio )
6254 e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6255 e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6260 //================================================================================
6262 * \brief Fill data._collisionEdges
6264 //================================================================================
6266 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6268 data._collisionEdges.clear();
6270 // set the full thickness of the layers to LEs
6271 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6273 _EdgesOnShape& eos = data._edgesOnShape[iS];
6274 if ( eos._edges.empty() ) continue;
6275 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6277 for ( size_t i = 0; i < eos._edges.size(); ++i )
6279 if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6280 double maxLen = eos._edges[i]->_maxLen;
6281 eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6282 eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6283 eos._edges[i]->_maxLen = maxLen;
6287 // make temporary quadrangles got by extrusion of
6288 // mesh edges along _LayerEdge._normal's
6290 vector< const SMDS_MeshElement* > tmpFaces;
6292 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6294 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6295 if ( eos.ShapeType() != TopAbs_EDGE )
6297 if ( eos._edges.empty() )
6299 _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6300 SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6301 while ( smIt->more() )
6302 if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6303 if ( eov->_edges.size() == 1 )
6304 edge[ bool( edge[0]) ] = eov->_edges[0];
6308 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6309 tmpFaces.push_back( f );
6312 for ( size_t i = 0; i < eos._edges.size(); ++i )
6314 _LayerEdge* edge = eos._edges[i];
6315 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6317 const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6318 if ( src2->GetPosition()->GetDim() > 0 &&
6319 src2->GetID() < edge->_nodes[0]->GetID() )
6320 continue; // avoid using same segment twice
6322 // a _LayerEdge containg tgt2
6323 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6325 _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6326 tmpFaces.push_back( f );
6331 // Find _LayerEdge's intersecting tmpFaces.
6333 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6335 SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6336 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6338 double dist1, dist2, segLen, eps = 0.5;
6339 _CollisionEdges collEdges;
6340 vector< const SMDS_MeshElement* > suspectFaces;
6341 const double angle45 = Cos( 45. * M_PI / 180. );
6343 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6345 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6346 if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6348 // find sub-shapes whose VL can influence VL on eos
6349 set< TGeomID > neighborShapes;
6350 PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6351 while ( const TopoDS_Shape* face = fIt->next() )
6353 TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6354 if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6356 SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6357 while ( subIt->more() )
6358 neighborShapes.insert( subIt->next()->GetId() );
6361 if ( eos.ShapeType() == TopAbs_VERTEX )
6363 PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6364 while ( const TopoDS_Shape* edge = eIt->next() )
6365 neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6367 // find intersecting _LayerEdge's
6368 for ( size_t i = 0; i < eos._edges.size(); ++i )
6370 if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6371 _LayerEdge* edge = eos._edges[i];
6372 gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6375 gp_Vec eSegDir0, eSegDir1;
6376 if ( edge->IsOnEdge() )
6378 SMESH_TNodeXYZ eP( edge->_nodes[0] );
6379 eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6380 eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6382 suspectFaces.clear();
6383 searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6384 SMDSAbs_Face, suspectFaces );
6385 collEdges._intEdges.clear();
6386 for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6388 const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6389 if ( f->_le1 == edge || f->_le2 == edge ) continue;
6390 if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6391 if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6392 if ( edge->IsOnEdge() ) {
6393 if ( edge->_2neibors->include( f->_le1 ) ||
6394 edge->_2neibors->include( f->_le2 )) continue;
6397 if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6398 ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge ))) continue;
6400 dist1 = dist2 = Precision::Infinite();
6401 if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6402 dist1 = Precision::Infinite();
6403 if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6404 dist2 = Precision::Infinite();
6405 if (( dist1 > segLen ) && ( dist2 > segLen ))
6408 if ( edge->IsOnEdge() )
6410 // skip perpendicular EDGEs
6411 gp_Vec fSegDir = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6412 bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6413 isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6414 isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6415 isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6420 // either limit inflation of edges or remember them for updating _normal
6421 // double dot = edge->_normal * f->GetDir();
6424 collEdges._intEdges.push_back( f->_le1 );
6425 collEdges._intEdges.push_back( f->_le2 );
6429 // double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6430 // edge->_maxLen = Min( shortLen, edge->_maxLen );
6434 if ( !collEdges._intEdges.empty() )
6436 collEdges._edge = edge;
6437 data._collisionEdges.push_back( collEdges );
6442 for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6445 // restore the zero thickness
6446 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6448 _EdgesOnShape& eos = data._edgesOnShape[iS];
6449 if ( eos._edges.empty() ) continue;
6450 if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6452 for ( size_t i = 0; i < eos._edges.size(); ++i )
6454 eos._edges[i]->InvalidateStep( 1, eos );
6455 eos._edges[i]->_len = 0;
6460 //================================================================================
6462 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6463 * _LayerEdge's on neighbor EDGE's
6465 //================================================================================
6467 bool _ViscousBuilder::updateNormals( _SolidData& data,
6468 SMESH_MesherHelper& helper,
6472 updateNormalsOfC1Vertices( data );
6474 if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6477 // map to store new _normal and _cosin for each intersected edge
6478 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp > edge2newEdge;
6479 map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6480 _LayerEdge zeroEdge;
6481 zeroEdge._normal.SetCoord( 0,0,0 );
6482 zeroEdge._maxLen = Precision::Infinite();
6483 zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6485 set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6487 double segLen, dist1, dist2, dist;
6488 vector< pair< _LayerEdge*, double > > intEdgesDist;
6489 _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6491 for ( int iter = 0; iter < 5; ++iter )
6493 edge2newEdge.clear();
6495 for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6497 _CollisionEdges& ce = data._collisionEdges[iE];
6498 _LayerEdge* edge1 = ce._edge;
6499 if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6500 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6501 if ( !eos1 ) continue;
6503 // detect intersections
6504 gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6505 double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6507 intEdgesDist.clear();
6508 double minIntDist = Precision::Infinite();
6509 for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6511 if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6512 ce._intEdges[i ]->Is( _LayerEdge::BLOCKED ) &&
6513 ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6515 double dot = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6516 double fact = ( 1.1 + dot * dot );
6517 SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6518 SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6519 gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6520 gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6521 dist1 = dist2 = Precision::Infinite();
6522 if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1, dist1, eps ) &&
6523 !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6526 if ( dist > testLen || dist <= 0 )
6529 if ( dist > testLen || dist <= 0 )
6532 // choose a closest edge
6533 gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6534 double d1 = intP.SquareDistance( pSrc0 );
6535 double d2 = intP.SquareDistance( pSrc1 );
6536 int iClose = i + ( d2 < d1 );
6537 _LayerEdge* edge2 = ce._intEdges[iClose];
6538 edge2->Unset( _LayerEdge::MARKED );
6540 // choose a closest edge among neighbors
6541 gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6542 d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6543 for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6545 _LayerEdge * edgeJ = intEdgesDist[j].first;
6546 if ( edge2->IsNeiborOnEdge( edgeJ ))
6548 d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6549 ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6552 intEdgesDist.push_back( make_pair( edge2, dist ));
6553 // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6555 // iClose = i + !( d2 < d1 );
6556 // intEdges.push_back( ce._intEdges[iClose] );
6557 // ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6559 minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6564 // compute new _normals
6565 for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6567 _LayerEdge* edge2 = intEdgesDist[i].first;
6568 double distWgt = edge1->_len / intEdgesDist[i].second;
6569 // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6570 // edge2->Is( _LayerEdge::BLOCKED )) continue;
6571 if ( edge2->Is( _LayerEdge::MARKED )) continue;
6572 edge2->Set( _LayerEdge::MARKED );
6575 gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6577 double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6578 double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6579 double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6580 // double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6581 // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6582 // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6583 // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6584 gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6585 newNormal.Normalize();
6589 double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6590 if ( cos1 < theMinSmoothCosin )
6592 newCos = cos2 * sgn1;
6594 else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6596 newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6600 newCos = edge1->_cosin;
6603 e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6604 e2neIt->second._normal += distWgt * newNormal;
6605 e2neIt->second._cosin = newCos;
6606 e2neIt->second._maxLen = 0.7 * minIntDist / edge1->_lenFactor;
6607 if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6608 e2neIt->second._normal += dir2;
6609 e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6610 e2neIt->second._normal += distWgt * newNormal;
6611 e2neIt->second._cosin = edge2->_cosin;
6612 if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6613 e2neIt->second._normal += dir1;
6617 if ( edge2newEdge.empty() )
6618 break; //return true;
6620 dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6622 // Update data of edges depending on a new _normal
6625 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6627 _LayerEdge* edge = e2neIt->first;
6628 if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6629 _LayerEdge& newEdge = e2neIt->second;
6630 _EdgesOnShape* eos = data.GetShapeEdges( edge );
6632 // Check if a new _normal is OK:
6633 newEdge._normal.Normalize();
6634 if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6636 if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6638 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6639 edge->_maxLen = newEdge._maxLen;
6640 edge->SetNewLength( newEdge._maxLen, *eos, helper );
6642 continue; // the new _normal is bad
6644 // the new _normal is OK
6646 // find shapes that need smoothing due to change of _normal
6647 if ( edge->_cosin < theMinSmoothCosin &&
6648 newEdge._cosin > theMinSmoothCosin )
6650 if ( eos->_sWOL.IsNull() )
6652 SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6653 while ( fIt->more() )
6654 shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6656 else // edge inflates along a FACE
6658 TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6659 PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6660 while ( const TopoDS_Shape* E = eIt->next() )
6662 if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6664 gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6665 double angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6666 if ( angle < M_PI / 2 )
6667 shapesToSmooth.insert( data.GetShapeEdges( *E ));
6672 double len = edge->_len;
6673 edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6674 edge->SetNormal( newEdge._normal );
6675 edge->SetCosin( newEdge._cosin );
6676 edge->SetNewLength( len, *eos, helper );
6677 edge->Set( _LayerEdge::MARKED );
6678 edge->Set( _LayerEdge::NORMAL_UPDATED );
6679 edgesNoAnaSmooth.insert( eos );
6682 // Update normals and other dependent data of not intersecting _LayerEdge's
6683 // neighboring the intersecting ones
6685 for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6687 _LayerEdge* edge1 = e2neIt->first;
6688 _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6689 if ( !edge1->Is( _LayerEdge::MARKED ))
6692 if ( edge1->IsOnEdge() )
6694 const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6695 const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6696 edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6699 if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6701 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6703 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6704 if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6705 continue; // j-th neighbor is also intersected
6706 _LayerEdge* prevEdge = edge1;
6707 const int nbSteps = 10;
6708 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6710 if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6711 neighbor->Is( _LayerEdge::MARKED ))
6713 _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6714 if ( !eos ) continue;
6715 _LayerEdge* nextEdge = neighbor;
6716 if ( neighbor->_2neibors )
6719 nextEdge = neighbor->_2neibors->_edges[iNext];
6720 if ( nextEdge == prevEdge )
6721 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6723 double r = double(step-1)/nbSteps/(iter+1);
6724 if ( !nextEdge->_2neibors )
6727 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6728 newNorm.Normalize();
6729 if ( !isNewNormalOk( data, *neighbor, newNorm ))
6732 double len = neighbor->_len;
6733 neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true );
6734 neighbor->SetNormal( newNorm );
6735 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6736 if ( neighbor->_2neibors )
6737 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6738 neighbor->SetNewLength( len, *eos, helper );
6739 neighbor->Set( _LayerEdge::MARKED );
6740 neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6741 edgesNoAnaSmooth.insert( eos );
6743 if ( !neighbor->_2neibors )
6744 break; // neighbor is on VERTEX
6746 // goto the next neighbor
6747 prevEdge = neighbor;
6748 neighbor = nextEdge;
6755 data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6760 //================================================================================
6762 * \brief Check if a new normal is OK
6764 //================================================================================
6766 bool _ViscousBuilder::isNewNormalOk( _SolidData& data,
6768 const gp_XYZ& newNormal)
6770 // check a min angle between the newNormal and surrounding faces
6771 vector<_Simplex> simplices;
6772 SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6773 _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6774 double newMinDot = 1, curMinDot = 1;
6775 for ( size_t i = 0; i < simplices.size(); ++i )
6777 n1.Set( simplices[i]._nPrev );
6778 n2.Set( simplices[i]._nNext );
6779 gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6780 double normLen2 = normFace.SquareModulus();
6781 if ( normLen2 < std::numeric_limits<double>::min() )
6783 normFace /= Sqrt( normLen2 );
6784 newMinDot = Min( newNormal * normFace, newMinDot );
6785 curMinDot = Min( edge._normal * normFace, curMinDot );
6788 if ( newMinDot < 0.5 )
6790 ok = ( newMinDot >= curMinDot * 0.9 );
6791 //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6792 // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6793 // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6799 //================================================================================
6801 * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6803 //================================================================================
6805 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData& data,
6806 SMESH_MesherHelper& helper,
6808 const double stepSize )
6810 if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6811 return true; // no shapes needing smoothing
6813 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6815 _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6816 if ( //!eos._toSmooth || _eosC1 have _toSmooth == false
6817 !eos._hyp.ToSmooth() ||
6818 eos.ShapeType() != TopAbs_FACE ||
6819 eos._edges.empty() )
6822 bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6823 if ( !toSmooth ) continue;
6825 for ( size_t i = 0; i < eos._edges.size(); ++i )
6827 _LayerEdge* edge = eos._edges[i];
6828 if ( !edge->Is( _LayerEdge::SMOOTHED ))
6830 if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6833 const gp_XYZ& pPrev = edge->PrevPos();
6834 const gp_XYZ& pLast = edge->_pos.back();
6835 gp_XYZ stepVec = pLast - pPrev;
6836 double realStepSize = stepVec.Modulus();
6837 if ( realStepSize < numeric_limits<double>::min() )
6840 edge->_lenFactor = realStepSize / stepSize;
6841 edge->_normal = stepVec / realStepSize;
6842 edge->Set( _LayerEdge::NORMAL_UPDATED );
6849 //================================================================================
6851 * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6853 //================================================================================
6855 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6857 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6859 _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6860 if ( eov._eosC1.empty() ||
6861 eov.ShapeType() != TopAbs_VERTEX ||
6862 eov._edges.empty() )
6865 gp_XYZ newNorm = eov._edges[0]->_normal;
6866 double curThick = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6867 bool normChanged = false;
6869 for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6871 _EdgesOnShape* eoe = eov._eosC1[i];
6872 const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6873 const double eLen = SMESH_Algo::EdgeLength( e );
6874 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
6875 if ( oppV.IsSame( eov._shape ))
6876 oppV = SMESH_MesherHelper::IthVertex( 1, e );
6877 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6878 if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6879 if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6881 double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6882 if ( curThickOpp + curThick < eLen )
6885 double wgt = 2. * curThick / eLen;
6886 newNorm += wgt * eovOpp->_edges[0]->_normal;
6891 eov._edges[0]->SetNormal( newNorm.Normalized() );
6892 eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6897 //================================================================================
6899 * \brief Modify normals of _LayerEdge's on _ConvexFace's
6901 //================================================================================
6903 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData& data,
6904 SMESH_MesherHelper& helper,
6907 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6910 map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6911 for ( ; id2face != data._convexFaces.end(); ++id2face )
6913 _ConvexFace & convFace = (*id2face).second;
6914 if ( convFace._normalsFixed )
6915 continue; // already fixed
6916 if ( convFace.CheckPrisms() )
6917 continue; // nothing to fix
6919 convFace._normalsFixed = true;
6921 BRepAdaptor_Surface surface ( convFace._face, false );
6922 BRepLProp_SLProps surfProp( surface, 2, 1e-6 );
6924 // check if the convex FACE is of spherical shape
6926 Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6930 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6931 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6933 _EdgesOnShape& eos = *(id2eos->second);
6934 if ( eos.ShapeType() == TopAbs_VERTEX )
6936 _LayerEdge* ledge = eos._edges[ 0 ];
6937 if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6938 centersBox.Add( center );
6940 for ( size_t i = 0; i < eos._edges.size(); ++i )
6941 nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6943 if ( centersBox.IsVoid() )
6945 debugMsg( "Error: centersBox.IsVoid()" );
6948 const bool isSpherical =
6949 ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6951 int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6952 vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6956 // set _LayerEdge::_normal as average of all normals
6958 // WARNING: different density of nodes on EDGEs is not taken into account that
6959 // can lead to an improper new normal
6961 gp_XYZ avgNormal( 0,0,0 );
6963 id2eos = convFace._subIdToEOS.begin();
6964 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6966 _EdgesOnShape& eos = *(id2eos->second);
6967 // set data of _CentralCurveOnEdge
6968 if ( eos.ShapeType() == TopAbs_EDGE )
6970 _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6971 ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6972 if ( !eos._sWOL.IsNull() )
6973 ceCurve._adjFace.Nullify();
6975 ceCurve._ledges.insert( ceCurve._ledges.end(),
6976 eos._edges.begin(), eos._edges.end());
6978 // summarize normals
6979 for ( size_t i = 0; i < eos._edges.size(); ++i )
6980 avgNormal += eos._edges[ i ]->_normal;
6982 double normSize = avgNormal.SquareModulus();
6983 if ( normSize < 1e-200 )
6985 debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6988 avgNormal /= Sqrt( normSize );
6990 // compute new _LayerEdge::_cosin on EDGEs
6991 double avgCosin = 0;
6994 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6996 _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6997 if ( ceCurve._adjFace.IsNull() )
6999 for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7001 const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7002 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7005 double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7006 ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7007 avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7013 avgCosin /= nbCosin;
7015 // set _LayerEdge::_normal = avgNormal
7016 id2eos = convFace._subIdToEOS.begin();
7017 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7019 _EdgesOnShape& eos = *(id2eos->second);
7020 if ( eos.ShapeType() != TopAbs_EDGE )
7021 for ( size_t i = 0; i < eos._edges.size(); ++i )
7022 eos._edges[ i ]->_cosin = avgCosin;
7024 for ( size_t i = 0; i < eos._edges.size(); ++i )
7026 eos._edges[ i ]->SetNormal( avgNormal );
7027 eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7031 else // if ( isSpherical )
7033 // We suppose that centers of curvature at all points of the FACE
7034 // lie on some curve, let's call it "central curve". For all _LayerEdge's
7035 // having a common center of curvature we define the same new normal
7036 // as a sum of normals of _LayerEdge's on EDGEs among them.
7038 // get all centers of curvature for each EDGE
7040 helper.SetSubShape( convFace._face );
7041 _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7043 TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7044 for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7046 const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7048 // set adjacent FACE
7049 centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7051 // get _LayerEdge's of the EDGE
7052 TGeomID edgeID = meshDS->ShapeToIndex( edge );
7053 _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7054 if ( !eos || eos->_edges.empty() )
7056 // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7057 for ( int iV = 0; iV < 2; ++iV )
7059 TopoDS_Vertex v = helper.IthVertex( iV, edge );
7060 TGeomID vID = meshDS->ShapeToIndex( v );
7061 eos = data.GetShapeEdges( vID );
7062 vertexLEdges[ iV ] = eos->_edges[ 0 ];
7064 edgeLEdge = &vertexLEdges[0];
7065 edgeLEdgeEnd = edgeLEdge + 2;
7067 centerCurves[ iE ]._adjFace.Nullify();
7071 if ( ! eos->_toSmooth )
7072 data.SortOnEdge( edge, eos->_edges );
7073 edgeLEdge = &eos->_edges[ 0 ];
7074 edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7075 vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7076 vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7078 if ( ! eos->_sWOL.IsNull() )
7079 centerCurves[ iE ]._adjFace.Nullify();
7082 // Get curvature centers
7086 if ( edgeLEdge[0]->IsOnEdge() &&
7087 convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7089 centerCurves[ iE ].Append( center, vertexLEdges[0] );
7090 centersBox.Add( center );
7092 for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7093 if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7094 { // EDGE or VERTEXes
7095 centerCurves[ iE ].Append( center, *edgeLEdge );
7096 centersBox.Add( center );
7098 if ( edgeLEdge[-1]->IsOnEdge() &&
7099 convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7101 centerCurves[ iE ].Append( center, vertexLEdges[1] );
7102 centersBox.Add( center );
7104 centerCurves[ iE ]._isDegenerated =
7105 ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7107 } // loop on EDGES of convFace._face to set up data of centerCurves
7109 // Compute new normals for _LayerEdge's on EDGEs
7111 double avgCosin = 0;
7114 for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7116 _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7117 if ( ceCurve._isDegenerated )
7119 const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7120 vector< gp_XYZ > & newNormals = ceCurve._normals;
7121 for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7124 for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7127 isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7129 if ( isOK && !ceCurve._adjFace.IsNull() )
7131 // compute new _LayerEdge::_cosin
7132 const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7133 inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7136 double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7137 ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7138 avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7144 // set new normals to _LayerEdge's of NOT degenerated central curves
7145 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7147 if ( centerCurves[ iE ]._isDegenerated )
7149 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7151 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7152 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7155 // set new normals to _LayerEdge's of degenerated central curves
7156 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7158 if ( !centerCurves[ iE ]._isDegenerated ||
7159 centerCurves[ iE ]._ledges.size() < 3 )
7161 // new normal is an average of new normals at VERTEXes that
7162 // was computed on non-degenerated _CentralCurveOnEdge's
7163 gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7164 centerCurves[ iE ]._ledges.back ()->_normal );
7165 double sz = newNorm.Modulus();
7169 double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7170 0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7171 for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7173 centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7174 centerCurves[ iE ]._ledges[ iLE ]->_cosin = newCosin;
7175 centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7179 // Find new normals for _LayerEdge's based on FACE
7182 avgCosin /= nbCosin;
7183 const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7184 map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7185 if ( id2eos != convFace._subIdToEOS.end() )
7189 _EdgesOnShape& eos = * ( id2eos->second );
7190 for ( size_t i = 0; i < eos._edges.size(); ++i )
7192 _LayerEdge* ledge = eos._edges[ i ];
7193 if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7195 for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7197 iE = iE % centerCurves.size();
7198 if ( centerCurves[ iE ]._isDegenerated )
7200 newNorm.SetCoord( 0,0,0 );
7201 if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7203 ledge->SetNormal( newNorm );
7204 ledge->_cosin = avgCosin;
7205 ledge->Set( _LayerEdge::NORMAL_UPDATED );
7212 } // not a quasi-spherical FACE
7214 // Update _LayerEdge's data according to a new normal
7216 dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7217 <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7219 id2eos = convFace._subIdToEOS.begin();
7220 for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7222 _EdgesOnShape& eos = * ( id2eos->second );
7223 for ( size_t i = 0; i < eos._edges.size(); ++i )
7225 _LayerEdge* & ledge = eos._edges[ i ];
7226 double len = ledge->_len;
7227 ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7228 ledge->SetCosin( ledge->_cosin );
7229 ledge->SetNewLength( len, eos, helper );
7231 if ( eos.ShapeType() != TopAbs_FACE )
7232 for ( size_t i = 0; i < eos._edges.size(); ++i )
7234 _LayerEdge* ledge = eos._edges[ i ];
7235 for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7237 _LayerEdge* neibor = ledge->_neibors[iN];
7238 if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7240 neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7241 neibor->Set( _LayerEdge::MOVED );
7242 neibor->SetSmooLen( neibor->_len );
7246 } // loop on sub-shapes of convFace._face
7248 // Find FACEs adjacent to convFace._face that got necessity to smooth
7249 // as a result of normals modification
7251 set< _EdgesOnShape* > adjFacesToSmooth;
7252 for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7254 if ( centerCurves[ iE ]._adjFace.IsNull() ||
7255 centerCurves[ iE ]._adjFaceToSmooth )
7257 for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7259 if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7261 adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7266 data.AddShapesToSmooth( adjFacesToSmooth );
7271 } // loop on data._convexFaces
7276 //================================================================================
7278 * \brief Finds a center of curvature of a surface at a _LayerEdge
7280 //================================================================================
7282 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge* ledge,
7283 BRepLProp_SLProps& surfProp,
7284 SMESH_MesherHelper& helper,
7285 gp_Pnt & center ) const
7287 gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7288 surfProp.SetParameters( uv.X(), uv.Y() );
7289 if ( !surfProp.IsCurvatureDefined() )
7292 const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7293 double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7294 double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7295 if ( surfCurvatureMin > surfCurvatureMax )
7296 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7298 center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7303 //================================================================================
7305 * \brief Check that prisms are not distorted
7307 //================================================================================
7309 bool _ConvexFace::CheckPrisms() const
7312 for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7314 const _LayerEdge* edge = _simplexTestEdges[i];
7315 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7316 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7317 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7319 debugMsg( "Bad simplex of _simplexTestEdges ("
7320 << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7321 << " "<< edge->_simplices[j]._nPrev->GetID()
7322 << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7329 //================================================================================
7331 * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7332 * stored in this _CentralCurveOnEdge.
7333 * \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7334 * \param [in,out] newNormal - current normal at this point, to be redefined
7335 * \return bool - true if succeeded.
7337 //================================================================================
7339 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7341 if ( this->_isDegenerated )
7344 // find two centers the given one lies between
7346 for ( size_t i = 0, nb = _curvaCenters.size()-1; i < nb; ++i )
7348 double sl2 = 1.001 * _segLength2[ i ];
7350 double d1 = center.SquareDistance( _curvaCenters[ i ]);
7354 double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7355 if ( d2 > sl2 || d2 + d1 < 1e-100 )
7360 double r = d1 / ( d1 + d2 );
7361 gp_XYZ norm = (( 1. - r ) * _ledges[ i ]->_normal +
7362 ( r ) * _ledges[ i+1 ]->_normal );
7366 double sz = newNormal.Modulus();
7375 //================================================================================
7377 * \brief Set shape members
7379 //================================================================================
7381 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge& edge,
7382 const _ConvexFace& convFace,
7384 SMESH_MesherHelper& helper)
7388 PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7389 while ( const TopoDS_Shape* F = fIt->next())
7390 if ( !convFace._face.IsSame( *F ))
7392 _adjFace = TopoDS::Face( *F );
7393 _adjFaceToSmooth = false;
7394 // _adjFace already in a smoothing queue ?
7395 if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7396 _adjFaceToSmooth = eos->_toSmooth;
7401 //================================================================================
7403 * \brief Looks for intersection of it's last segment with faces
7404 * \param distance - returns shortest distance from the last node to intersection
7406 //================================================================================
7408 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
7410 const double& epsilon,
7412 const SMDS_MeshElement** intFace)
7414 vector< const SMDS_MeshElement* > suspectFaces;
7416 gp_Ax1 lastSegment = LastSegment( segLen, eos );
7417 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7419 bool segmentIntersected = false;
7420 distance = Precision::Infinite();
7421 int iFace = -1; // intersected face
7422 for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7424 const SMDS_MeshElement* face = suspectFaces[j];
7425 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7426 face->GetNodeIndex( _nodes[0] ) >= 0 )
7427 continue; // face sharing _LayerEdge node
7428 const int nbNodes = face->NbCornerNodes();
7429 bool intFound = false;
7431 SMDS_MeshElement::iterator nIt = face->begin_nodes();
7434 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7438 const SMDS_MeshNode* tria[3];
7441 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7444 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7450 if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7451 segmentIntersected = true;
7452 if ( distance > dist )
7453 distance = dist, iFace = j;
7456 if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7460 if ( segmentIntersected )
7463 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7464 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7465 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7466 << ", intersection with face ("
7467 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7468 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7469 << ") distance = " << distance << endl;
7473 return segmentIntersected;
7476 //================================================================================
7478 * \brief Returns a point used to check orientation of _simplices
7480 //================================================================================
7482 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7484 size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7486 if ( !eos || eos->_sWOL.IsNull() )
7489 if ( eos->SWOLType() == TopAbs_EDGE )
7491 return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7493 //else // TopAbs_FACE
7495 return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7498 //================================================================================
7500 * \brief Returns size and direction of the last segment
7502 //================================================================================
7504 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7506 // find two non-coincident positions
7507 gp_XYZ orig = _pos.back();
7509 int iPrev = _pos.size() - 2;
7510 //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7511 const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7512 while ( iPrev >= 0 )
7514 vec = orig - _pos[iPrev];
7515 if ( vec.SquareModulus() > tol*tol )
7525 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7526 segDir.SetDirection( _normal );
7531 gp_Pnt pPrev = _pos[ iPrev ];
7532 if ( !eos._sWOL.IsNull() )
7534 TopLoc_Location loc;
7535 if ( eos.SWOLType() == TopAbs_EDGE )
7538 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7539 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7543 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7544 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7546 vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7548 segDir.SetLocation( pPrev );
7549 segDir.SetDirection( vec );
7550 segLen = vec.Modulus();
7556 //================================================================================
7558 * \brief Return the last position of the target node on a FACE.
7559 * \param [in] F - the FACE this _LayerEdge is inflated along
7560 * \return gp_XY - result UV
7562 //================================================================================
7564 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7566 if ( F.IsSame( eos._sWOL )) // F is my FACE
7567 return gp_XY( _pos.back().X(), _pos.back().Y() );
7569 if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7570 return gp_XY( 1e100, 1e100 );
7572 // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7573 double f, l, u = _pos.back().X();
7574 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7575 if ( !C2d.IsNull() && f <= u && u <= l )
7576 return C2d->Value( u ).XY();
7578 return gp_XY( 1e100, 1e100 );
7581 //================================================================================
7583 * \brief Test intersection of the last segment with a given triangle
7584 * using Moller-Trumbore algorithm
7585 * Intersection is detected if distance to intersection is less than _LayerEdge._len
7587 //================================================================================
7589 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7590 const gp_XYZ& vert0,
7591 const gp_XYZ& vert1,
7592 const gp_XYZ& vert2,
7594 const double& EPSILON) const
7596 const gp_Pnt& orig = lastSegment.Location();
7597 const gp_Dir& dir = lastSegment.Direction();
7599 /* calculate distance from vert0 to ray origin */
7600 //gp_XYZ tvec = orig.XYZ() - vert0;
7602 //if ( tvec * dir > EPSILON )
7603 // intersected face is at back side of the temporary face this _LayerEdge belongs to
7606 gp_XYZ edge1 = vert1 - vert0;
7607 gp_XYZ edge2 = vert2 - vert0;
7609 /* begin calculating determinant - also used to calculate U parameter */
7610 gp_XYZ pvec = dir.XYZ() ^ edge2;
7612 /* if determinant is near zero, ray lies in plane of triangle */
7613 double det = edge1 * pvec;
7615 const double ANGL_EPSILON = 1e-12;
7616 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7619 /* calculate distance from vert0 to ray origin */
7620 gp_XYZ tvec = orig.XYZ() - vert0;
7622 /* calculate U parameter and test bounds */
7623 double u = ( tvec * pvec ) / det;
7624 //if (u < 0.0 || u > 1.0)
7625 if ( u < -EPSILON || u > 1.0 + EPSILON )
7628 /* prepare to test V parameter */
7629 gp_XYZ qvec = tvec ^ edge1;
7631 /* calculate V parameter and test bounds */
7632 double v = (dir.XYZ() * qvec) / det;
7633 //if ( v < 0.0 || u + v > 1.0 )
7634 if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7637 /* calculate t, ray intersects triangle */
7638 t = (edge2 * qvec) / det;
7644 //================================================================================
7646 * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7647 * neighbor _LayerEdge's by it's own inflation vector.
7648 * \param [in] eov - EOS of the VERTEX
7649 * \param [in] eos - EOS of the FACE
7650 * \param [in] step - inflation step
7651 * \param [in,out] badSmooEdges - not untangled _LayerEdge's
7653 //================================================================================
7655 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape* eov,
7656 const _EdgesOnShape* eos,
7658 vector< _LayerEdge* > & badSmooEdges )
7660 // check if any of _neibors is in badSmooEdges
7661 if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7662 badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7665 // get all edges to move
7667 set< _LayerEdge* > edges;
7669 // find a distance between _LayerEdge on VERTEX and its neighbors
7670 gp_XYZ curPosV = SMESH_TNodeXYZ( _nodes.back() );
7672 for ( size_t i = 0; i < _neibors.size(); ++i )
7674 _LayerEdge* nEdge = _neibors[i];
7675 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7677 edges.insert( nEdge );
7678 dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7681 // add _LayerEdge's close to curPosV
7685 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7687 _LayerEdge* edgeF = *e;
7688 for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7690 _LayerEdge* nEdge = edgeF->_neibors[i];
7691 if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7692 dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7693 edges.insert( nEdge );
7697 while ( nbE < edges.size() );
7699 // move the target node of the got edges
7701 gp_XYZ prevPosV = PrevPos();
7702 if ( eov->SWOLType() == TopAbs_EDGE )
7704 BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7705 prevPosV = curve.Value( prevPosV.X() ).XYZ();
7707 else if ( eov->SWOLType() == TopAbs_FACE )
7709 BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7710 prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7713 SMDS_FacePosition* fPos;
7714 //double r = 1. - Min( 0.9, step / 10. );
7715 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7717 _LayerEdge* edgeF = *e;
7718 const gp_XYZ prevVF = edgeF->PrevPos() - prevPosV;
7719 const gp_XYZ newPosF = curPosV + prevVF;
7720 SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7721 tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7722 edgeF->_pos.back() = newPosF;
7723 dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7725 // set _curvature to make edgeF updated by putOnOffsetSurface()
7726 if ( !edgeF->_curvature )
7727 if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7729 edgeF->_curvature = new _Curvature;
7730 edgeF->_curvature->_r = 0;
7731 edgeF->_curvature->_k = 0;
7732 edgeF->_curvature->_h2lenRatio = 0;
7733 edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7736 // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7737 // SMESH_TNodeXYZ( _nodes[0] ));
7738 // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7740 // _LayerEdge* edgeF = *e;
7741 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7742 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7743 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7744 // edgeF->_pos.back() = newPosF;
7745 // dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7748 // smooth _LayerEdge's around moved nodes
7749 //size_t nbBadBefore = badSmooEdges.size();
7750 for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7752 _LayerEdge* edgeF = *e;
7753 for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7754 if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7755 //&& !edges.count( edgeF->_neibors[j] ))
7757 _LayerEdge* edgeFN = edgeF->_neibors[j];
7758 edgeFN->Unset( SMOOTHED );
7759 int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7762 // gp_XYZ newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7763 // const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7764 // int nbBadAfter = edgeFN->_simplices.size();
7766 // for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7768 // nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7770 // if ( nbBadAfter <= nbBad )
7772 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7773 // tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7774 // edgeF->_pos.back() = newPosF;
7775 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7776 // nbBad = nbBadAfter;
7780 badSmooEdges.push_back( edgeFN );
7783 // move a bit not smoothed around moved nodes
7784 // for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7786 // _LayerEdge* edgeF = badSmooEdges[i];
7787 // SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7788 // gp_XYZ newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7789 // gp_XYZ newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7790 // tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7791 // edgeF->_pos.back() = newPosF;
7792 // dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7796 //================================================================================
7798 * \brief Perform smooth of _LayerEdge's based on EDGE's
7799 * \retval bool - true if node has been moved
7801 //================================================================================
7803 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7804 const TopoDS_Face& F,
7805 SMESH_MesherHelper& helper)
7807 ASSERT( IsOnEdge() );
7809 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7810 SMESH_TNodeXYZ oldPos( tgtNode );
7811 double dist01, distNewOld;
7813 SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7814 SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7815 dist01 = p0.Distance( _2neibors->tgtNode(1) );
7817 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7818 double lenDelta = 0;
7821 //lenDelta = _curvature->lenDelta( _len );
7822 lenDelta = _curvature->lenDeltaByDist( dist01 );
7823 newPos.ChangeCoord() += _normal * lenDelta;
7826 distNewOld = newPos.Distance( oldPos );
7830 if ( _2neibors->_plnNorm )
7832 // put newPos on the plane defined by source node and _plnNorm
7833 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7834 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7835 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7837 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7838 _pos.back() = newPos.XYZ();
7842 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7843 gp_XY uv( Precision::Infinite(), 0 );
7844 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7845 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7847 newPos = surface->Value( uv );
7848 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7851 // commented for IPAL0052478
7852 // if ( _curvature && lenDelta < 0 )
7854 // gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7855 // _len -= prevPos.Distance( oldPos );
7856 // _len += prevPos.Distance( newPos );
7858 bool moved = distNewOld > dist01/50;
7860 dumpMove( tgtNode ); // debug
7865 //================================================================================
7867 * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7869 //================================================================================
7871 void _LayerEdge::SmoothWoCheck()
7873 if ( Is( DIFFICULT ))
7876 bool moved = Is( SMOOTHED );
7877 for ( size_t i = 0; i < _neibors.size() && !moved; ++i )
7878 moved = _neibors[i]->Is( SMOOTHED );
7882 gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7884 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7885 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7886 _pos.back() = newPos;
7888 dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7891 //================================================================================
7893 * \brief Checks validity of _neibors on EDGEs and VERTEXes
7895 //================================================================================
7897 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7899 if ( ! Is( NEAR_BOUNDARY ))
7904 for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7906 _LayerEdge* eN = _neibors[iN];
7907 if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7910 *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7911 eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7912 eN->_pos.size() != _pos.size() );
7914 SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7915 SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7916 for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7917 if ( eN->_nodes.size() > 1 &&
7918 eN->_simplices[i].Includes( _nodes.back() ) &&
7919 !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7924 badNeibors->push_back( eN );
7925 debugMsg("Bad boundary simplex ( "
7926 << " "<< eN->_nodes[0]->GetID()
7927 << " "<< eN->_nodes.back()->GetID()
7928 << " "<< eN->_simplices[i]._nPrev->GetID()
7929 << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7940 //================================================================================
7942 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7943 * \retval int - nb of bad simplices around this _LayerEdge
7945 //================================================================================
7947 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7949 if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7950 return 0; // shape of simplices not changed
7951 if ( _simplices.size() < 2 )
7952 return 0; // _LayerEdge inflated along EDGE or FACE
7954 if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7957 const gp_XYZ& curPos = _pos.back();
7958 const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7960 // quality metrics (orientation) of tetras around _tgtNode
7962 double vol, minVolBefore = 1e100;
7963 for ( size_t i = 0; i < _simplices.size(); ++i )
7965 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7966 minVolBefore = Min( minVolBefore, vol );
7968 int nbBad = _simplices.size() - nbOkBefore;
7970 bool bndNeedSmooth = false;
7972 nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7976 // evaluate min angle
7977 if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7979 size_t nbGoodAngles = _simplices.size();
7981 for ( size_t i = 0; i < _simplices.size(); ++i )
7983 if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7986 if ( nbGoodAngles == _simplices.size() )
7992 if ( Is( ON_CONCAVE_FACE ))
7995 if ( step % 2 == 0 )
7998 if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8000 if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8001 _smooFunction = _funs[ FUN_CENTROIDAL ];
8003 _smooFunction = _funs[ FUN_LAPLACIAN ];
8006 // compute new position for the last _pos using different _funs
8009 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8012 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8013 else if ( _funs[ iFun ] == _smooFunction )
8014 continue; // _smooFunction again
8015 else if ( step > 1 )
8016 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8018 break; // let "easy" functions improve elements around distorted ones
8022 double delta = _curvature->lenDelta( _len );
8024 newPos += _normal * delta;
8027 double segLen = _normal * ( newPos - prevPos );
8028 if ( segLen + delta > 0 )
8029 newPos += _normal * delta;
8031 // double segLenChange = _normal * ( curPos - newPos );
8032 // newPos += 0.5 * _normal * segLenChange;
8036 double minVolAfter = 1e100;
8037 for ( size_t i = 0; i < _simplices.size(); ++i )
8039 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8040 minVolAfter = Min( minVolAfter, vol );
8043 if ( nbOkAfter < nbOkBefore )
8047 ( nbOkAfter == nbOkBefore ) &&
8048 ( minVolAfter <= minVolBefore ))
8051 nbBad = _simplices.size() - nbOkAfter;
8052 minVolBefore = minVolAfter;
8053 nbOkBefore = nbOkAfter;
8056 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8057 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8058 _pos.back() = newPos;
8060 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8061 << (nbBad ? " --BAD" : ""));
8065 continue; // look for a better function
8071 } // loop on smoothing functions
8073 if ( moved ) // notify _neibors
8076 for ( size_t i = 0; i < _neibors.size(); ++i )
8077 if ( !_neibors[i]->Is( MOVED ))
8079 _neibors[i]->Set( MOVED );
8080 toSmooth.push_back( _neibors[i] );
8087 //================================================================================
8089 * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8090 * \retval int - nb of bad simplices around this _LayerEdge
8092 //================================================================================
8094 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8096 if ( !_smooFunction )
8097 return 0; // _LayerEdge inflated along EDGE or FACE
8099 return 0; // not inflated
8101 const gp_XYZ& curPos = _pos.back();
8102 const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8104 // quality metrics (orientation) of tetras around _tgtNode
8106 double vol, minVolBefore = 1e100;
8107 for ( size_t i = 0; i < _simplices.size(); ++i )
8109 nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8110 minVolBefore = Min( minVolBefore, vol );
8112 int nbBad = _simplices.size() - nbOkBefore;
8114 if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8116 if ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8117 _smooFunction = _funs[ FUN_LAPLACIAN ];
8118 else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8119 _smooFunction = _funs[ FUN_CENTROIDAL ];
8122 // compute new position for the last _pos using different _funs
8124 for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8127 newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8128 else if ( _funs[ iFun ] == _smooFunction )
8129 continue; // _smooFunction again
8130 else if ( step > 1 )
8131 newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8133 break; // let "easy" functions improve elements around distorted ones
8137 double delta = _curvature->lenDelta( _len );
8139 newPos += _normal * delta;
8142 double segLen = _normal * ( newPos - prevPos );
8143 if ( segLen + delta > 0 )
8144 newPos += _normal * delta;
8146 // double segLenChange = _normal * ( curPos - newPos );
8147 // newPos += 0.5 * _normal * segLenChange;
8151 double minVolAfter = 1e100;
8152 for ( size_t i = 0; i < _simplices.size(); ++i )
8154 nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8155 minVolAfter = Min( minVolAfter, vol );
8158 if ( nbOkAfter < nbOkBefore )
8160 if (( isConcaveFace || findBest ) &&
8161 ( nbOkAfter == nbOkBefore ) &&
8162 ( minVolAfter <= minVolBefore )
8166 nbBad = _simplices.size() - nbOkAfter;
8167 minVolBefore = minVolAfter;
8168 nbOkBefore = nbOkAfter;
8170 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8171 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8172 _pos.back() = newPos;
8174 dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8175 << ( nbBad ? "--BAD" : ""));
8177 // commented for IPAL0052478
8178 // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8179 // _len += prevPos.Distance(newPos);
8181 if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8183 //_smooFunction = _funs[ iFun ];
8184 // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8185 // << "\t nbBad: " << _simplices.size() - nbOkAfter
8186 // << " minVol: " << minVolAfter
8187 // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8189 continue; // look for a better function
8195 } // loop on smoothing functions
8200 //================================================================================
8202 * \brief Chooses a smoothing technic giving a position most close to an initial one.
8203 * For a correct result, _simplices must contain nodes lying on geometry.
8205 //================================================================================
8207 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8208 const TNode2Edge& n2eMap)
8210 if ( _smooFunction ) return;
8212 // use smoothNefPolygon() near concaveVertices
8213 if ( !concaveVertices.empty() )
8215 _smooFunction = _funs[ FUN_CENTROIDAL ];
8217 Set( ON_CONCAVE_FACE );
8219 for ( size_t i = 0; i < _simplices.size(); ++i )
8221 if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8223 _smooFunction = _funs[ FUN_NEFPOLY ];
8225 // set FUN_CENTROIDAL to neighbor edges
8226 for ( i = 0; i < _neibors.size(); ++i )
8228 if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8230 _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8237 // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8238 // // where the nodes are smoothed too far along a sphere thus creating
8239 // // inverted _simplices
8240 // double dist[theNbSmooFuns];
8241 // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8242 // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8244 // double minDist = Precision::Infinite();
8245 // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8246 // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8248 // gp_Pnt newP = (this->*_funs[i])();
8249 // dist[i] = p.SquareDistance( newP );
8250 // if ( dist[i]*coef[i] < minDist )
8252 // _smooFunction = _funs[i];
8253 // minDist = dist[i]*coef[i];
8259 _smooFunction = _funs[ FUN_LAPLACIAN ];
8262 // for ( size_t i = 0; i < _simplices.size(); ++i )
8263 // minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8264 // if ( minDim == 0 )
8265 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8266 // else if ( minDim == 1 )
8267 // _smooFunction = _funs[ FUN_CENTROIDAL ];
8271 // for ( int i = 0; i < FUN_NB; ++i )
8273 // //cout << dist[i] << " ";
8274 // if ( _smooFunction == _funs[i] ) {
8276 // //debugMsg( fNames[i] );
8280 // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8283 //================================================================================
8285 * \brief Returns a name of _SmooFunction
8287 //================================================================================
8289 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8292 fun = _smooFunction;
8293 for ( int i = 0; i < theNbSmooFuns; ++i )
8294 if ( fun == _funs[i] )
8297 return theNbSmooFuns;
8300 //================================================================================
8302 * \brief Computes a new node position using Laplacian smoothing
8304 //================================================================================
8306 gp_XYZ _LayerEdge::smoothLaplacian()
8308 gp_XYZ newPos (0,0,0);
8309 for ( size_t i = 0; i < _simplices.size(); ++i )
8310 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8311 newPos /= _simplices.size();
8316 //================================================================================
8318 * \brief Computes a new node position using angular-based smoothing
8320 //================================================================================
8322 gp_XYZ _LayerEdge::smoothAngular()
8324 vector< gp_Vec > edgeDir; edgeDir. reserve( _simplices.size() + 1 );
8325 vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
8326 vector< gp_XYZ > points; points. reserve( _simplices.size() + 1 );
8328 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8330 for ( size_t i = 0; i < _simplices.size(); ++i )
8332 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8333 edgeDir.push_back( p - pPrev );
8334 edgeSize.push_back( edgeDir.back().Magnitude() );
8335 if ( edgeSize.back() < numeric_limits<double>::min() )
8338 edgeSize.pop_back();
8342 edgeDir.back() /= edgeSize.back();
8343 points.push_back( p );
8348 edgeDir.push_back ( edgeDir[0] );
8349 edgeSize.push_back( edgeSize[0] );
8350 pN /= points.size();
8352 gp_XYZ newPos(0,0,0);
8354 for ( size_t i = 0; i < points.size(); ++i )
8356 gp_Vec toN = pN - points[i];
8357 double toNLen = toN.Magnitude();
8358 if ( toNLen < numeric_limits<double>::min() )
8363 gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
8364 double bisecLen = bisec.SquareMagnitude();
8365 if ( bisecLen < numeric_limits<double>::min() )
8367 gp_Vec norm = edgeDir[i] ^ toN;
8368 bisec = norm ^ edgeDir[i];
8369 bisecLen = bisec.SquareMagnitude();
8371 bisecLen = Sqrt( bisecLen );
8375 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8376 sumSize += bisecLen;
8378 gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8379 sumSize += ( edgeSize[i] + edgeSize[i+1] );
8385 // project newPos to an average plane
8387 gp_XYZ norm(0,0,0); // plane normal
8388 points.push_back( points[0] );
8389 for ( size_t i = 1; i < points.size(); ++i )
8391 gp_XYZ vec1 = points[ i-1 ] - pN;
8392 gp_XYZ vec2 = points[ i ] - pN;
8393 gp_XYZ cross = vec1 ^ vec2;
8396 if ( cross * norm < numeric_limits<double>::min() )
8397 norm += cross.Reversed();
8401 catch (Standard_Failure) { // if |cross| == 0.
8404 gp_XYZ vec = newPos - pN;
8405 double r = ( norm * vec ) / norm.SquareModulus(); // param [0,1] on norm
8406 newPos = newPos - r * norm;
8411 //================================================================================
8413 * \brief Computes a new node position using weigthed node positions
8415 //================================================================================
8417 gp_XYZ _LayerEdge::smoothLengthWeighted()
8419 vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8420 vector< gp_XYZ > points; points. reserve( _simplices.size() );
8422 gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8423 for ( size_t i = 0; i < _simplices.size(); ++i )
8425 gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8426 edgeSize.push_back( ( p - pPrev ).Modulus() );
8427 if ( edgeSize.back() < numeric_limits<double>::min() )
8429 edgeSize.pop_back();
8433 points.push_back( p );
8437 edgeSize.push_back( edgeSize[0] );
8439 gp_XYZ newPos(0,0,0);
8441 for ( size_t i = 0; i < points.size(); ++i )
8443 newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8444 sumSize += edgeSize[i] + edgeSize[i+1];
8450 //================================================================================
8452 * \brief Computes a new node position using angular-based smoothing
8454 //================================================================================
8456 gp_XYZ _LayerEdge::smoothCentroidal()
8458 gp_XYZ newPos(0,0,0);
8459 gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8461 for ( size_t i = 0; i < _simplices.size(); ++i )
8463 gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8464 gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8465 gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8466 double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8469 newPos += gc * size;
8476 //================================================================================
8478 * \brief Computes a new node position located inside a Nef polygon
8480 //================================================================================
8482 gp_XYZ _LayerEdge::smoothNefPolygon()
8483 #ifdef OLD_NEF_POLYGON
8485 gp_XYZ newPos(0,0,0);
8487 // get a plane to seach a solution on
8489 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8491 const double tol = numeric_limits<double>::min();
8492 gp_XYZ center(0,0,0);
8493 for ( i = 0; i < _simplices.size(); ++i )
8495 vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8496 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8497 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8499 vecs.back() = vecs[0];
8500 center /= _simplices.size();
8502 gp_XYZ zAxis(0,0,0);
8503 for ( i = 0; i < _simplices.size(); ++i )
8504 zAxis += vecs[i] ^ vecs[i+1];
8507 for ( i = 0; i < _simplices.size(); ++i )
8510 if ( yAxis.SquareModulus() > tol )
8513 gp_XYZ xAxis = yAxis ^ zAxis;
8514 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8515 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8516 // p0.Distance( _simplices[2]._nPrev ));
8517 // gp_XYZ center = smoothLaplacian();
8518 // gp_XYZ xAxis, yAxis, zAxis;
8519 // for ( i = 0; i < _simplices.size(); ++i )
8521 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8522 // if ( xAxis.SquareModulus() > tol*tol )
8525 // for ( i = 1; i < _simplices.size(); ++i )
8527 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8528 // zAxis = xAxis ^ yAxis;
8529 // if ( zAxis.SquareModulus() > tol*tol )
8532 // if ( i == _simplices.size() ) return newPos;
8534 yAxis = zAxis ^ xAxis;
8535 xAxis /= xAxis.Modulus();
8536 yAxis /= yAxis.Modulus();
8538 // get half-planes of _simplices
8540 vector< _halfPlane > halfPlns( _simplices.size() );
8542 for ( size_t i = 0; i < _simplices.size(); ++i )
8544 gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8545 gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8546 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8547 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8548 gp_XY vec12 = p2 - p1;
8549 double dist12 = vec12.Modulus();
8553 halfPlns[ nbHP ]._pos = p1;
8554 halfPlns[ nbHP ]._dir = vec12;
8555 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8559 // intersect boundaries of half-planes, define state of intersection points
8560 // in relation to all half-planes and calculate internal point of a 2D polygon
8563 gp_XY newPos2D (0,0);
8565 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8566 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8567 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8569 vector< vector< TIntPntState > > allIntPnts( nbHP );
8570 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8572 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8573 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8575 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8576 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8579 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8581 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8583 if ( iHP1 == iHP2 ) continue;
8585 TIntPntState & ips1 = intPnts1[ iHP2 ];
8586 if ( ips1.second == UNDEF )
8588 // find an intersection point of boundaries of iHP1 and iHP2
8590 if ( iHP2 == iPrev ) // intersection with neighbors is known
8591 ips1.first = halfPlns[ iHP1 ]._pos;
8592 else if ( iHP2 == iNext )
8593 ips1.first = halfPlns[ iHP2 ]._pos;
8594 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8595 ips1.second = NO_INT;
8597 // classify the found intersection point
8598 if ( ips1.second != NO_INT )
8600 ips1.second = NOT_OUT;
8601 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8602 if ( i != iHP1 && i != iHP2 &&
8603 halfPlns[ i ].IsOut( ips1.first, tol ))
8604 ips1.second = IS_OUT;
8606 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8607 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8608 TIntPntState & ips2 = intPnts2[ iHP1 ];
8611 if ( ips1.second == NOT_OUT )
8614 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8618 // find a NOT_OUT segment of boundary which is located between
8619 // two NOT_OUT int points
8622 continue; // no such a segment
8626 // sort points along the boundary
8627 map< double, TIntPntState* > ipsByParam;
8628 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8630 TIntPntState & ips1 = intPnts1[ iHP2 ];
8631 if ( ips1.second != NO_INT )
8633 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8634 double param = op * halfPlns[ iHP1 ]._dir;
8635 ipsByParam.insert( make_pair( param, & ips1 ));
8638 // look for two neighboring NOT_OUT points
8640 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8641 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8643 TIntPntState & ips1 = *(u2ips->second);
8644 if ( ips1.second == NOT_OUT )
8645 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8646 else if ( nbNotOut >= 2 )
8653 if ( nbNotOut >= 2 )
8655 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8658 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8665 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8674 #else // OLD_NEF_POLYGON
8675 { ////////////////////////////////// NEW
8676 gp_XYZ newPos(0,0,0);
8678 // get a plane to seach a solution on
8681 gp_XYZ center(0,0,0);
8682 for ( i = 0; i < _simplices.size(); ++i )
8683 center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8684 center /= _simplices.size();
8686 vector< gp_XYZ > vecs( _simplices.size() + 1 );
8687 for ( i = 0; i < _simplices.size(); ++i )
8688 vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8689 vecs.back() = vecs[0];
8691 const double tol = numeric_limits<double>::min();
8692 gp_XYZ zAxis(0,0,0);
8693 for ( i = 0; i < _simplices.size(); ++i )
8695 gp_XYZ cross = vecs[i] ^ vecs[i+1];
8698 if ( cross * zAxis < tol )
8699 zAxis += cross.Reversed();
8703 catch (Standard_Failure) { // if |cross| == 0.
8708 for ( i = 0; i < _simplices.size(); ++i )
8711 if ( yAxis.SquareModulus() > tol )
8714 gp_XYZ xAxis = yAxis ^ zAxis;
8715 // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8716 // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8717 // p0.Distance( _simplices[2]._nPrev ));
8718 // gp_XYZ center = smoothLaplacian();
8719 // gp_XYZ xAxis, yAxis, zAxis;
8720 // for ( i = 0; i < _simplices.size(); ++i )
8722 // xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8723 // if ( xAxis.SquareModulus() > tol*tol )
8726 // for ( i = 1; i < _simplices.size(); ++i )
8728 // yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8729 // zAxis = xAxis ^ yAxis;
8730 // if ( zAxis.SquareModulus() > tol*tol )
8733 // if ( i == _simplices.size() ) return newPos;
8735 yAxis = zAxis ^ xAxis;
8736 xAxis /= xAxis.Modulus();
8737 yAxis /= yAxis.Modulus();
8739 // get half-planes of _simplices
8741 vector< _halfPlane > halfPlns( _simplices.size() );
8743 for ( size_t i = 0; i < _simplices.size(); ++i )
8745 const gp_XYZ& OP1 = vecs[ i ];
8746 const gp_XYZ& OP2 = vecs[ i+1 ];
8747 gp_XY p1( OP1 * xAxis, OP1 * yAxis );
8748 gp_XY p2( OP2 * xAxis, OP2 * yAxis );
8749 gp_XY vec12 = p2 - p1;
8750 double dist12 = vec12.Modulus();
8754 halfPlns[ nbHP ]._pos = p1;
8755 halfPlns[ nbHP ]._dir = vec12;
8756 halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8760 // intersect boundaries of half-planes, define state of intersection points
8761 // in relation to all half-planes and calculate internal point of a 2D polygon
8764 gp_XY newPos2D (0,0);
8766 enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8767 typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8768 TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8770 vector< vector< TIntPntState > > allIntPnts( nbHP );
8771 for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8773 vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8774 if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8776 int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8777 int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8780 const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8782 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8784 if ( iHP1 == iHP2 ) continue;
8786 TIntPntState & ips1 = intPnts1[ iHP2 ];
8787 if ( ips1.second == UNDEF )
8789 // find an intersection point of boundaries of iHP1 and iHP2
8791 if ( iHP2 == iPrev ) // intersection with neighbors is known
8792 ips1.first = halfPlns[ iHP1 ]._pos;
8793 else if ( iHP2 == iNext )
8794 ips1.first = halfPlns[ iHP2 ]._pos;
8795 else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8796 ips1.second = NO_INT;
8798 // classify the found intersection point
8799 if ( ips1.second != NO_INT )
8801 ips1.second = NOT_OUT;
8802 for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8803 if ( i != iHP1 && i != iHP2 &&
8804 halfPlns[ i ].IsOut( ips1.first, tol ))
8805 ips1.second = IS_OUT;
8807 vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8808 if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8809 TIntPntState & ips2 = intPnts2[ iHP1 ];
8812 if ( ips1.second == NOT_OUT )
8815 segEnds[ bool(segEnds[0]) ] = & ips1.first;
8819 // find a NOT_OUT segment of boundary which is located between
8820 // two NOT_OUT int points
8823 continue; // no such a segment
8827 // sort points along the boundary
8828 map< double, TIntPntState* > ipsByParam;
8829 for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8831 TIntPntState & ips1 = intPnts1[ iHP2 ];
8832 if ( ips1.second != NO_INT )
8834 gp_XY op = ips1.first - halfPlns[ iHP1 ]._pos;
8835 double param = op * halfPlns[ iHP1 ]._dir;
8836 ipsByParam.insert( make_pair( param, & ips1 ));
8839 // look for two neighboring NOT_OUT points
8841 map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8842 for ( ; u2ips != ipsByParam.end(); ++u2ips )
8844 TIntPntState & ips1 = *(u2ips->second);
8845 if ( ips1.second == NOT_OUT )
8846 segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8847 else if ( nbNotOut >= 2 )
8854 if ( nbNotOut >= 2 )
8856 double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8859 newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8866 newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8875 #endif // OLD_NEF_POLYGON
8877 //================================================================================
8879 * \brief Add a new segment to _LayerEdge during inflation
8881 //================================================================================
8883 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8888 if ( len > _maxLen )
8891 Block( eos.GetData() );
8893 const double lenDelta = len - _len;
8894 if ( lenDelta < len * 1e-3 )
8896 Block( eos.GetData() );
8900 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8901 gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8903 if ( eos._hyp.IsOffsetMethod() )
8907 SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8908 while ( faceIt->more() )
8910 const SMDS_MeshElement* face = faceIt->next();
8911 if ( !eos.GetNormal( face, faceNorm ))
8914 // translate plane of a face
8915 gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8917 // find point of intersection of the face plane located at baryCenter
8918 // and _normal located at newXYZ
8919 double d = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8920 double dot = ( faceNorm.XYZ() * _normal );
8921 if ( dot < std::numeric_limits<double>::min() )
8922 dot = lenDelta * 1e-3;
8923 double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8924 newXYZ += step * _normal;
8926 _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8930 newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8933 n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8934 _pos.push_back( newXYZ );
8936 if ( !eos._sWOL.IsNull() )
8940 if ( eos.SWOLType() == TopAbs_EDGE )
8942 double u = Precision::Infinite(); // to force projection w/o distance check
8943 uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8944 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8945 _pos.back().SetCoord( u, 0, 0 );
8946 if ( _nodes.size() > 1 && uvOK )
8948 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8949 pos->SetUParameter( u );
8954 gp_XY uv( Precision::Infinite(), 0 );
8955 uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8956 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8957 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8958 if ( _nodes.size() > 1 && uvOK )
8960 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8961 pos->SetUParameter( uv.X() );
8962 pos->SetVParameter( uv.Y() );
8967 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8971 n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8973 Block( eos.GetData() );
8981 if ( eos.ShapeType() != TopAbs_FACE )
8983 for ( size_t i = 0; i < _neibors.size(); ++i )
8984 //if ( _len > _neibors[i]->GetSmooLen() )
8985 _neibors[i]->Set( MOVED );
8989 dumpMove( n ); //debug
8992 //================================================================================
8994 * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8996 //================================================================================
8998 void _LayerEdge::Block( _SolidData& data )
9000 //if ( Is( BLOCKED )) return;
9004 std::queue<_LayerEdge*> queue;
9007 gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9008 while ( !queue.empty() )
9010 _LayerEdge* edge = queue.front(); queue.pop();
9011 pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9012 pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9013 for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9015 _LayerEdge* neibor = edge->_neibors[iN];
9016 if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9018 pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9019 pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9020 double minDist = pSrc.SquareDistance( pSrcN );
9021 minDist = Min( pTgt.SquareDistance( pTgtN ), minDist );
9022 minDist = Min( pSrc.SquareDistance( pTgtN ), minDist );
9023 minDist = Min( pTgt.SquareDistance( pSrcN ), minDist );
9024 double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9025 if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9027 newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9029 if ( neibor->_maxLen > newMaxLen )
9031 neibor->_maxLen = newMaxLen;
9032 if ( neibor->_maxLen < neibor->_len )
9034 _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9035 while ( neibor->_len > neibor->_maxLen &&
9036 neibor->NbSteps() > 1 )
9037 neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9038 neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9039 //neibor->Block( data );
9041 queue.push( neibor );
9047 //================================================================================
9049 * \brief Remove last inflation step
9051 //================================================================================
9053 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9055 if ( _pos.size() > curStep && _nodes.size() > 1 )
9057 _pos.resize( curStep );
9059 gp_Pnt nXYZ = _pos.back();
9060 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9061 SMESH_TNodeXYZ curXYZ( n );
9062 if ( !eos._sWOL.IsNull() )
9064 TopLoc_Location loc;
9065 if ( eos.SWOLType() == TopAbs_EDGE )
9067 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9068 pos->SetUParameter( nXYZ.X() );
9070 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9071 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9075 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9076 pos->SetUParameter( nXYZ.X() );
9077 pos->SetVParameter( nXYZ.Y() );
9078 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9079 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9082 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9085 if ( restoreLength )
9087 _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9092 //================================================================================
9094 * \brief Return index of a _pos distant from _normal
9096 //================================================================================
9098 int _LayerEdge::GetSmoothedPos( const double tol )
9101 for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9103 double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9104 if ( normDist > tol * tol )
9110 //================================================================================
9112 * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9114 //================================================================================
9116 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9118 if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9121 // find the 1st smoothed _pos
9122 int iSmoothed = GetSmoothedPos( tol );
9123 if ( !iSmoothed ) return;
9125 //if ( 1 || Is( DISTORTED ))
9127 gp_XYZ normal = _normal;
9128 if ( Is( NORMAL_UPDATED ))
9129 for ( size_t i = 1; i < _pos.size(); ++i )
9131 normal = _pos[i] - _pos[0];
9132 double size = normal.Modulus();
9133 if ( size > RealSmall() )
9139 const double r = 0.2;
9140 for ( int iter = 0; iter < 50; ++iter )
9143 for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9145 gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9146 gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9148 double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9149 double newLen = ( 1-r ) * midLen + r * segLen[i];
9150 const_cast< double& >( segLen[i] ) = newLen;
9151 // check angle between normal and (_pos[i+1], _pos[i] )
9152 gp_XYZ posDir = _pos[i+1] - _pos[i];
9153 double size = posDir.SquareModulus();
9154 if ( size > RealSmall() )
9155 minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9157 if ( minDot > 0.5 * 0.5 )
9163 // for ( size_t i = 1; i < _pos.size()-1; ++i )
9165 // if ((int) i < iSmoothed && ( segLen[i] / segLen.back() < 0.5 ))
9168 // double wgt = segLen[i] / segLen.back();
9169 // gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9170 // gp_XYZ tgtPos = ( 1 - wgt ) * _pos[0] + wgt * _pos.back();
9171 // gp_XYZ newPos = ( 1 - wgt ) * normPos + wgt * tgtPos;
9172 // _pos[i] = newPos;
9177 //================================================================================
9179 * \brief Create layers of prisms
9181 //================================================================================
9183 bool _ViscousBuilder::refine(_SolidData& data)
9185 SMESH_MesherHelper& helper = data.GetHelper();
9186 helper.SetElementsOnShape(false);
9188 Handle(Geom_Curve) curve;
9189 Handle(ShapeAnalysis_Surface) surface;
9190 TopoDS_Edge geomEdge;
9191 TopoDS_Face geomFace;
9192 TopLoc_Location loc;
9195 vector< gp_XYZ > pos3D;
9197 TGeomID prevBaseId = -1;
9198 TNode2Edge* n2eMap = 0;
9199 TNode2Edge::iterator n2e;
9201 // Create intermediate nodes on each _LayerEdge
9203 for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9205 _EdgesOnShape& eos = data._edgesOnShape[iS];
9206 if ( eos._edges.empty() ) continue;
9208 if ( eos._edges[0]->_nodes.size() < 2 )
9209 continue; // on _noShrinkShapes
9211 // get data of a shrink shape
9213 geomEdge.Nullify(); geomFace.Nullify();
9214 curve.Nullify(); surface.Nullify();
9215 if ( !eos._sWOL.IsNull() )
9217 isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9220 geomEdge = TopoDS::Edge( eos._sWOL );
9221 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
9225 geomFace = TopoDS::Face( eos._sWOL );
9226 surface = helper.GetSurface( geomFace );
9229 else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9231 geomFace = TopoDS::Face( eos._shape );
9232 surface = helper.GetSurface( geomFace );
9233 // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9234 for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9236 eos._eosC1[ i ]->_toSmooth = true;
9237 for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9238 eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9242 vector< double > segLen;
9243 for ( size_t i = 0; i < eos._edges.size(); ++i )
9245 _LayerEdge& edge = *eos._edges[i];
9246 if ( edge._pos.size() < 2 )
9249 // get accumulated length of segments
9250 segLen.resize( edge._pos.size() );
9252 if ( eos._sWOL.IsNull() )
9254 bool useNormal = true;
9255 bool usePos = false;
9256 bool smoothed = false;
9257 double preci = 0.1 * edge._len;
9258 if ( eos._toSmooth && edge._pos.size() > 2 )
9260 smoothed = edge.GetSmoothedPos( preci );
9264 if ( !surface.IsNull() &&
9265 !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9267 useNormal = usePos = false;
9268 gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9269 for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9271 uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9272 if ( surface->Gap() < 2. * edge._len )
9273 segLen[j] = surface->Gap();
9279 else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9281 #ifndef __NODES_AT_POS
9282 useNormal = usePos = false;
9283 edge._pos[1] = edge._pos.back();
9284 edge._pos.resize( 2 );
9286 segLen[ 1 ] = edge._len;
9289 if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9291 useNormal = usePos = false;
9292 _LayerEdge tmpEdge; // get original _normal
9293 tmpEdge._nodes.push_back( edge._nodes[0] );
9294 if ( !setEdgeData( tmpEdge, eos, helper, data ))
9297 for ( size_t j = 1; j < edge._pos.size(); ++j )
9298 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9302 for ( size_t j = 1; j < edge._pos.size(); ++j )
9303 segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9307 for ( size_t j = 1; j < edge._pos.size(); ++j )
9308 segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9312 bool swapped = ( edge._pos.size() > 2 );
9316 for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9317 if ( segLen[j] > segLen.back() )
9319 segLen.erase( segLen.begin() + j );
9320 edge._pos.erase( edge._pos.begin() + j );
9323 else if ( segLen[j] < segLen[j-1] )
9325 std::swap( segLen[j], segLen[j-1] );
9326 std::swap( edge._pos[j], edge._pos[j-1] );
9331 // smooth a path formed by edge._pos
9332 #ifndef __NODES_AT_POS
9333 if (( smoothed ) /*&&
9334 ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9335 edge.SmoothPos( segLen, preci );
9338 else if ( eos._isRegularSWOL ) // usual SWOL
9340 for ( size_t j = 1; j < edge._pos.size(); ++j )
9341 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9343 else if ( !surface.IsNull() ) // SWOL surface with singularities
9345 pos3D.resize( edge._pos.size() );
9346 for ( size_t j = 0; j < edge._pos.size(); ++j )
9347 pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9349 for ( size_t j = 1; j < edge._pos.size(); ++j )
9350 segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9353 // allocate memory for new nodes if it is not yet refined
9354 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9355 if ( edge._nodes.size() == 2 )
9357 #ifdef __NODES_AT_POS
9358 int nbNodes = edge._pos.size();
9360 int nbNodes = eos._hyp.GetNumberLayers() + 1;
9362 edge._nodes.resize( nbNodes, 0 );
9364 edge._nodes.back() = tgtNode;
9366 // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9367 const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9368 if ( baseShapeId != prevBaseId )
9370 map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9371 n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9372 prevBaseId = baseShapeId;
9374 _LayerEdge* edgeOnSameNode = 0;
9375 bool useExistingPos = false;
9376 if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9378 edgeOnSameNode = n2e->second;
9379 useExistingPos = ( edgeOnSameNode->_len < edge._len );
9380 const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9381 SMDS_PositionPtr lastPos = tgtNode->GetPosition();
9384 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9385 epos->SetUParameter( otherTgtPos.X() );
9389 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9390 fpos->SetUParameter( otherTgtPos.X() );
9391 fpos->SetVParameter( otherTgtPos.Y() );
9394 // calculate height of the first layer
9396 const double T = segLen.back(); //data._hyp.GetTotalThickness();
9397 const double f = eos._hyp.GetStretchFactor();
9398 const int N = eos._hyp.GetNumberLayers();
9399 const double fPowN = pow( f, N );
9400 if ( fPowN - 1 <= numeric_limits<double>::min() )
9403 h0 = T * ( f - 1 )/( fPowN - 1 );
9405 const double zeroLen = std::numeric_limits<double>::min();
9407 // create intermediate nodes
9408 double hSum = 0, hi = h0/f;
9410 for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9412 // compute an intermediate position
9415 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9417 int iPrevSeg = iSeg-1;
9418 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9420 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9421 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9422 #ifdef __NODES_AT_POS
9423 pos = edge._pos[ iStep ];
9425 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9426 if ( !eos._sWOL.IsNull() )
9428 // compute XYZ by parameters <pos>
9433 pos = curve->Value( u ).Transformed(loc);
9435 else if ( eos._isRegularSWOL )
9437 uv.SetCoord( pos.X(), pos.Y() );
9439 pos = surface->Value( pos.X(), pos.Y() );
9443 uv.SetCoord( pos.X(), pos.Y() );
9444 gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9445 uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9447 pos = surface->Value( uv );
9450 // create or update the node
9453 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9454 if ( !eos._sWOL.IsNull() )
9457 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9459 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9463 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9468 if ( !eos._sWOL.IsNull() )
9470 // make average pos from new and current parameters
9473 //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9474 if ( useExistingPos )
9475 u = helper.GetNodeU( geomEdge, node );
9476 pos = curve->Value( u ).Transformed(loc);
9478 SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9479 epos->SetUParameter( u );
9483 //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9484 if ( useExistingPos )
9485 uv = helper.GetNodeUV( geomFace, node );
9486 pos = surface->Value( uv );
9488 SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9489 fpos->SetUParameter( uv.X() );
9490 fpos->SetVParameter( uv.Y() );
9493 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9495 } // loop on edge._nodes
9497 if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9500 edge._pos.back().SetCoord( u, 0,0);
9502 edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9504 if ( edgeOnSameNode )
9505 edgeOnSameNode->_pos.back() = edge._pos.back();
9508 } // loop on eos._edges to create nodes
9511 if ( !getMeshDS()->IsEmbeddedMode() )
9512 // Log node movement
9513 for ( size_t i = 0; i < eos._edges.size(); ++i )
9515 SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9516 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9523 helper.SetElementsOnShape(true);
9525 vector< vector<const SMDS_MeshNode*>* > nnVec;
9526 set< vector<const SMDS_MeshNode*>* > nnSet;
9527 set< int > degenEdgeInd;
9528 vector<const SMDS_MeshElement*> degenVols;
9529 vector<int> isRiskySWOL;
9531 TopExp_Explorer exp( data._solid, TopAbs_FACE );
9532 for ( ; exp.More(); exp.Next() )
9534 const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9535 if ( data._ignoreFaceIds.count( faceID ))
9537 const bool isReversedFace = data._reversedFaceIds.count( faceID );
9538 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
9539 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
9540 while ( fIt->more() )
9542 const SMDS_MeshElement* face = fIt->next();
9543 const int nbNodes = face->NbCornerNodes();
9544 nnVec.resize( nbNodes );
9546 degenEdgeInd.clear();
9547 isRiskySWOL.resize( nbNodes );
9548 size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9549 SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9550 for ( int iN = 0; iN < nbNodes; ++iN )
9552 const SMDS_MeshNode* n = nIt->next();
9553 _LayerEdge* edge = data._n2eMap[ n ];
9554 const int i = isReversedFace ? nbNodes-1-iN : iN;
9555 nnVec[ i ] = & edge->_nodes;
9556 maxZ = std::max( maxZ, nnVec[ i ]->size() );
9557 minZ = std::min( minZ, nnVec[ i ]->size() );
9558 //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9560 if ( helper.HasDegeneratedEdges() )
9561 nnSet.insert( nnVec[ i ]);
9566 if ( 0 < nnSet.size() && nnSet.size() < 3 )
9574 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9575 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9576 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
9578 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9580 for ( int iN = 0; iN < nbNodes; ++iN )
9581 if ( nnVec[ iN ]->size() < iZ+1 )
9582 degenEdgeInd.insert( iN );
9584 if ( degenEdgeInd.size() == 1 ) // PYRAM
9586 int i2 = *degenEdgeInd.begin();
9587 int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9588 int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9589 helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9590 (*nnVec[i1])[iZ ], (*nnVec[i0])[iZ ], (*nnVec[i2]).back());
9594 int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9595 helper.AddVolume( (*nnVec[ 0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9596 (*nnVec[ 1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9597 (*nnVec[ 2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9598 (*nnVec[ i3 ])[ iZ ]);
9606 for ( size_t iZ = 1; iZ < minZ; ++iZ )
9607 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9608 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9609 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
9610 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
9612 for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9614 for ( int iN = 0; iN < nbNodes; ++iN )
9615 if ( nnVec[ iN ]->size() < iZ+1 )
9616 degenEdgeInd.insert( iN );
9618 switch ( degenEdgeInd.size() )
9622 int i2 = *degenEdgeInd.begin();
9623 int i3 = *degenEdgeInd.rbegin();
9624 bool ok = ( i3 - i2 == 1 );
9625 if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9626 int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9627 int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9629 const SMDS_MeshElement* vol =
9630 helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9631 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9633 degenVols.push_back( vol );
9637 default: // degen HEX
9639 const SMDS_MeshElement* vol =
9640 helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9641 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9642 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9643 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9644 nnVec[0]->size() > iZ ? (*nnVec[0])[iZ] : nnVec[0]->back(),
9645 nnVec[1]->size() > iZ ? (*nnVec[1])[iZ] : nnVec[1]->back(),
9646 nnVec[2]->size() > iZ ? (*nnVec[2])[iZ] : nnVec[2]->back(),
9647 nnVec[3]->size() > iZ ? (*nnVec[3])[iZ] : nnVec[3]->back());
9648 degenVols.push_back( vol );
9655 return error("Not supported type of element", data._index);
9657 } // switch ( nbNodes )
9658 } // while ( fIt->more() )
9661 if ( !degenVols.empty() )
9663 SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9664 if ( !err || err->IsOK() )
9666 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9667 "Degenerated volumes created" ));
9668 err->myBadElements.insert( err->myBadElements.end(),
9669 degenVols.begin(),degenVols.end() );
9676 //================================================================================
9678 * \brief Shrink 2D mesh on faces to let space for inflated layers
9680 //================================================================================
9682 bool _ViscousBuilder::shrink(_SolidData& theData)
9684 // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9685 // _LayerEdge's inflated along FACE or EDGE)
9686 map< TGeomID, list< _SolidData* > > f2sdMap;
9687 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9689 _SolidData& data = _sdVec[i];
9690 TopTools_MapOfShape FFMap;
9691 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9692 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9693 if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9695 f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9697 if ( &data == &theData && FFMap.Add( (*s2s).second ))
9698 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9699 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9700 // by StdMeshers_QuadToTriaAdaptor
9701 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9703 SMESH_ProxyMesh::SubMesh* proxySub =
9704 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9705 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9706 while ( fIt->more() )
9707 proxySub->AddElement( fIt->next() );
9708 // as a result 3D algo will use elements from proxySub and not from smDS
9713 SMESH_MesherHelper helper( *_mesh );
9714 helper.ToFixNodeParameters( true );
9717 map< TGeomID, _Shrinker1D > e2shrMap;
9718 vector< _EdgesOnShape* > subEOS;
9719 vector< _LayerEdge* > lEdges;
9721 // loop on FACEs to srink mesh on
9722 map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9723 for ( ; f2sd != f2sdMap.end(); ++f2sd )
9725 list< _SolidData* > & dataList = f2sd->second;
9726 if ( dataList.front()->_n2eMap.empty() ||
9727 dataList.back() ->_n2eMap.empty() )
9728 continue; // not yet computed
9729 if ( dataList.front() != &theData &&
9730 dataList.back() != &theData )
9733 _SolidData& data = *dataList.front();
9734 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9735 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
9736 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9738 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9740 _shrinkedFaces.Add( F );
9741 helper.SetSubShape( F );
9743 // ===========================
9744 // Prepare data for shrinking
9745 // ===========================
9747 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9748 // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9749 vector < const SMDS_MeshNode* > smoothNodes;
9751 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9752 while ( nIt->more() )
9754 const SMDS_MeshNode* n = nIt->next();
9755 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9756 smoothNodes.push_back( n );
9759 // Find out face orientation
9761 const set<TGeomID> ignoreShapes;
9763 if ( !smoothNodes.empty() )
9765 vector<_Simplex> simplices;
9766 _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9767 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9768 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9769 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9770 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9774 // Find _LayerEdge's inflated along F
9778 SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9779 /*complexFirst=*/true); //!!!
9780 while ( subIt->more() )
9782 const TGeomID subID = subIt->next()->GetId();
9783 if ( data._noShrinkShapes.count( subID ))
9785 _EdgesOnShape* eos = data.GetShapeEdges( subID );
9786 if ( !eos || eos->_sWOL.IsNull() ) continue;
9788 subEOS.push_back( eos );
9790 for ( size_t i = 0; i < eos->_edges.size(); ++i )
9792 lEdges.push_back( eos->_edges[ i ] );
9793 prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9798 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9799 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9800 while ( fIt->more() )
9801 if ( const SMDS_MeshElement* f = fIt->next() )
9802 dumpChangeNodes( f );
9805 // Replace source nodes by target nodes in mesh faces to shrink
9806 dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9807 const SMDS_MeshNode* nodes[20];
9808 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9810 _EdgesOnShape& eos = * subEOS[ iS ];
9811 for ( size_t i = 0; i < eos._edges.size(); ++i )
9813 _LayerEdge& edge = *eos._edges[i];
9814 const SMDS_MeshNode* srcNode = edge._nodes[0];
9815 const SMDS_MeshNode* tgtNode = edge._nodes.back();
9816 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9817 while ( fIt->more() )
9819 const SMDS_MeshElement* f = fIt->next();
9820 if ( !smDS->Contains( f ))
9822 SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9823 for ( int iN = 0; nIt->more(); ++iN )
9825 const SMDS_MeshNode* n = nIt->next();
9826 nodes[iN] = ( n == srcNode ? tgtNode : n );
9828 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9829 dumpChangeNodes( f );
9835 // find out if a FACE is concave
9836 const bool isConcaveFace = isConcave( F, helper );
9838 // Create _SmoothNode's on face F
9839 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9841 dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9842 const bool sortSimplices = isConcaveFace;
9843 for ( size_t i = 0; i < smoothNodes.size(); ++i )
9845 const SMDS_MeshNode* n = smoothNodes[i];
9846 nodesToSmooth[ i ]._node = n;
9847 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9848 _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9849 // fix up incorrect uv of nodes on the FACE
9850 helper.GetNodeUV( F, n, 0, &isOkUV);
9855 //if ( nodesToSmooth.empty() ) continue;
9857 // Find EDGE's to shrink and set simpices to LayerEdge's
9858 set< _Shrinker1D* > eShri1D;
9860 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9862 _EdgesOnShape& eos = * subEOS[ iS ];
9863 if ( eos.SWOLType() == TopAbs_EDGE )
9865 SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9866 _Shrinker1D& srinker = e2shrMap[ edgeSM->GetId() ];
9867 eShri1D.insert( & srinker );
9868 srinker.AddEdge( eos._edges[0], eos, helper );
9869 VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9870 // restore params of nodes on EGDE if the EDGE has been already
9871 // srinked while srinking other FACE
9872 srinker.RestoreParams();
9874 for ( size_t i = 0; i < eos._edges.size(); ++i )
9876 _LayerEdge& edge = * eos._edges[i];
9877 _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9882 bool toFixTria = false; // to improve quality of trias by diagonal swap
9883 if ( isConcaveFace )
9885 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9886 if ( hasTria != hasQuad ) {
9887 toFixTria = hasTria;
9890 set<int> nbNodesSet;
9891 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9892 while ( fIt->more() && nbNodesSet.size() < 2 )
9893 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9894 toFixTria = ( *nbNodesSet.begin() == 3 );
9898 // ==================
9899 // Perform shrinking
9900 // ==================
9902 bool shrinked = true;
9903 int nbBad, shriStep=0, smooStep=0;
9904 _SmoothNode::SmoothType smoothType
9905 = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9906 SMESH_Comment errMsg;
9910 // Move boundary nodes (actually just set new UV)
9911 // -----------------------------------------------
9912 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9914 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9916 _EdgesOnShape& eos = * subEOS[ iS ];
9917 for ( size_t i = 0; i < eos._edges.size(); ++i )
9919 shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9924 // Move nodes on EDGE's
9925 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9926 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9927 for ( ; shr != eShri1D.end(); ++shr )
9928 (*shr)->Compute( /*set3D=*/false, helper );
9931 // -----------------
9932 int nbNoImpSteps = 0;
9935 while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9937 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9939 int oldBadNb = nbBad;
9942 // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9943 _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9944 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9946 moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9947 smooTy, /*set3D=*/isConcaveFace);
9949 if ( nbBad < oldBadNb )
9959 errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9960 if ( shriStep > 200 )
9961 errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9962 if ( !errMsg.empty() )
9965 // Fix narrow triangles by swapping diagonals
9966 // ---------------------------------------
9969 set<const SMDS_MeshNode*> usedNodes;
9970 fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9972 // update working data
9973 set<const SMDS_MeshNode*>::iterator n;
9974 for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9976 n = usedNodes.find( nodesToSmooth[ i ]._node );
9977 if ( n != usedNodes.end())
9979 _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9980 nodesToSmooth[ i ]._simplices,
9982 /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9983 usedNodes.erase( n );
9986 for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9988 n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9989 if ( n != usedNodes.end())
9991 _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9992 lEdges[i]->_simplices,
9994 usedNodes.erase( n );
9998 // TODO: check effect of this additional smooth
9999 // additional laplacian smooth to increase allowed shrink step
10000 // for ( int st = 1; st; --st )
10002 // dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10003 // for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10005 // nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10006 // _SmoothNode::LAPLACIAN,/*set3D=*/false);
10010 } // while ( shrinked )
10012 if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10015 SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10017 vector< const SMDS_MeshElement* > facesToRm;
10020 facesToRm.reserve( psm->NbElements() );
10021 for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10022 facesToRm.push_back( ite->next() );
10024 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10025 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10028 for ( size_t i = 0; i < facesToRm.size(); ++i )
10029 getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10033 TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10034 for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10035 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10036 nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10037 subEOS[iS]->_edges[i]->_nodes.end() );
10039 SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10040 while ( itn->more() ) {
10041 const SMDS_MeshNode* n = itn->next();
10042 if ( !nodesToKeep.count( n ))
10043 getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10046 // restore position and UV of target nodes
10048 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10049 for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10051 _LayerEdge* edge = subEOS[iS]->_edges[i];
10052 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10053 if ( edge->_pos.empty() ) continue;
10054 if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10056 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10057 pos->SetUParameter( edge->_pos[0].X() );
10058 pos->SetVParameter( edge->_pos[0].Y() );
10059 p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10063 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10064 pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10065 p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10067 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10068 dumpMove( tgtNode );
10070 // shrink EDGE sub-meshes and set proxy sub-meshes
10071 UVPtStructVec uvPtVec;
10072 set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10073 for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10075 _Shrinker1D* shr = (*shrIt);
10076 shr->Compute( /*set3D=*/true, helper );
10078 // set proxy mesh of EDGEs w/o layers
10079 map< double, const SMDS_MeshNode* > nodes;
10080 SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10081 // remove refinement nodes
10082 const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10083 const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10084 map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10085 if ( u2n->second == sn0 || u2n->second == sn1 )
10087 while ( u2n->second != tn0 && u2n->second != tn1 )
10089 nodes.erase( nodes.begin(), u2n );
10091 u2n = --nodes.end();
10092 if ( u2n->second == sn0 || u2n->second == sn1 )
10094 while ( u2n->second != tn0 && u2n->second != tn1 )
10096 nodes.erase( ++u2n, nodes.end() );
10098 // set proxy sub-mesh
10099 uvPtVec.resize( nodes.size() );
10100 u2n = nodes.begin();
10101 BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10102 for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10104 uvPtVec[ i ].node = u2n->second;
10105 uvPtVec[ i ].param = u2n->first;
10106 uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10108 StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10109 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10112 // set proxy mesh of EDGEs with layers
10113 vector< _LayerEdge* > edges;
10114 for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10116 _EdgesOnShape& eos = * subEOS[ iS ];
10117 if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10119 const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10120 data.SortOnEdge( E, eos._edges );
10123 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10124 if ( !eov->_edges.empty() )
10125 edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10127 edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10129 if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10130 if ( !eov->_edges.empty() )
10131 edges.push_back( eov->_edges[0] ); // on last VERTEX
10133 uvPtVec.resize( edges.size() );
10134 for ( size_t i = 0; i < edges.size(); ++i )
10136 uvPtVec[ i ].node = edges[i]->_nodes.back();
10137 uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10138 uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10140 BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10141 StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10142 StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10144 // temporary clear the FACE sub-mesh from faces made by refine()
10145 vector< const SMDS_MeshElement* > elems;
10146 elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10147 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10148 elems.push_back( ite->next() );
10149 for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10150 elems.push_back( ite->next() );
10153 // compute the mesh on the FACE
10154 sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10155 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10157 // re-fill proxy sub-meshes of the FACE
10158 for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10159 if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10160 for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10161 psm->AddElement( ite->next() );
10164 for ( size_t i = 0; i < elems.size(); ++i )
10165 smDS->AddElement( elems[i] );
10167 if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10168 return error( errMsg );
10170 } // end of re-meshing in case of failed smoothing
10173 // No wrongly shaped faces remain; final smooth. Set node XYZ.
10174 bool isStructuredFixed = false;
10175 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10176 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10177 if ( !isStructuredFixed )
10179 if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10180 fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10182 for ( int st = 3; st; --st )
10185 case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10186 case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10187 case 3: smoothType = _SmoothNode::ANGULAR; break;
10189 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10190 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10192 nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10193 smoothType,/*set3D=*/st==1 );
10198 if ( !getMeshDS()->IsEmbeddedMode() )
10199 // Log node movement
10200 for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10202 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10203 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10207 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10208 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10210 } // loop on FACES to srink mesh on
10213 // Replace source nodes by target nodes in shrinked mesh edges
10215 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10216 for ( ; e2shr != e2shrMap.end(); ++e2shr )
10217 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10222 //================================================================================
10224 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10226 //================================================================================
10228 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
10229 _EdgesOnShape& eos,
10230 SMESH_MesherHelper& helper,
10231 const SMESHDS_SubMesh* faceSubMesh)
10233 const SMDS_MeshNode* srcNode = edge._nodes[0];
10234 const SMDS_MeshNode* tgtNode = edge._nodes.back();
10236 if ( eos.SWOLType() == TopAbs_FACE )
10238 if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10241 return srcNode == tgtNode;
10243 gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() ); //helper.GetNodeUV( F, srcNode );
10244 gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10245 gp_Vec2d uvDir( srcUV, tgtUV );
10246 double uvLen = uvDir.Magnitude();
10248 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10251 edge._pos.resize(1);
10252 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10254 // set UV of source node to target node
10255 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10256 pos->SetUParameter( srcUV.X() );
10257 pos->SetVParameter( srcUV.Y() );
10259 else // _sWOL is TopAbs_EDGE
10261 if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10264 return srcNode == tgtNode;
10266 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10267 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10268 if ( !edgeSM || edgeSM->NbElements() == 0 )
10269 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10271 const SMDS_MeshNode* n2 = 0;
10272 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10273 while ( eIt->more() && !n2 )
10275 const SMDS_MeshElement* e = eIt->next();
10276 if ( !edgeSM->Contains(e)) continue;
10277 n2 = e->GetNode( 0 );
10278 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10281 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10283 double uSrc = helper.GetNodeU( E, srcNode, n2 );
10284 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10285 double u2 = helper.GetNodeU( E, n2, srcNode );
10289 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10291 // tgtNode is located so that it does not make faces with wrong orientation
10294 edge._pos.resize(1);
10295 edge._pos[0].SetCoord( U_TGT, uTgt );
10296 edge._pos[0].SetCoord( U_SRC, uSrc );
10297 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10299 edge._simplices.resize( 1 );
10300 edge._simplices[0]._nPrev = n2;
10302 // set U of source node to the target node
10303 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10304 pos->SetUParameter( uSrc );
10309 //================================================================================
10311 * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10313 //================================================================================
10315 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10317 if ( edge._nodes.size() == 1 )
10322 const SMDS_MeshNode* srcNode = edge._nodes[0];
10323 TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10324 if ( S.IsNull() ) return;
10328 switch ( S.ShapeType() )
10333 TopLoc_Location loc;
10334 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10335 if ( curve.IsNull() ) return;
10336 SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10337 p = curve->Value( ePos->GetUParameter() );
10340 case TopAbs_VERTEX:
10342 p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10347 getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10348 dumpMove( srcNode );
10352 //================================================================================
10354 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10356 //================================================================================
10358 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F,
10359 SMESH_MesherHelper& helper,
10362 set<const SMDS_MeshNode*> * involvedNodes)
10364 SMESH::Controls::AspectRatio qualifier;
10365 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10366 const double maxAspectRatio = is2D ? 4. : 2;
10367 _NodeCoordHelper xyz( F, helper, is2D );
10369 // find bad triangles
10371 vector< const SMDS_MeshElement* > badTrias;
10372 vector< double > badAspects;
10373 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
10374 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10375 while ( fIt->more() )
10377 const SMDS_MeshElement * f = fIt->next();
10378 if ( f->NbCornerNodes() != 3 ) continue;
10379 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10380 double aspect = qualifier.GetValue( points );
10381 if ( aspect > maxAspectRatio )
10383 badTrias.push_back( f );
10384 badAspects.push_back( aspect );
10389 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10390 SMDS_ElemIteratorPtr fIt = sm->GetElements();
10391 while ( fIt->more() )
10393 const SMDS_MeshElement * f = fIt->next();
10394 if ( f->NbCornerNodes() == 3 )
10395 dumpChangeNodes( f );
10399 if ( badTrias.empty() )
10402 // find couples of faces to swap diagonal
10404 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10405 vector< T2Trias > triaCouples;
10407 TIDSortedElemSet involvedFaces, emptySet;
10408 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10411 double aspRatio [3];
10414 if ( !involvedFaces.insert( badTrias[iTia] ).second )
10416 for ( int iP = 0; iP < 3; ++iP )
10417 points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10419 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10420 int bestCouple = -1;
10421 for ( int iSide = 0; iSide < 3; ++iSide )
10423 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10424 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10425 trias [iSide].first = badTrias[iTia];
10426 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10428 if (( ! trias[iSide].second ) ||
10429 ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10430 ( ! sm->Contains( trias[iSide].second )))
10433 // aspect ratio of an adjacent tria
10434 for ( int iP = 0; iP < 3; ++iP )
10435 points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10436 double aspectInit = qualifier.GetValue( points2 );
10438 // arrange nodes as after diag-swaping
10439 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10440 i3 = helper.WrapIndex( i1-1, 3 );
10442 i3 = helper.WrapIndex( i1+1, 3 );
10444 points1( 1+ iSide ) = points2( 1+ i3 );
10445 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
10447 // aspect ratio after diag-swaping
10448 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10449 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10452 // prevent inversion of a triangle
10453 gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10454 gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10455 if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10458 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10459 bestCouple = iSide;
10462 if ( bestCouple >= 0 )
10464 triaCouples.push_back( trias[bestCouple] );
10465 involvedFaces.insert ( trias[bestCouple].second );
10469 involvedFaces.erase( badTrias[iTia] );
10472 if ( triaCouples.empty() )
10477 SMESH_MeshEditor editor( helper.GetMesh() );
10478 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10479 for ( size_t i = 0; i < triaCouples.size(); ++i )
10481 dumpChangeNodes( triaCouples[i].first );
10482 dumpChangeNodes( triaCouples[i].second );
10483 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10486 if ( involvedNodes )
10487 for ( size_t i = 0; i < triaCouples.size(); ++i )
10489 involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10490 triaCouples[i].first->end_nodes() );
10491 involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10492 triaCouples[i].second->end_nodes() );
10495 // just for debug dump resulting triangles
10496 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10497 for ( size_t i = 0; i < triaCouples.size(); ++i )
10499 dumpChangeNodes( triaCouples[i].first );
10500 dumpChangeNodes( triaCouples[i].second );
10504 //================================================================================
10506 * \brief Move target node to it's final position on the FACE during shrinking
10508 //================================================================================
10510 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10511 const TopoDS_Face& F,
10512 _EdgesOnShape& eos,
10513 SMESH_MesherHelper& helper )
10515 if ( _pos.empty() )
10516 return false; // already at the target position
10518 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10520 if ( eos.SWOLType() == TopAbs_FACE )
10522 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
10523 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10524 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10525 const double uvLen = tgtUV.Distance( curUV );
10526 const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10528 // Select shrinking step such that not to make faces with wrong orientation.
10529 double stepSize = 1e100;
10530 for ( size_t i = 0; i < _simplices.size(); ++i )
10532 // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10533 gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10534 gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10535 gp_XY dirN = uvN2 - uvN1;
10536 double det = uvDir.Crossed( dirN );
10537 if ( Abs( det ) < std::numeric_limits<double>::min() ) continue;
10538 gp_XY dirN2Cur = curUV - uvN1;
10539 double step = dirN.Crossed( dirN2Cur ) / det;
10541 stepSize = Min( step, stepSize );
10544 if ( uvLen <= stepSize )
10549 else if ( stepSize > 0 )
10551 newUV = curUV + uvDir.XY() * stepSize * kSafe;
10557 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10558 pos->SetUParameter( newUV.X() );
10559 pos->SetVParameter( newUV.Y() );
10562 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10563 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10564 dumpMove( tgtNode );
10567 else // _sWOL is TopAbs_EDGE
10569 const TopoDS_Edge& E = TopoDS::Edge( eos._sWOL );
10570 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
10571 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10573 const double u2 = helper.GetNodeU( E, n2, tgtNode );
10574 const double uSrc = _pos[0].Coord( U_SRC );
10575 const double lenTgt = _pos[0].Coord( LEN_TGT );
10577 double newU = _pos[0].Coord( U_TGT );
10578 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10584 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10586 tgtPos->SetUParameter( newU );
10588 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10589 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10590 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10591 dumpMove( tgtNode );
10598 //================================================================================
10600 * \brief Perform smooth on the FACE
10601 * \retval bool - true if the node has been moved
10603 //================================================================================
10605 bool _SmoothNode::Smooth(int& nbBad,
10606 Handle(Geom_Surface)& surface,
10607 SMESH_MesherHelper& helper,
10608 const double refSign,
10612 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10614 // get uv of surrounding nodes
10615 vector<gp_XY> uv( _simplices.size() );
10616 for ( size_t i = 0; i < _simplices.size(); ++i )
10617 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10619 // compute new UV for the node
10620 gp_XY newPos (0,0);
10621 if ( how == TFI && _simplices.size() == 4 )
10624 for ( size_t i = 0; i < _simplices.size(); ++i )
10625 if ( _simplices[i]._nOpp )
10626 corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10628 throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10630 newPos = helper.calcTFI ( 0.5, 0.5,
10631 corners[0], corners[1], corners[2], corners[3],
10632 uv[1], uv[2], uv[3], uv[0] );
10634 else if ( how == ANGULAR )
10636 newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10638 else if ( how == CENTROIDAL && _simplices.size() > 3 )
10640 // average centers of diagonals wieghted with their reciprocal lengths
10641 if ( _simplices.size() == 4 )
10643 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10644 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10645 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10649 double sumWeight = 0;
10650 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10651 for ( int i = 0; i < nb; ++i )
10654 int iTo = i + _simplices.size() - 1;
10655 for ( int j = iFrom; j < iTo; ++j )
10657 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10658 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10660 newPos += w * ( uv[i]+uv[i2] );
10663 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10668 // Laplacian smooth
10669 for ( size_t i = 0; i < _simplices.size(); ++i )
10671 newPos /= _simplices.size();
10674 // count quality metrics (orientation) of triangles around the node
10675 int nbOkBefore = 0;
10676 gp_XY tgtUV = helper.GetNodeUV( face, _node );
10677 for ( size_t i = 0; i < _simplices.size(); ++i )
10678 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10681 for ( size_t i = 0; i < _simplices.size(); ++i )
10682 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10684 if ( nbOkAfter < nbOkBefore )
10686 nbBad += _simplices.size() - nbOkBefore;
10690 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10691 pos->SetUParameter( newPos.X() );
10692 pos->SetVParameter( newPos.Y() );
10699 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10700 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10704 nbBad += _simplices.size() - nbOkAfter;
10705 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10708 //================================================================================
10710 * \brief Computes new UV using angle based smoothing technic
10712 //================================================================================
10714 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10715 const gp_XY& uvToFix,
10716 const double refSign)
10718 uv.push_back( uv.front() );
10720 vector< gp_XY > edgeDir ( uv.size() );
10721 vector< double > edgeSize( uv.size() );
10722 for ( size_t i = 1; i < edgeDir.size(); ++i )
10724 edgeDir [i-1] = uv[i] - uv[i-1];
10725 edgeSize[i-1] = edgeDir[i-1].Modulus();
10726 if ( edgeSize[i-1] < numeric_limits<double>::min() )
10727 edgeDir[i-1].SetX( 100 );
10729 edgeDir[i-1] /= edgeSize[i-1] * refSign;
10731 edgeDir.back() = edgeDir.front();
10732 edgeSize.back() = edgeSize.front();
10736 double sumSize = 0;
10737 for ( size_t i = 1; i < edgeDir.size(); ++i )
10739 if ( edgeDir[i-1].X() > 1. ) continue;
10741 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10742 if ( i == edgeDir.size() ) break;
10744 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10745 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
10746 gp_XY bisec = norm1 + norm2;
10747 double bisecSize = bisec.Modulus();
10748 if ( bisecSize < numeric_limits<double>::min() )
10750 bisec = -edgeDir[i1] + edgeDir[i];
10751 bisecSize = bisec.Modulus();
10753 bisec /= bisecSize;
10755 gp_XY dirToN = uvToFix - p;
10756 double distToN = dirToN.Modulus();
10757 if ( bisec * dirToN < 0 )
10758 distToN = -distToN;
10760 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10762 sumSize += edgeSize[i1] + edgeSize[i];
10764 newPos /= /*nbEdges * */sumSize;
10768 //================================================================================
10770 * \brief Delete _SolidData
10772 //================================================================================
10774 _SolidData::~_SolidData()
10776 TNode2Edge::iterator n2e = _n2eMap.begin();
10777 for ( ; n2e != _n2eMap.end(); ++n2e )
10779 _LayerEdge* & e = n2e->second;
10782 delete e->_curvature;
10783 if ( e->_2neibors )
10784 delete e->_2neibors->_plnNorm;
10785 delete e->_2neibors;
10796 //================================================================================
10798 * \brief Keep a _LayerEdge inflated along the EDGE
10800 //================================================================================
10802 void _Shrinker1D::AddEdge( const _LayerEdge* e,
10803 _EdgesOnShape& eos,
10804 SMESH_MesherHelper& helper )
10807 if ( _nodes.empty() )
10809 _edges[0] = _edges[1] = 0;
10812 // check _LayerEdge
10813 if ( e == _edges[0] || e == _edges[1] )
10815 if ( eos.SWOLType() != TopAbs_EDGE )
10816 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10817 if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10818 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10820 // store _LayerEdge
10821 _geomEdge = TopoDS::Edge( eos._sWOL );
10823 BRep_Tool::Range( _geomEdge, f,l );
10824 double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10825 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10829 const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10830 const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10832 if ( _nodes.empty() )
10834 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10835 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10837 TopLoc_Location loc;
10838 Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10839 GeomAdaptor_Curve aCurve(C, f,l);
10840 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10842 int nbExpectNodes = eSubMesh->NbNodes();
10843 _initU .reserve( nbExpectNodes );
10844 _normPar.reserve( nbExpectNodes );
10845 _nodes .reserve( nbExpectNodes );
10846 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10847 while ( nIt->more() )
10849 const SMDS_MeshNode* node = nIt->next();
10850 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10851 node == tgtNode0 || node == tgtNode1 )
10852 continue; // refinement nodes
10853 _nodes.push_back( node );
10854 _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10855 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10856 _normPar.push_back( len / totLen );
10861 // remove target node of the _LayerEdge from _nodes
10862 size_t nbFound = 0;
10863 for ( size_t i = 0; i < _nodes.size(); ++i )
10864 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10865 _nodes[i] = 0, nbFound++;
10866 if ( nbFound == _nodes.size() )
10871 //================================================================================
10873 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10875 //================================================================================
10877 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10879 if ( _done || _nodes.empty())
10881 const _LayerEdge* e = _edges[0];
10882 if ( !e ) e = _edges[1];
10885 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10886 ( !_edges[1] || _edges[1]->_pos.empty() ));
10889 if ( set3D || _done )
10891 Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10892 GeomAdaptor_Curve aCurve(C, f,l);
10895 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10897 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10898 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10900 for ( size_t i = 0; i < _nodes.size(); ++i )
10902 if ( !_nodes[i] ) continue;
10903 double len = totLen * _normPar[i];
10904 GCPnts_AbscissaPoint discret( aCurve, len, f );
10905 if ( !discret.IsDone() )
10906 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10907 double u = discret.Parameter();
10908 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10909 pos->SetUParameter( u );
10910 gp_Pnt p = C->Value( u );
10911 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10916 BRep_Tool::Range( _geomEdge, f,l );
10918 f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10920 l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10922 for ( size_t i = 0; i < _nodes.size(); ++i )
10924 if ( !_nodes[i] ) continue;
10925 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10926 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10927 pos->SetUParameter( u );
10932 //================================================================================
10934 * \brief Restore initial parameters of nodes on EDGE
10936 //================================================================================
10938 void _Shrinker1D::RestoreParams()
10941 for ( size_t i = 0; i < _nodes.size(); ++i )
10943 if ( !_nodes[i] ) continue;
10944 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10945 pos->SetUParameter( _initU[i] );
10950 //================================================================================
10952 * \brief Replace source nodes by target nodes in shrinked mesh edges
10954 //================================================================================
10956 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10958 const SMDS_MeshNode* nodes[3];
10959 for ( int i = 0; i < 2; ++i )
10961 if ( !_edges[i] ) continue;
10963 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10964 if ( !eSubMesh ) return;
10965 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10966 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10967 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10968 while ( eIt->more() )
10970 const SMDS_MeshElement* e = eIt->next();
10971 if ( !eSubMesh->Contains( e ))
10973 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10974 for ( int iN = 0; iN < e->NbNodes(); ++iN )
10976 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10977 nodes[iN] = ( n == srcNode ? tgtNode : n );
10979 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10984 //================================================================================
10986 * \brief Creates 2D and 1D elements on boundaries of new prisms
10988 //================================================================================
10990 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
10992 SMESH_MesherHelper helper( *_mesh );
10994 vector< const SMDS_MeshNode* > faceNodes;
10996 //for ( size_t i = 0; i < _sdVec.size(); ++i )
10998 //_SolidData& data = _sdVec[i];
10999 TopTools_IndexedMapOfShape geomEdges;
11000 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11001 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11003 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11004 if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
11007 // Get _LayerEdge's based on E
11009 map< double, const SMDS_MeshNode* > u2nodes;
11010 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11013 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11014 TNode2Edge & n2eMap = data._n2eMap;
11015 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11017 //check if 2D elements are needed on E
11018 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11019 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11020 ledges.push_back( n2e->second );
11022 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11023 continue; // no layers on E
11024 ledges.push_back( n2eMap[ u2n->second ]);
11026 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11027 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11028 int nbSharedPyram = 0;
11029 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11030 while ( vIt->more() )
11032 const SMDS_MeshElement* v = vIt->next();
11033 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11035 if ( nbSharedPyram > 1 )
11036 continue; // not free border of the pyramid
11039 faceNodes.push_back( ledges[0]->_nodes[0] );
11040 faceNodes.push_back( ledges[1]->_nodes[0] );
11041 if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11042 if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11044 if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11045 continue; // faces already created
11047 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11048 ledges.push_back( n2eMap[ u2n->second ]);
11050 // Find out orientation and type of face to create
11052 bool reverse = false, isOnFace;
11054 map< TGeomID, TopoDS_Shape >::iterator e2f =
11055 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
11057 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11059 F = e2f->second.Oriented( TopAbs_FORWARD );
11060 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11061 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11062 reverse = !reverse, F.Reverse();
11063 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11064 reverse = !reverse;
11068 // find FACE with layers sharing E
11069 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
11070 while ( fIt->more() && F.IsNull() )
11072 const TopoDS_Shape* pF = fIt->next();
11073 if ( helper.IsSubShape( *pF, data._solid) &&
11074 !data._ignoreFaceIds.count( e2f->first ))
11078 // Find the sub-mesh to add new faces
11079 SMESHDS_SubMesh* sm = 0;
11081 sm = getMeshDS()->MeshElements( F );
11083 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11085 return error("error in addBoundaryElements()", data._index);
11088 const int dj1 = reverse ? 0 : 1;
11089 const int dj2 = reverse ? 1 : 0;
11090 for ( size_t j = 1; j < ledges.size(); ++j )
11092 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
11093 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
11094 if ( nn1.size() == nn2.size() )
11097 for ( size_t z = 1; z < nn1.size(); ++z )
11098 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11100 for ( size_t z = 1; z < nn1.size(); ++z )
11101 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11103 else if ( nn1.size() == 1 )
11106 for ( size_t z = 1; z < nn2.size(); ++z )
11107 sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11109 for ( size_t z = 1; z < nn2.size(); ++z )
11110 sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11115 for ( size_t z = 1; z < nn1.size(); ++z )
11116 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11118 for ( size_t z = 1; z < nn1.size(); ++z )
11119 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11124 for ( int isFirst = 0; isFirst < 2; ++isFirst )
11126 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11127 _EdgesOnShape* eos = data.GetShapeEdges( edge );
11128 if ( eos && eos->SWOLType() == TopAbs_EDGE )
11130 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
11131 if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11133 helper.SetSubShape( eos->_sWOL );
11134 helper.SetElementsOnShape( true );
11135 for ( size_t z = 1; z < nn.size(); ++z )
11136 helper.AddEdge( nn[z-1], nn[z] );
11140 } // loop on EDGE's
11141 } // loop on _SolidData's