Salome HOME
IPAL54401: Offset dialog bug
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.hxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File      : SMESH_MeshEditor.hxx
24 // Created   : Mon Apr 12 14:56:19 2004
25 // Author    : Edward AGAPOV (eap)
26 // Module    : SMESH
27 //
28 #ifndef SMESH_MeshEditor_HeaderFile
29 #define SMESH_MeshEditor_HeaderFile
30
31 #include "SMESH_SMESH.hxx"
32
33 #include "SMESH_Controls.hxx"
34 #include "SMESH_TypeDefs.hxx"
35 #include "SMESH_ComputeError.hxx"
36
37 #include <utilities.h>
38
39 #include <TColStd_HSequenceOfReal.hxx>
40 #include <gp_Dir.hxx>
41
42 #include <list>
43 #include <map>
44 #include <set>
45
46 class SMDS_MeshElement;
47 class SMDS_MeshFace;
48 class SMDS_MeshNode;
49 class SMESHDS_Group;
50 class SMESHDS_Mesh;
51 class SMESHDS_SubMesh;
52 class SMESH_ElementSearcher;
53 class SMESH_Group;
54 class SMESH_Mesh;
55 class SMESH_MesherHelper;
56 class SMESH_NodeSearcher;
57 class SMESH_subMesh;
58 class TopoDS_Edge;
59 class TopoDS_Shape;
60 class TopoDS_Vertex;
61 class gp_Ax1;
62 class gp_Pnt;
63 class gp_Vec;
64
65 // ============================================================
66 /*!
67  * \brief Editor of a mesh
68  */
69 // ============================================================
70
71 class SMESH_EXPORT SMESH_MeshEditor
72 {
73 public:
74
75   SMESH_MeshEditor( SMESH_Mesh* theMesh );
76
77   SMESH_Mesh   *                 GetMesh() { return myMesh; }
78   SMESHDS_Mesh *                 GetMeshDS();
79
80   const SMESH_SequenceOfElemPtr& GetLastCreatedNodes() const { return myLastCreatedNodes; }
81   const SMESH_SequenceOfElemPtr& GetLastCreatedElems() const { return myLastCreatedElems; }
82   void                           ClearLastCreated();
83   SMESH_ComputeErrorPtr &        GetError() { return myError; }
84
85   // --------------------------------------------------------------------------------
86   struct ElemFeatures //!< Features of element to create
87   {
88     SMDSAbs_ElementType               myType;
89     bool                              myIsPoly, myIsQuad;
90     int                               myID;
91     double                            myBallDiameter;
92     std::vector<int>                  myPolyhedQuantities;
93     std::vector<const SMDS_MeshNode*> myNodes; // not managed by ElemFeatures
94
95     SMESH_EXPORT ElemFeatures( SMDSAbs_ElementType type=SMDSAbs_All, bool isPoly=false, bool isQuad=false )
96       :myType( type ), myIsPoly(isPoly), myIsQuad(isQuad), myID(-1), myBallDiameter(0) {}
97
98     SMESH_EXPORT ElemFeatures& Init( SMDSAbs_ElementType type, bool isPoly=false, bool isQuad=false )
99     { myType = type; myIsPoly = isPoly; myIsQuad = isQuad; return *this; }
100
101     SMESH_EXPORT ElemFeatures& Init( const SMDS_MeshElement* elem, bool basicOnly=true );
102
103     SMESH_EXPORT ElemFeatures& Init( double diameter )
104     { myType = SMDSAbs_Ball; myBallDiameter = diameter; return *this; }
105
106     SMESH_EXPORT ElemFeatures& Init( std::vector<int>& quanities, bool isQuad=false )
107     { myType = SMDSAbs_Volume; myIsPoly = 1; myIsQuad = isQuad;
108       myPolyhedQuantities.swap( quanities ); return *this; }
109
110     SMESH_EXPORT ElemFeatures& Init( const std::vector<int>& quanities, bool isQuad=false )
111     { myType = SMDSAbs_Volume; myIsPoly = 1; myIsQuad = isQuad;
112       myPolyhedQuantities = quanities; return *this; }
113
114     SMESH_EXPORT ElemFeatures& SetPoly(bool isPoly) { myIsPoly = isPoly; return *this; }
115     SMESH_EXPORT ElemFeatures& SetQuad(bool isQuad) { myIsQuad = isQuad; return *this; }
116     SMESH_EXPORT ElemFeatures& SetID  (int ID)      { myID = ID; return *this; }
117   };
118
119   /*!
120    * \brief Add element
121    */
122   SMDS_MeshElement* AddElement(const std::vector<const SMDS_MeshNode*> & nodes,
123                                const ElemFeatures&                       features);
124   /*!
125    * \brief Add element
126    */
127   SMDS_MeshElement* AddElement(const std::vector<int> & nodeIDs,
128                                const ElemFeatures&      features);
129
130   int Remove (const std::list< int >& theElemIDs, const bool isNodes);
131   // Remove a node or an element.
132   // Modify a compute state of sub-meshes which become empty
133
134   void Create0DElementsOnAllNodes( const TIDSortedElemSet& elements,
135                                    TIDSortedElemSet&       all0DElems,
136                                    const bool              duplicateElements);
137   // Create 0D elements on all nodes of the given. \a all0DElems returns
138   // all 0D elements found or created on nodes of \a elements
139
140   bool InverseDiag (const SMDS_MeshElement * theTria1,
141                     const SMDS_MeshElement * theTria2 );
142   // Replace two neighbour triangles with ones built on the same 4 nodes
143   // but having other common link.
144   // Return False if args are improper
145
146   bool InverseDiag (const SMDS_MeshNode * theNode1,
147                     const SMDS_MeshNode * theNode2 );
148   // Replace two neighbour triangles sharing theNode1-theNode2 link
149   // with ones built on the same 4 nodes but having other common link.
150   // Return false if proper faces not found
151
152   bool DeleteDiag (const SMDS_MeshNode * theNode1,
153                    const SMDS_MeshNode * theNode2 );
154   // Replace two neighbour triangles sharing theNode1-theNode2 link
155   // with a quadrangle built on the same 4 nodes.
156   // Return false if proper faces not found
157
158   bool Reorient (const SMDS_MeshElement * theElement);
159   // Reverse theElement orientation
160
161   int Reorient2D (TIDSortedElemSet &       theFaces,
162                   const gp_Dir&            theDirection,
163                   const SMDS_MeshElement * theFace);
164   // Reverse theFaces whose orientation to be same as that of theFace
165   // oriented according to theDirection. Return nb of reoriented faces
166
167   int Reorient2DBy3D (TIDSortedElemSet & theFaces,
168                       TIDSortedElemSet & theVolumes,
169                       const bool         theOutsideNormal);
170   // Reorient faces basing on orientation of adjacent volumes.
171   // Return nb of reoriented faces
172
173   /*!
174    * \brief Fuse neighbour triangles into quadrangles.
175    * \param theElems     - The triangles to be fused.
176    * \param theCriterion - Is used to choose a neighbour to fuse with.
177    * \param theMaxAngle  - Is a max angle between element normals at which fusion
178    *                       is still performed; theMaxAngle is measured in radians.
179    * \return bool - Success or not.
180    */
181   bool TriToQuad (TIDSortedElemSet &                   theElems,
182                   SMESH::Controls::NumericalFunctorPtr theCriterion,
183                   const double                         theMaxAngle);
184   /*!
185    * \brief Split quadrangles into triangles.
186    * \param theElems     - The faces to be split.
187    * \param theCriterion - Is used to choose a diagonal for splitting.
188    * \return bool - Success or not.
189    */
190   bool QuadToTri (TIDSortedElemSet &                   theElems,
191                   SMESH::Controls::NumericalFunctorPtr theCriterion);
192   /*!
193    * \brief Split quadrangles into triangles.
194    * \param theElems  - The faces to be split.
195    * \param the13Diag - Is used to choose a diagonal for splitting.
196    * \return bool - Success or not.
197    */
198   bool QuadToTri (TIDSortedElemSet & theElems,
199                   const bool         the13Diag);
200   /*!
201    * \brief Split each of given quadrangles into 4 triangles.
202    * \param theElems - The faces to be split. If empty all faces are split.
203    */
204   void QuadTo4Tri (TIDSortedElemSet & theElems);
205
206   /*!
207    * \brief Find better diagonal for splitting.
208    * \param theQuad      - The face to find better splitting of.
209    * \param theCriterion - Is used to choose a diagonal for splitting.
210    * \return int - 1 for 1-3 diagonal, 2 for 2-4, -1 - for errors.
211    */
212   int BestSplit (const SMDS_MeshElement*              theQuad,
213                  SMESH::Controls::NumericalFunctorPtr theCriterion);
214
215
216   typedef std::map < const SMDS_MeshElement*, int, TIDCompare > TFacetOfElem;
217
218     //!<2nd arg of SplitVolumes()
219   enum SplitVolumToTetraFlags { HEXA_TO_5 = 1, // split into tetrahedra
220                                 HEXA_TO_6,
221                                 HEXA_TO_24,
222                                 HEXA_TO_2_PRISMS, // split into prisms
223                                 HEXA_TO_4_PRISMS };
224   /*!
225    * \brief Split volumic elements into tetrahedra or prisms.
226    *        If facet ID < 0, element is split into tetrahedra,
227    *        else a hexahedron is split into prisms so that the given facet is
228    *        split into triangles
229    */
230   void SplitVolumes (const TFacetOfElem & theElems, const int theMethodFlags);
231
232   /*!
233    * \brief For hexahedra that will be split into prisms, finds facets to
234    *        split into triangles
235    *  \param [in,out] theHexas - the hexahedra
236    *  \param [in]     theFacetNormal - facet normal
237    *  \param [out]    theFacets - the hexahedra and found facet IDs
238    */
239   void GetHexaFacetsToSplit( TIDSortedElemSet& theHexas,
240                              const gp_Ax1&     theFacetNormal,
241                              TFacetOfElem &    theFacets);
242
243   /*!
244    * \brief Split bi-quadratic elements into linear ones without creation of additional nodes
245    *   - bi-quadratic triangle will be split into 3 linear quadrangles;
246    *   - bi-quadratic quadrangle will be split into 4 linear quadrangles;
247    *   - tri-quadratic hexahedron will be split into 8 linear hexahedra;
248    *   Quadratic elements of lower dimension  adjacent to the split bi-quadratic element
249    *   will be split in order to keep the mesh conformal.
250    *  \param elems - elements to split
251    */
252   void SplitBiQuadraticIntoLinear(TIDSortedElemSet& theElems);
253
254   enum SmoothMethod { LAPLACIAN = 0, CENTROIDAL };
255
256   void Smooth (TIDSortedElemSet &               theElements,
257                std::set<const SMDS_MeshNode*> & theFixedNodes,
258                const SmoothMethod               theSmoothMethod,
259                const int                        theNbIterations,
260                double                           theTgtAspectRatio = 1.0,
261                const bool                       the2D = true);
262   // Smooth theElements using theSmoothMethod during theNbIterations
263   // or until a worst element has aspect ratio <= theTgtAspectRatio.
264   // Aspect Ratio varies in range [1.0, inf].
265   // If theElements is empty, the whole mesh is smoothed.
266   // theFixedNodes contains additionally fixed nodes. Nodes built
267   // on edges and boundary nodes are always fixed.
268   // If the2D, smoothing is performed using UV parameters of nodes
269   // on geometrical faces
270
271   typedef TIDTypeCompare TElemSort;
272   typedef std::map < const SMDS_MeshElement*,
273     std::list<const SMDS_MeshElement*>, TElemSort >                        TTElemOfElemListMap;
274   typedef std::map<const SMDS_MeshNode*, std::list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
275   typedef TNodeOfNodeListMap::iterator                                     TNodeOfNodeListMapItr;
276   typedef std::vector<TNodeOfNodeListMapItr>                               TVecOfNnlmiMap;
277   typedef std::map<const SMDS_MeshElement*, TVecOfNnlmiMap, TElemSort >    TElemOfVecOfNnlmiMap;
278   typedef std::auto_ptr< std::list<int> > PGroupIDs;
279
280   PGroupIDs RotationSweep (TIDSortedElemSet   theElements[2],
281                            const gp_Ax1&      theAxis,
282                            const double       theAngle,
283                            const int          theNbSteps,
284                            const double       theToler,
285                            const bool         theMakeGroups,
286                            const bool         theMakeWalls=true);
287   // Generate new elements by rotation of theElements around theAxis
288   // by theAngle by theNbSteps
289
290   /*!
291    * Flags of extrusion.
292    * BOUNDARY: create or not boundary for result of extrusion
293    * SEW:      try to use existing nodes or create new nodes in any case
294    * GROUPS:   to create groups
295    * BY_AVG_NORMAL: step size is measured along average normal to elements,
296    *                else step size is measured along average normal of any element
297    * USE_INPUT_ELEMS_ONLY: to use only input elements to compute extrusion direction
298    *                       for ExtrusionByNormal()
299    * SCALE_LINEAR_VARIATION: to make linear variation of scale factors
300    */
301   enum ExtrusionFlags {
302     EXTRUSION_FLAG_BOUNDARY = 0x01,
303     EXTRUSION_FLAG_SEW = 0x02,
304     EXTRUSION_FLAG_GROUPS = 0x04,
305     EXTRUSION_FLAG_BY_AVG_NORMAL = 0x08,
306     EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY = 0x10,
307     EXTRUSION_FLAG_SCALE_LINEAR_VARIATION = 0x20
308   };
309
310   /*!
311    * Generator of nodes for extrusion functionality
312    */
313   class SMESH_EXPORT ExtrusParam
314   {
315     gp_Dir                          myDir;   // direction of extrusion
316     Handle(TColStd_HSequenceOfReal) mySteps; // magnitudes for each step
317     std::vector<double>             myScales, myMediumScales;// scale factors
318     gp_XYZ                          myBaseP; // scaling center
319     SMESH_SequenceOfNode            myNodes; // nodes for using in sewing
320     int                             myFlags; // see ExtrusionFlags
321     double                          myTolerance; // tolerance for sewing nodes
322     const TIDSortedElemSet*         myElemsToUse; // elements to use for extrusion by normal
323
324     int (ExtrusParam::*myMakeNodesFun)(SMESHDS_Mesh*                     mesh,
325                                        const SMDS_MeshNode*              srcNode,
326                                        std::list<const SMDS_MeshNode*> & newNodes,
327                                        const bool                        makeMediumNodes);
328
329   public:
330     ExtrusParam( const gp_Vec&                   theStep,
331                  const int                       theNbSteps,
332                  const std::list<double>&        theScales,
333                  const gp_XYZ*                   theBaseP,
334                  const int                       theFlags = 0,
335                  const double                    theTolerance = 1e-6);
336     ExtrusParam( const gp_Dir&                   theDir,
337                  Handle(TColStd_HSequenceOfReal) theSteps,
338                  const int                       theFlags = 0,
339                  const double                    theTolerance = 1e-6);
340     ExtrusParam( const double                    theStep,
341                  const int                       theNbSteps,
342                  const int                       theFlags,
343                  const int                       theDim); // for extrusion by normal
344
345     SMESH_SequenceOfNode& ChangeNodes() { return myNodes; }
346     int& Flags()                   { return myFlags; }
347     bool ToMakeBoundary()    const { return myFlags & EXTRUSION_FLAG_BOUNDARY; }
348     bool ToMakeGroups()      const { return myFlags & EXTRUSION_FLAG_GROUPS; }
349     bool ToUseInpElemsOnly() const { return myFlags & EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY; }
350     bool IsLinearVariation() const { return myFlags & EXTRUSION_FLAG_SCALE_LINEAR_VARIATION; }
351     int  NbSteps()           const { return mySteps->Length(); }
352
353     // stores elements to use for extrusion by normal, depending on
354     // state of EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY flag;
355     // define myBaseP for scaling
356     void SetElementsToUse( const TIDSortedElemSet& elems, const TIDSortedElemSet& nodes );
357
358     // creates nodes and returns number of nodes added in \a newNodes
359     int MakeNodes( SMESHDS_Mesh*                     mesh,
360                    const SMDS_MeshNode*              srcNode,
361                    std::list<const SMDS_MeshNode*> & newNodes,
362                    const bool                        makeMediumNodes)
363     {
364       return (this->*myMakeNodesFun)( mesh, srcNode, newNodes, makeMediumNodes );
365     }
366   private:
367
368     int makeNodesByDir( SMESHDS_Mesh*                     mesh,
369                         const SMDS_MeshNode*              srcNode,
370                         std::list<const SMDS_MeshNode*> & newNodes,
371                         const bool                        makeMediumNodes);
372     int makeNodesByDirAndSew( SMESHDS_Mesh*                     mesh,
373                               const SMDS_MeshNode*              srcNode,
374                               std::list<const SMDS_MeshNode*> & newNodes,
375                               const bool                        makeMediumNodes);
376     int makeNodesByNormal2D( SMESHDS_Mesh*                     mesh,
377                              const SMDS_MeshNode*              srcNode,
378                              std::list<const SMDS_MeshNode*> & newNodes,
379                              const bool                        makeMediumNodes);
380     int makeNodesByNormal1D( SMESHDS_Mesh*                     mesh,
381                              const SMDS_MeshNode*              srcNode,
382                              std::list<const SMDS_MeshNode*> & newNodes,
383                              const bool                        makeMediumNodes);
384     // step iteration
385     void   beginStepIter( bool withMediumNodes );
386     bool   moreSteps();
387     double nextStep();
388     std::vector< double > myCurSteps;
389     bool                  myWithMediumNodes;
390     int                   myNextStep;
391   };
392
393   /*!
394    * Generate new elements by extrusion of theElements
395    * It is a method used in .idl file. All functionality
396    * is implemented in the next method (see below) which
397    * is used in the current method.
398    * @param theElems - list of elements for extrusion
399    * @param newElemsMap returns history of extrusion
400    * @param theFlags set flags for performing extrusion (see description
401    *   of enum ExtrusionFlags for additional information)
402    * @param theTolerance - uses for comparing locations of nodes if flag
403    *   EXTRUSION_FLAG_SEW is set
404    */
405   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
406                             const gp_Vec&        theStep,
407                             const int            theNbSteps,
408                             TTElemOfElemListMap& newElemsMap,
409                             const int            theFlags,
410                             const double         theTolerance = 1.e-6);
411   
412   /*!
413    * Generate new elements by extrusion of theElements
414    * @param theElems - list of elements for extrusion
415    * @param newElemsMap returns history of extrusion
416    * @param theFlags set flags for performing extrusion (see description
417    *   of enum ExtrusionFlags for additional information)
418    * @param theTolerance - uses for comparing locations of nodes if flag
419    *   EXTRUSION_FLAG_SEW is set
420    * @param theParams - special structure for manage of extrusion
421    */
422   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
423                             ExtrusParam&         theParams,
424                             TTElemOfElemListMap& newElemsMap);
425
426
427   // Generate new elements by extrusion of theElements 
428   // by theStep by theNbSteps
429
430   enum Extrusion_Error {
431     EXTR_OK,
432     EXTR_NO_ELEMENTS, 
433     EXTR_PATH_NOT_EDGE,
434     EXTR_BAD_PATH_SHAPE,
435     EXTR_BAD_STARTING_NODE,
436     EXTR_BAD_ANGLES_NUMBER,
437     EXTR_CANT_GET_TANGENT
438     };
439   
440   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet     theElements[2],
441                                        SMESH_subMesh*       theTrackPattern,
442                                        const SMDS_MeshNode* theNodeStart,
443                                        const bool           theHasAngles,
444                                        std::list<double>&   theAngles,
445                                        const bool           theLinearVariation,
446                                        const bool           theHasRefPoint,
447                                        const gp_Pnt&        theRefPoint,
448                                        const bool           theMakeGroups);
449   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet     theElements[2],
450                                        SMESH_Mesh*          theTrackPattern,
451                                        const SMDS_MeshNode* theNodeStart,
452                                        const bool           theHasAngles,
453                                        std::list<double>&   theAngles,
454                                        const bool           theLinearVariation,
455                                        const bool           theHasRefPoint,
456                                        const gp_Pnt&        theRefPoint,
457                                        const bool           theMakeGroups);
458   // Generate new elements by extrusion of theElements along path given by theTrackPattern,
459   // theHasAngles are the rotation angles, base point can be given by theRefPoint
460
461   PGroupIDs Transform (TIDSortedElemSet & theElements,
462                        const gp_Trsf&     theTrsf,
463                        const bool         theCopy,
464                        const bool         theMakeGroups,
465                        SMESH_Mesh*        theTargetMesh=0);
466   // Move or copy theElements applying theTrsf to their nodes
467
468   PGroupIDs Offset( TIDSortedElemSet & theElements,
469                     const double       theValue,
470                     SMESH_Mesh*        theTgtMesh,
471                     const bool         theMakeGroups,
472                     const bool         theCopyElements,
473                     const bool         theFixSelfIntersection);
474   // Make an offset mesh from a source 2D mesh
475
476   typedef std::list< std::list< const SMDS_MeshNode* > > TListOfListOfNodes;
477
478   void FindCoincidentNodes (TIDSortedNodeSet &   theNodes,
479                             const double         theTolerance,
480                             TListOfListOfNodes & theGroupsOfNodes,
481                             bool                 theSeparateCornersAndMedium);
482   // Return list of group of nodes close to each other within theTolerance.
483   // Search among theNodes or in the whole mesh if theNodes is empty.
484
485   void MergeNodes (TListOfListOfNodes & theNodeGroups,
486                    const bool           theAvoidMakingHoles = false);
487   // In each group, the cdr of nodes are substituted by the first one
488   // in all elements.
489
490   typedef std::list< std::list< int > > TListOfListOfElementsID;
491
492   void FindEqualElements(TIDSortedElemSet &        theElements,
493                          TListOfListOfElementsID & theGroupsOfElementsID);
494   // Return list of group of elements build on the same nodes.
495   // Search among theElements or in the whole mesh if theElements is empty.
496
497   void MergeElements(TListOfListOfElementsID & theGroupsOfElementsID);
498   // In each group remove all but first of elements.
499
500   void MergeEqualElements();
501   // Remove all but one of elements built on the same nodes.
502   // Return nb of successfully merged groups.
503
504   int SimplifyFace (const std::vector<const SMDS_MeshNode *>& faceNodes,
505                     std::vector<const SMDS_MeshNode *>&       poly_nodes,
506                     std::vector<int>&                         quantities) const;
507   // Split face, defined by <faceNodes>, into several faces by repeating nodes.
508   // Is used by MergeNodes()
509
510   static bool CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
511                                    const SMDS_MeshNode* theNode2,
512                                    const SMDS_MeshNode* theNode3 = 0);
513   // Return true if the three nodes are on a free border
514
515   static bool FindFreeBorder (const SMDS_MeshNode*                  theFirstNode,
516                               const SMDS_MeshNode*                  theSecondNode,
517                               const SMDS_MeshNode*                  theLastNode,
518                               std::list< const SMDS_MeshNode* > &   theNodes,
519                               std::list< const SMDS_MeshElement* >& theFaces);
520   // Return nodes and faces of a free border if found 
521
522   enum Sew_Error {
523     SEW_OK,
524     // for SewFreeBorder()
525     SEW_BORDER1_NOT_FOUND,
526     SEW_BORDER2_NOT_FOUND,
527     SEW_BOTH_BORDERS_NOT_FOUND,
528     SEW_BAD_SIDE_NODES,
529     SEW_VOLUMES_TO_SPLIT,
530     // for SewSideElements()
531     SEW_DIFF_NB_OF_ELEMENTS,
532     SEW_TOPO_DIFF_SETS_OF_ELEMENTS,
533     SEW_BAD_SIDE1_NODES,
534     SEW_BAD_SIDE2_NODES,
535     SEW_INTERNAL_ERROR
536     };
537     
538
539   Sew_Error SewFreeBorder (const SMDS_MeshNode* theBorderFirstNode,
540                            const SMDS_MeshNode* theBorderSecondNode,
541                            const SMDS_MeshNode* theBorderLastNode,
542                            const SMDS_MeshNode* theSide2FirstNode,
543                            const SMDS_MeshNode* theSide2SecondNode,
544                            const SMDS_MeshNode* theSide2ThirdNode = 0,
545                            const bool           theSide2IsFreeBorder = true,
546                            const bool           toCreatePolygons = false,
547                            const bool           toCreatePolyedrs = false);
548   // Sew the free border to the side2 by replacing nodes in
549   // elements on the free border with nodes of the elements
550   // of the side 2. If nb of links in the free border and
551   // between theSide2FirstNode and theSide2LastNode are different,
552   // additional nodes are inserted on a link provided that no
553   // volume elements share the split link.
554   // The side 2 is a free border if theSide2IsFreeBorder == true.
555   // Sewing is performed between the given first, second and last
556   // nodes on the sides.
557   // theBorderFirstNode is merged with theSide2FirstNode.
558   // if (!theSide2IsFreeBorder) then theSide2SecondNode gives
559   // the last node on the side 2, which will be merged with
560   // theBorderLastNode.
561   // if (theSide2IsFreeBorder) then theSide2SecondNode will
562   // be merged with theBorderSecondNode.
563   // if (theSide2IsFreeBorder && theSide2ThirdNode == 0) then
564   // the 2 free borders are sewn link by link and no additional
565   // nodes are inserted.
566   // Return false, if sewing failed.
567
568   Sew_Error SewSideElements (TIDSortedElemSet&    theSide1,
569                              TIDSortedElemSet&    theSide2,
570                              const SMDS_MeshNode* theFirstNode1ToMerge,
571                              const SMDS_MeshNode* theFirstNode2ToMerge,
572                              const SMDS_MeshNode* theSecondNode1ToMerge,
573                              const SMDS_MeshNode* theSecondNode2ToMerge);
574   // Sew two sides of a mesh. Nodes belonging to theSide1 are
575   // merged with nodes of elements of theSide2.
576   // Number of elements in theSide1 and in theSide2 must be
577   // equal and they should have similar node connectivity.
578   // The nodes to merge should belong to side s borders and
579   // the first node should be linked to the second.
580
581   void InsertNodesIntoLink(const SMDS_MeshElement*          theFace,
582                            const SMDS_MeshNode*             theBetweenNode1,
583                            const SMDS_MeshNode*             theBetweenNode2,
584                            std::list<const SMDS_MeshNode*>& theNodesToInsert,
585                            const bool                       toCreatePoly = false);
586   // insert theNodesToInsert into theFace between theBetweenNode1 and theBetweenNode2.
587   // If toCreatePoly is true, replace theFace by polygon, else split theFace.
588
589   void UpdateVolumes (const SMDS_MeshNode*             theBetweenNode1,
590                       const SMDS_MeshNode*             theBetweenNode2,
591                       std::list<const SMDS_MeshNode*>& theNodesToInsert);
592   // insert theNodesToInsert into all volumes, containing link
593   // theBetweenNode1 - theBetweenNode2, between theBetweenNode1 and theBetweenNode2.
594
595   void ConvertToQuadratic(const bool theForce3d, const bool theToBiQuad);
596   void ConvertToQuadratic(const bool theForce3d,
597                           TIDSortedElemSet& theElements, const bool theToBiQuad);
598   // Converts all mesh to quadratic or bi-quadratic one, deletes old elements, 
599   // replacing them with quadratic or bi-quadratic ones with the same id.
600   // If theForce3d = 1; this results in the medium node lying at the 
601   // middle of the line segments connecting start and end node of a mesh element.
602   // If theForce3d = 0; this results in the medium node lying at the 
603   // geometrical edge from which the mesh element is built.
604
605   bool ConvertFromQuadratic();
606   void ConvertFromQuadratic(TIDSortedElemSet& theElements);
607   // Converts all mesh from quadratic to ordinary ones, deletes old quadratic elements, replacing 
608   // them with ordinary mesh elements with the same id.
609   // Returns true in case of success, false otherwise.
610
611   static void AddToSameGroups (const SMDS_MeshElement* elemToAdd,
612                                const SMDS_MeshElement* elemInGroups,
613                                SMESHDS_Mesh *          aMesh);
614   // Add elemToAdd to the all groups the elemInGroups belongs to
615
616   static void RemoveElemFromGroups (const SMDS_MeshElement* element,
617                                     SMESHDS_Mesh *          aMesh);
618   // remove element from the all groups
619
620   static void ReplaceElemInGroups (const SMDS_MeshElement* elemToRm,
621                                    const SMDS_MeshElement* elemToAdd,
622                                    SMESHDS_Mesh *          aMesh);
623   // replace elemToRm by elemToAdd in the all groups
624
625   static void ReplaceElemInGroups (const SMDS_MeshElement*                     elemToRm,
626                                    const std::vector<const SMDS_MeshElement*>& elemToAdd,
627                                    SMESHDS_Mesh *                              aMesh);
628   // replace elemToRm by elemToAdd in the all groups
629
630   /*!
631    * \brief Return nodes linked to the given one in elements of the type
632    */
633   static void GetLinkedNodes( const SMDS_MeshNode* node,
634                               TIDSortedElemSet &   linkedNodes,
635                               SMDSAbs_ElementType  type = SMDSAbs_All );
636
637   /*!
638    * \brief Find corresponding nodes in two sets of faces 
639     * \param theSide1 - first face set
640     * \param theSide2 - second first face
641     * \param theFirstNode1 - a boundary node of set 1
642     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
643     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
644     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
645     * \param nReplaceMap - output map of corresponding nodes
646     * \return Sew_Error  - is a success or not
647    */
648   static Sew_Error FindMatchingNodes(std::set<const SMDS_MeshElement*>& theSide1,
649                                      std::set<const SMDS_MeshElement*>& theSide2,
650                                      const SMDS_MeshNode*               theFirstNode1,
651                                      const SMDS_MeshNode*               theFirstNode2,
652                                      const SMDS_MeshNode*               theSecondNode1,
653                                      const SMDS_MeshNode*               theSecondNode2,
654                                      TNodeNodeMap &                     theNodeReplaceMap);
655
656   /*!
657    * \brief Returns true if given node is medium
658     * \param n - node to check
659     * \param typeToCheck - type of elements containing the node to ask about node status
660     * \return bool - check result
661    */
662   static bool IsMedium(const SMDS_MeshNode*      node,
663                        const SMDSAbs_ElementType typeToCheck = SMDSAbs_All);
664
665   int FindShape (const SMDS_MeshElement * theElem);
666   // Return an index of the shape theElem is on
667   // or zero if a shape not found
668
669   void DoubleElements( const TIDSortedElemSet& theElements );
670
671   bool DoubleNodes( const std::list< int >& theListOfNodes, 
672                     const std::list< int >& theListOfModifiedElems );
673   
674   bool DoubleNodes( const TIDSortedElemSet& theElems, 
675                     const TIDSortedElemSet& theNodesNot,
676                     const TIDSortedElemSet& theAffectedElems );
677
678   bool AffectedElemGroupsInRegion( const TIDSortedElemSet& theElems,
679                                    const TIDSortedElemSet& theNodesNot,
680                                    const TopoDS_Shape&     theShape,
681                                    TIDSortedElemSet& theAffectedElems);
682
683   bool DoubleNodesInRegion( const TIDSortedElemSet& theElems, 
684                             const TIDSortedElemSet& theNodesNot,
685                             const TopoDS_Shape&     theShape );
686   
687   double OrientedAngle(const gp_Pnt& p0, const gp_Pnt& p1, const gp_Pnt& g1, const gp_Pnt& g2);
688
689   bool DoubleNodesOnGroupBoundaries( const std::vector<TIDSortedElemSet>& theElems,
690                                      bool                                 createJointElems,
691                                      bool                                 onAllBoundaries);
692
693   bool CreateFlatElementsOnFacesGroups( const std::vector<TIDSortedElemSet>& theElems );
694
695   void CreateHoleSkin(double radius,
696                       const TopoDS_Shape& theShape,
697                       SMESH_NodeSearcher* theNodeSearcher,
698                       const char* groupName,
699                       std::vector<double>&   nodesCoords,
700                       std::vector<std::vector<int> >& listOfListOfNodes);
701
702   /*!
703    * \brief Generated skin mesh (containing 2D cells) from 3D mesh
704    * The created 2D mesh elements based on nodes of free faces of boundary volumes
705    * \return TRUE if operation has been completed successfully, FALSE otherwise
706    */
707   bool Make2DMeshFrom3D();
708
709   enum Bnd_Dimension { BND_2DFROM3D, BND_1DFROM3D, BND_1DFROM2D };
710
711   int MakeBoundaryMesh(const TIDSortedElemSet& elements,
712                        Bnd_Dimension           dimension,
713                        SMESH_Group*            group = 0,
714                        SMESH_Mesh*             targetMesh = 0,
715                        bool                    toCopyElements = false,
716                        bool                    toCopyExistingBondary = false,
717                        bool                    toAddExistingBondary = false,
718                        bool                    aroundElements = false);
719
720
721   // structure used in MakePolyLine() to define a cutting plane
722   struct PolySegment
723   {
724     // 2 points: if myNode2 != 0, then the point is the middle of a face edge defined
725     //           by two nodes, else it is at myNode1
726     const SMDS_MeshNode* myNode1[2];
727     const SMDS_MeshNode* myNode2[2];
728
729     gp_Vec myVector; // vector on the plane; to use a default plane set vector = (0,0,0)
730
731     // point to return coordinates of a middle of the two points, projected to mesh
732     gp_Pnt myMidProjPoint;
733   };
734   typedef std::vector<PolySegment> TListOfPolySegments;
735
736   /*!
737    * \brief Create a polyline consisting of 1D mesh elements each lying on a 2D element of
738    *        the initial mesh. Positions of new nodes are found by cutting the mesh by the
739    *        plane passing through pairs of points specified by each PolySegment structure.
740    *        If there are several paths connecting a pair of points, the shortest path is
741    *        selected by the module. Position of the cutting plane is defined by the two
742    *        points and an optional vector lying on the plane specified by a PolySegment.
743    *        By default the vector is defined by Mesh module as following. A middle point
744    *        of the two given points is computed. The middle point is projected to the mesh.
745    *        The vector goes from the middle point to the projection point. In case of planar
746    *        mesh, the vector is normal to the mesh.
747    *  \param [inout] segments - PolySegment's defining positions of cutting planes.
748    *        Return the used vector and position of the middle point.
749    *  \param [in] group - an optional group where created mesh segments will
750    *        be added.
751    */
752   void MakePolyLine( TListOfPolySegments&   segments,
753                      SMESHDS_Group*         group=0,
754                      SMESH_ElementSearcher* searcher=0);
755
756  private:
757
758   /*!
759    * \brief Convert elements contained in a submesh to quadratic
760    * \return int - nb of checked elements
761    */
762   int convertElemToQuadratic(SMESHDS_SubMesh *   theSm,
763                              SMESH_MesherHelper& theHelper,
764                              const bool          theForce3d);
765
766   /*!
767    * \brief Convert quadratic elements to linear ones and remove quadratic nodes
768    * \return nb of checked elements
769    */
770   int removeQuadElem( SMESHDS_SubMesh *    theSm,
771                       SMDS_ElemIteratorPtr theItr,
772                       const int            theShapeID);
773   /*!
774    * \brief Create groups of elements made during transformation
775    * \param nodeGens - nodes making corresponding myLastCreatedNodes
776    * \param elemGens - elements making corresponding myLastCreatedElems
777    * \param postfix - to append to names of new groups
778    * \param targetMesh - mesh to create groups in
779    * \param topPresent - is there "top" elements that are created by sweeping
780    */
781   PGroupIDs generateGroups(const SMESH_SequenceOfElemPtr& nodeGens,
782                            const SMESH_SequenceOfElemPtr& elemGens,
783                            const std::string&             postfix,
784                            SMESH_Mesh*                    targetMesh=0,
785                            const bool                     topPresent=true);
786   /*!
787    * \brief Create elements by sweeping an element
788    * \param elem - element to sweep
789    * \param newNodesItVec - nodes generated from each node of the element
790    * \param newElems - generated elements
791    * \param nbSteps - number of sweeping steps
792    * \param srcElements - to append elem for each generated element
793    */
794   void sweepElement(const SMDS_MeshElement*                    elem,
795                     const std::vector<TNodeOfNodeListMapItr> & newNodesItVec,
796                     std::list<const SMDS_MeshElement*>&        newElems,
797                     const size_t                               nbSteps,
798                     SMESH_SequenceOfElemPtr&                   srcElements);
799
800   /*!
801    * \brief Computes new connectivity of an element after merging nodes
802    *  \param [in] elems - the element
803    *  \param [out] newElemDefs - definition(s) of result element(s)
804    *  \param [inout] nodeNodeMap - nodes to merge
805    *  \param [in] avoidMakingHoles - if true and and the element becomes invalid
806    *             after merging (but not degenerated), removes nodes causing
807    *             the invalidity from \a nodeNodeMap.
808    *  \return bool - true if the element should be removed
809    */
810   bool applyMerge( const SMDS_MeshElement*      elems,
811                    std::vector< ElemFeatures >& newElemDefs,
812                    TNodeNodeMap&                nodeNodeMap,
813                    const bool                   avoidMakingHoles );
814   /*!
815    * \brief Create 1D and 2D elements around swept elements
816    * \param mapNewNodes - source nodes and ones generated from them
817    * \param newElemsMap - source elements and ones generated from them
818    * \param elemNewNodesMap - nodes generated from each node of each element
819    * \param elemSet - all swept elements
820    * \param nbSteps - number of sweeping steps
821    * \param srcElements - to append elem for each generated element
822    */
823   void makeWalls (TNodeOfNodeListMap &     mapNewNodes,
824                   TTElemOfElemListMap &    newElemsMap,
825                   TElemOfVecOfNnlmiMap &   elemNewNodesMap,
826                   TIDSortedElemSet&        elemSet,
827                   const int                nbSteps,
828                   SMESH_SequenceOfElemPtr& srcElements);
829
830   struct SMESH_MeshEditor_PathPoint
831   {
832     gp_Pnt myPnt;
833     gp_Dir myTgt;
834     double myAngle, myPrm;
835
836     SMESH_MeshEditor_PathPoint(): myPnt(99., 99., 99.), myTgt(1.,0.,0.), myAngle(0), myPrm(0) {}
837     void          SetPnt      (const gp_Pnt& aP3D)  { myPnt  =aP3D; }
838     void          SetTangent  (const gp_Dir& aTgt)  { myTgt  =aTgt; }
839     void          SetAngle    (const double& aBeta) { myAngle=aBeta; }
840     void          SetParameter(const double& aPrm)  { myPrm  =aPrm; }
841     const gp_Pnt& Pnt         ()const               { return myPnt; }
842     const gp_Dir& Tangent     ()const               { return myTgt; }
843     double        Angle       ()const               { return myAngle; }
844     double        Parameter   ()const               { return myPrm; }
845   };
846   Extrusion_Error makeEdgePathPoints(std::list<double>&                     aPrms,
847                                      const TopoDS_Edge&                     aTrackEdge,
848                                      bool                                   aFirstIsStart,
849                                      std::list<SMESH_MeshEditor_PathPoint>& aLPP);
850   Extrusion_Error makeExtrElements(TIDSortedElemSet                       theElements[2],
851                                    std::list<SMESH_MeshEditor_PathPoint>& theFullList,
852                                    const bool                             theHasAngles,
853                                    std::list<double>&                     theAngles,
854                                    const bool                             theLinearVariation,
855                                    const bool                             theHasRefPoint,
856                                    const gp_Pnt&                          theRefPoint,
857                                    const bool                             theMakeGroups);
858   static void linearAngleVariation(const int          NbSteps,
859                                    std::list<double>& theAngles);
860
861   bool doubleNodes( SMESHDS_Mesh*           theMeshDS,
862                     const TIDSortedElemSet& theElems,
863                     const TIDSortedElemSet& theNodesNot,
864                     TNodeNodeMap&           theNodeNodeMap,
865                     const bool              theIsDoubleElem );
866
867   void copyPosition( const SMDS_MeshNode* from,
868                      const SMDS_MeshNode* to );
869
870 private:
871
872   SMESH_Mesh *            myMesh;
873
874   // Nodes and elements created during last operation
875   SMESH_SequenceOfElemPtr myLastCreatedNodes, myLastCreatedElems;
876
877   // Description of error/warning occurred during last operation
878   SMESH_ComputeErrorPtr   myError;
879 };
880
881 #endif