Salome HOME
IMP 22635: EDF 8345 - Creation of group based on groups
[modules/smesh.git] / src / SMESH_SWIG / smeshBuilder.py
1 # Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 #  File   : smeshBuilder.py
20 #  Author : Francis KLOSS, OCC
21 #  Module : SMESH
22
23 ## @package smeshBuilder
24 #  Python API for SALOME %Mesh module
25
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating  Creating meshes
28 ## @{
29 ##   @defgroup l2_impexp     Importing and exporting meshes
30 ##   @defgroup l2_construct  Constructing meshes
31 ##   @defgroup l2_algorithms Defining Algorithms
32 ##   @{
33 ##     @defgroup l3_algos_basic   Basic meshing algorithms
34 ##     @defgroup l3_algos_proj    Projection Algorithms
35 ##     @defgroup l3_algos_radialp Radial Prism
36 ##     @defgroup l3_algos_segmarv Segments around Vertex
37 ##     @defgroup l3_algos_3dextr  3D extrusion meshing algorithm
38
39 ##   @}
40 ##   @defgroup l2_hypotheses Defining hypotheses
41 ##   @{
42 ##     @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ##     @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ##     @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ##     @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ##     @defgroup l3_hypos_additi Additional Hypotheses
47
48 ##   @}
49 ##   @defgroup l2_submeshes Constructing submeshes
50 ##   @defgroup l2_compounds Building Compounds
51 ##   @defgroup l2_editing   Editing Meshes
52
53 ## @}
54 ## @defgroup l1_meshinfo  Mesh Information
55 ## @defgroup l1_controls  Quality controls and Filtering
56 ## @defgroup l1_grouping  Grouping elements
57 ## @{
58 ##   @defgroup l2_grps_create Creating groups
59 ##   @defgroup l2_grps_edit   Editing groups
60 ##   @defgroup l2_grps_operon Using operations on groups
61 ##   @defgroup l2_grps_delete Deleting Groups
62
63 ## @}
64 ## @defgroup l1_modifying Modifying meshes
65 ## @{
66 ##   @defgroup l2_modif_add      Adding nodes and elements
67 ##   @defgroup l2_modif_del      Removing nodes and elements
68 ##   @defgroup l2_modif_edit     Modifying nodes and elements
69 ##   @defgroup l2_modif_renumber Renumbering nodes and elements
70 ##   @defgroup l2_modif_trsf     Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ##   @defgroup l2_modif_movenode Moving nodes
72 ##   @defgroup l2_modif_throughp Mesh through point
73 ##   @defgroup l2_modif_invdiag  Diagonal inversion of elements
74 ##   @defgroup l2_modif_unitetri Uniting triangles
75 ##   @defgroup l2_modif_changori Changing orientation of elements
76 ##   @defgroup l2_modif_cutquadr Cutting elements
77 ##   @defgroup l2_modif_smooth   Smoothing
78 ##   @defgroup l2_modif_extrurev Extrusion and Revolution
79 ##   @defgroup l2_modif_patterns Pattern mapping
80 ##   @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
81
82 ## @}
83 ## @defgroup l1_measurements Measurements
84
85 import salome
86 from salome.geom import geomBuilder
87
88 import SMESH # This is necessary for back compatibility
89 from   SMESH import *
90 from   salome.smesh.smesh_algorithm import Mesh_Algorithm
91
92 import SALOME
93 import SALOMEDS
94 import os
95
96 class MeshMeta(type):
97     def __instancecheck__(cls, inst):
98         """Implement isinstance(inst, cls)."""
99         return any(cls.__subclasscheck__(c)
100                    for c in {type(inst), inst.__class__})
101
102     def __subclasscheck__(cls, sub):
103         """Implement issubclass(sub, cls)."""
104         return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
105
106 ## @addtogroup l1_auxiliary
107 ## @{
108
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
111     from math import pi
112     return AngleInDegrees * pi / 180.0
113
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
117 var_separator = ":"
118
119 ## Return list of variable values from salome notebook.
120 #  The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
122     Result = []
123     Parameters = ""
124     hasVariables = False
125     varModifFun=None
126     if args and callable( args[-1] ):
127         args, varModifFun = args[:-1], args[-1]
128     for parameter in args:
129
130         Parameters += str(parameter) + var_separator
131
132         if isinstance(parameter,str):
133             # check if there is an inexistent variable name
134             if not notebook.isVariable(parameter):
135                 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136             parameter = notebook.get(parameter)
137             hasVariables = True
138             if varModifFun:
139                 parameter = varModifFun(parameter)
140                 pass
141             pass
142         Result.append(parameter)
143
144         pass
145     Parameters = Parameters[:-1]
146     Result.append( Parameters )
147     Result.append( hasVariables )
148     return Result
149
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152     return ParseParameters( *( args + (DegreesToRadians, )))
153
154 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157     point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
158     pass
159 SMESH.PointStruct.__init__ = __initPointStruct
160
161 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
164     if len( args ) != 6:
165         raise RuntimeError,\
166               "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
167     ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
168     pass
169 SMESH.AxisStruct.__init__ = __initAxisStruct
170
171 smeshPrecisionConfusion = 1.e-07
172 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
173     if abs(val1 - val2) < tol:
174         return True
175     return False
176
177 NO_NAME = "NoName"
178
179 ## Gets object name
180 def GetName(obj):
181     if obj:
182         # object not null
183         if isinstance(obj, SALOMEDS._objref_SObject):
184             # study object
185             return obj.GetName()
186         try:
187             ior  = salome.orb.object_to_string(obj)
188         except:
189             ior = None
190         if ior:
191             # CORBA object
192             studies = salome.myStudyManager.GetOpenStudies()
193             for sname in studies:
194                 s = salome.myStudyManager.GetStudyByName(sname)
195                 if not s: continue
196                 sobj = s.FindObjectIOR(ior)
197                 if not sobj: continue
198                 return sobj.GetName()
199             if hasattr(obj, "GetName"):
200                 # unknown CORBA object, having GetName() method
201                 return obj.GetName()
202             else:
203                 # unknown CORBA object, no GetName() method
204                 return NO_NAME
205             pass
206         if hasattr(obj, "GetName"):
207             # unknown non-CORBA object, having GetName() method
208             return obj.GetName()
209         pass
210     raise RuntimeError, "Null or invalid object"
211
212 ## Prints error message if a hypothesis was not assigned.
213 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
214     if isAlgo:
215         hypType = "algorithm"
216     else:
217         hypType = "hypothesis"
218         pass
219     reason = ""
220     if hasattr( status, "__getitem__" ):
221         status,reason = status[0],status[1]
222     if status == HYP_UNKNOWN_FATAL :
223         reason = "for unknown reason"
224     elif status == HYP_INCOMPATIBLE :
225         reason = "this hypothesis mismatches the algorithm"
226     elif status == HYP_NOTCONFORM :
227         reason = "a non-conform mesh would be built"
228     elif status == HYP_ALREADY_EXIST :
229         if isAlgo: return # it does not influence anything
230         reason = hypType + " of the same dimension is already assigned to this shape"
231     elif status == HYP_BAD_DIM :
232         reason = hypType + " mismatches the shape"
233     elif status == HYP_CONCURENT :
234         reason = "there are concurrent hypotheses on sub-shapes"
235     elif status == HYP_BAD_SUBSHAPE :
236         reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
237     elif status == HYP_BAD_GEOMETRY:
238         reason = "geometry mismatches the expectation of the algorithm"
239     elif status == HYP_HIDDEN_ALGO:
240         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
241     elif status == HYP_HIDING_ALGO:
242         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
243     elif status == HYP_NEED_SHAPE:
244         reason = "algorithm can't work without shape"
245     elif status == HYP_INCOMPAT_HYPS:
246         pass
247     else:
248         return
249     where = geomName
250     if where:
251         where = '"%s"' % geomName
252         if mesh:
253             meshName = GetName( mesh )
254             if meshName and meshName != NO_NAME:
255                 where = '"%s" in "%s"' % ( geomName, meshName )
256     if status < HYP_UNKNOWN_FATAL and where:
257         print '"%s" was assigned to %s but %s' %( hypName, where, reason )
258     elif where:
259         print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
260     else:
261         print '"%s" was not assigned : %s' %( hypName, reason )
262         pass
263
264 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
265 def AssureGeomPublished(mesh, geom, name=''):
266     if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
267         return
268     if not geom.GetStudyEntry() and \
269            mesh.smeshpyD.GetCurrentStudy():
270         ## set the study
271         studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
272         if studyID != mesh.geompyD.myStudyId:
273             mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
274         ## get a name
275         if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
276             # for all groups SubShapeName() returns "Compound_-1"
277             name = mesh.geompyD.SubShapeName(geom, mesh.geom)
278         if not name:
279             name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
280         ## publish
281         mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
282     return
283
284 ## Return the first vertex of a geometrical edge by ignoring orientation
285 def FirstVertexOnCurve(mesh, edge):
286     vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
287     if not vv:
288         raise TypeError, "Given object has no vertices"
289     if len( vv ) == 1: return vv[0]
290     v0   = mesh.geompyD.MakeVertexOnCurve(edge,0.)
291     xyz  = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
292     xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
293     xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
294     dist1, dist2 = 0,0
295     for i in range(3):
296         dist1 += abs( xyz[i] - xyz1[i] )
297         dist2 += abs( xyz[i] - xyz2[i] )
298     if dist1 < dist2:
299         return vv[0]
300     else:
301         return vv[1]
302
303 # end of l1_auxiliary
304 ## @}
305
306
307 # Warning: smeshInst is a singleton
308 smeshInst = None
309 engine = None
310 doLcc = False
311 created = False
312
313 ## This class allows to create, load or manipulate meshes
314 #  It has a set of methods to create load or copy meshes, to combine several meshes.
315 #  It also has methods to get infos on meshes.
316 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
317
318     # MirrorType enumeration
319     POINT = SMESH_MeshEditor.POINT
320     AXIS =  SMESH_MeshEditor.AXIS
321     PLANE = SMESH_MeshEditor.PLANE
322
323     # Smooth_Method enumeration
324     LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
325     CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
326
327     PrecisionConfusion = smeshPrecisionConfusion
328
329     # TopAbs_State enumeration
330     [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
331
332     # Methods of splitting a hexahedron into tetrahedra
333     Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
334
335     def __new__(cls):
336         global engine
337         global smeshInst
338         global doLcc
339         #print "==== __new__", engine, smeshInst, doLcc
340
341         if smeshInst is None:
342             # smesh engine is either retrieved from engine, or created
343             smeshInst = engine
344             # Following test avoids a recursive loop
345             if doLcc:
346                 if smeshInst is not None:
347                     # smesh engine not created: existing engine found
348                     doLcc = False
349                 if doLcc:
350                     doLcc = False
351                     # FindOrLoadComponent called:
352                     # 1. CORBA resolution of server
353                     # 2. the __new__ method is called again
354                     #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
355                     smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
356             else:
357                 # FindOrLoadComponent not called
358                 if smeshInst is None:
359                     # smeshBuilder instance is created from lcc.FindOrLoadComponent
360                     #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
361                     smeshInst = super(smeshBuilder,cls).__new__(cls)
362                 else:
363                     # smesh engine not created: existing engine found
364                     #print "==== existing ", engine, smeshInst, doLcc
365                     pass
366             #print "====1 ", smeshInst
367             return smeshInst
368
369         #print "====2 ", smeshInst
370         return smeshInst
371
372     def __init__(self):
373         global created
374         #print "--------------- smeshbuilder __init__ ---", created
375         if not created:
376           created = True
377           SMESH._objref_SMESH_Gen.__init__(self)
378
379     ## Dump component to the Python script
380     #  This method overrides IDL function to allow default values for the parameters.
381     def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
382         return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
383
384     ## Set mode of DumpPython(), \a historical or \a snapshot.
385     # In the \a historical mode, the Python Dump script includes all commands
386     # performed by SMESH engine. In the \a snapshot mode, commands
387     # relating to objects removed from the Study are excluded from the script
388     # as well as commands not influencing the current state of meshes
389     def SetDumpPythonHistorical(self, isHistorical):
390         if isHistorical: val = "true"
391         else:            val = "false"
392         SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
393
394     ## Sets the current study and Geometry component
395     #  @ingroup l1_auxiliary
396     def init_smesh(self,theStudy,geompyD = None):
397         #print "init_smesh"
398         self.SetCurrentStudy(theStudy,geompyD)
399         if theStudy:
400             global notebook
401             notebook.myStudy = theStudy
402
403     ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
404     #  or a mesh wrapping a CORBA mesh given as a parameter.
405     #  @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
406     #         salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
407     #         (2) a Geometrical object for meshing or
408     #         (3) none.
409     #  @param name the name for the new mesh.
410     #  @return an instance of Mesh class.
411     #  @ingroup l2_construct
412     def Mesh(self, obj=0, name=0):
413         if isinstance(obj,str):
414             obj,name = name,obj
415         return Mesh(self,self.geompyD,obj,name)
416
417     ## Returns a long value from enumeration
418     #  @ingroup l1_controls
419     def EnumToLong(self,theItem):
420         return theItem._v
421
422     ## Returns a string representation of the color.
423     #  To be used with filters.
424     #  @param c color value (SALOMEDS.Color)
425     #  @ingroup l1_controls
426     def ColorToString(self,c):
427         val = ""
428         if isinstance(c, SALOMEDS.Color):
429             val = "%s;%s;%s" % (c.R, c.G, c.B)
430         elif isinstance(c, str):
431             val = c
432         else:
433             raise ValueError, "Color value should be of string or SALOMEDS.Color type"
434         return val
435
436     ## Gets PointStruct from vertex
437     #  @param theVertex a GEOM object(vertex)
438     #  @return SMESH.PointStruct
439     #  @ingroup l1_auxiliary
440     def GetPointStruct(self,theVertex):
441         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
442         return PointStruct(x,y,z)
443
444     ## Gets DirStruct from vector
445     #  @param theVector a GEOM object(vector)
446     #  @return SMESH.DirStruct
447     #  @ingroup l1_auxiliary
448     def GetDirStruct(self,theVector):
449         vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
450         if(len(vertices) != 2):
451             print "Error: vector object is incorrect."
452             return None
453         p1 = self.geompyD.PointCoordinates(vertices[0])
454         p2 = self.geompyD.PointCoordinates(vertices[1])
455         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
456         dirst = DirStruct(pnt)
457         return dirst
458
459     ## Makes DirStruct from a triplet
460     #  @param x,y,z vector components
461     #  @return SMESH.DirStruct
462     #  @ingroup l1_auxiliary
463     def MakeDirStruct(self,x,y,z):
464         pnt = PointStruct(x,y,z)
465         return DirStruct(pnt)
466
467     ## Get AxisStruct from object
468     #  @param theObj a GEOM object (line or plane)
469     #  @return SMESH.AxisStruct
470     #  @ingroup l1_auxiliary
471     def GetAxisStruct(self,theObj):
472         import GEOM
473         edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
474         axis = None
475         if len(edges) > 1:
476             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
477             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
478             vertex1 = self.geompyD.PointCoordinates(vertex1)
479             vertex2 = self.geompyD.PointCoordinates(vertex2)
480             vertex3 = self.geompyD.PointCoordinates(vertex3)
481             vertex4 = self.geompyD.PointCoordinates(vertex4)
482             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
483             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
484             normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
485             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
486             axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
487         elif len(edges) == 1:
488             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
489             p1 = self.geompyD.PointCoordinates( vertex1 )
490             p2 = self.geompyD.PointCoordinates( vertex2 )
491             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
492             axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
493         elif theObj.GetShapeType() == GEOM.VERTEX:
494             x,y,z = self.geompyD.PointCoordinates( theObj )
495             axis = AxisStruct( x,y,z, 1,0,0,)
496             axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
497         return axis
498
499     # From SMESH_Gen interface:
500     # ------------------------
501
502     ## Sets the given name to the object
503     #  @param obj the object to rename
504     #  @param name a new object name
505     #  @ingroup l1_auxiliary
506     def SetName(self, obj, name):
507         if isinstance( obj, Mesh ):
508             obj = obj.GetMesh()
509         elif isinstance( obj, Mesh_Algorithm ):
510             obj = obj.GetAlgorithm()
511         ior  = salome.orb.object_to_string(obj)
512         SMESH._objref_SMESH_Gen.SetName(self, ior, name)
513
514     ## Sets the current mode
515     #  @ingroup l1_auxiliary
516     def SetEmbeddedMode( self,theMode ):
517         #self.SetEmbeddedMode(theMode)
518         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
519
520     ## Gets the current mode
521     #  @ingroup l1_auxiliary
522     def IsEmbeddedMode(self):
523         #return self.IsEmbeddedMode()
524         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
525
526     ## Sets the current study. Calling SetCurrentStudy( None ) allows to
527     #  switch OFF automatic pubilishing in the Study of mesh objects.
528     #  @ingroup l1_auxiliary
529     def SetCurrentStudy( self, theStudy, geompyD = None ):
530         #self.SetCurrentStudy(theStudy)
531         if not geompyD:
532             from salome.geom import geomBuilder
533             geompyD = geomBuilder.geom
534             pass
535         self.geompyD=geompyD
536         self.SetGeomEngine(geompyD)
537         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
538         global notebook
539         if theStudy:
540             notebook = salome_notebook.NoteBook( theStudy )
541         else:
542             notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
543         if theStudy:
544             sb = theStudy.NewBuilder()
545             sc = theStudy.FindComponent("SMESH")
546             if sc: sb.LoadWith(sc, self)
547             pass
548         pass
549
550     ## Gets the current study
551     #  @ingroup l1_auxiliary
552     def GetCurrentStudy(self):
553         #return self.GetCurrentStudy()
554         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
555
556     ## Creates a Mesh object importing data from the given UNV file
557     #  @return an instance of Mesh class
558     #  @ingroup l2_impexp
559     def CreateMeshesFromUNV( self,theFileName ):
560         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
561         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
562         return aMesh
563
564     ## Creates a Mesh object(s) importing data from the given MED file
565     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
566     #  @ingroup l2_impexp
567     def CreateMeshesFromMED( self,theFileName ):
568         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
569         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
570         return aMeshes, aStatus
571
572     ## Creates a Mesh object(s) importing data from the given SAUV file
573     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
574     #  @ingroup l2_impexp
575     def CreateMeshesFromSAUV( self,theFileName ):
576         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
577         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
578         return aMeshes, aStatus
579
580     ## Creates a Mesh object importing data from the given STL file
581     #  @return an instance of Mesh class
582     #  @ingroup l2_impexp
583     def CreateMeshesFromSTL( self, theFileName ):
584         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
585         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
586         return aMesh
587
588     ## Creates Mesh objects importing data from the given CGNS file
589     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
590     #  @ingroup l2_impexp
591     def CreateMeshesFromCGNS( self, theFileName ):
592         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
593         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
594         return aMeshes, aStatus
595
596     ## Creates a Mesh object importing data from the given GMF file.
597     #  GMF files must have .mesh extension for the ASCII format and .meshb for
598     #  the binary format.
599     #  @return [ an instance of Mesh class, SMESH.ComputeError ]
600     #  @ingroup l2_impexp
601     def CreateMeshesFromGMF( self, theFileName ):
602         aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
603                                                                         theFileName,
604                                                                         True)
605         if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
606         return Mesh(self, self.geompyD, aSmeshMesh), error
607
608     ## Concatenate the given meshes into one mesh. All groups of input meshes will be
609     #  present in the new mesh.
610     #  @param meshes the meshes, sub-meshes and groups to combine into one mesh
611     #  @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
612     #  @param mergeNodesAndElements if true, equal nodes and elements are merged
613     #  @param mergeTolerance tolerance for merging nodes
614     #  @param allGroups forces creation of groups corresponding to every input mesh
615     #  @param name name of a new mesh
616     #  @return an instance of Mesh class
617     def Concatenate( self, meshes, uniteIdenticalGroups,
618                      mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
619                      name = ""):
620         if not meshes: return None
621         for i,m in enumerate(meshes):
622             if isinstance(m, Mesh):
623                 meshes[i] = m.GetMesh()
624         mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
625         meshes[0].SetParameters(Parameters)
626         if allGroups:
627             aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
629         else:
630             aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632         aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
633         return aMesh
634
635     ## Create a mesh by copying a part of another mesh.
636     #  @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
637     #                  to copy nodes or elements not contained in any mesh object,
638     #                  pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
639     #  @param meshName a name of the new mesh
640     #  @param toCopyGroups to create in the new mesh groups the copied elements belongs to
641     #  @param toKeepIDs to preserve order of the copied elements or not
642     #  @return an instance of Mesh class
643     def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
644         if (isinstance( meshPart, Mesh )):
645             meshPart = meshPart.GetMesh()
646         mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
647         return Mesh(self, self.geompyD, mesh)
648
649     ## From SMESH_Gen interface
650     #  @return the list of integer values
651     #  @ingroup l1_auxiliary
652     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
653         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
654
655     ## From SMESH_Gen interface. Creates a pattern
656     #  @return an instance of SMESH_Pattern
657     #
658     #  <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
659     #  @ingroup l2_modif_patterns
660     def GetPattern(self):
661         return SMESH._objref_SMESH_Gen.GetPattern(self)
662
663     ## Sets number of segments per diagonal of boundary box of geometry by which
664     #  default segment length of appropriate 1D hypotheses is defined.
665     #  Default value is 10
666     #  @ingroup l1_auxiliary
667     def SetBoundaryBoxSegmentation(self, nbSegments):
668         SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
669
670     # Filtering. Auxiliary functions:
671     # ------------------------------
672
673     ## Creates an empty criterion
674     #  @return SMESH.Filter.Criterion
675     #  @ingroup l1_controls
676     def GetEmptyCriterion(self):
677         Type = self.EnumToLong(FT_Undefined)
678         Compare = self.EnumToLong(FT_Undefined)
679         Threshold = 0
680         ThresholdStr = ""
681         ThresholdID = ""
682         UnaryOp = self.EnumToLong(FT_Undefined)
683         BinaryOp = self.EnumToLong(FT_Undefined)
684         Tolerance = 1e-07
685         TypeOfElement = ALL
686         Precision = -1 ##@1e-07
687         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
688                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
689
690     ## Creates a criterion by the given parameters
691     #  \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
692     #  @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
693     #  @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
694     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
695     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
696     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
697     #  @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
698     #                  FT_Undefined (must be for the last criterion of all criteria)
699     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
700     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
701     #  @return SMESH.Filter.Criterion
702     #
703     #  <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
704     #  @ingroup l1_controls
705     def GetCriterion(self,elementType,
706                      CritType,
707                      Compare = FT_EqualTo,
708                      Threshold="",
709                      UnaryOp=FT_Undefined,
710                      BinaryOp=FT_Undefined,
711                      Tolerance=1e-07):
712         if not CritType in SMESH.FunctorType._items:
713             raise TypeError, "CritType should be of SMESH.FunctorType"
714         aCriterion               = self.GetEmptyCriterion()
715         aCriterion.TypeOfElement = elementType
716         aCriterion.Type          = self.EnumToLong(CritType)
717         aCriterion.Tolerance     = Tolerance
718
719         aThreshold = Threshold
720
721         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
722             aCriterion.Compare = self.EnumToLong(Compare)
723         elif Compare == "=" or Compare == "==":
724             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
725         elif Compare == "<":
726             aCriterion.Compare = self.EnumToLong(FT_LessThan)
727         elif Compare == ">":
728             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
729         elif Compare != FT_Undefined:
730             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
731             aThreshold = Compare
732
733         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
734                         FT_BelongToCylinder, FT_LyingOnGeom]:
735             # Check that Threshold is GEOM object
736             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
737                 aCriterion.ThresholdStr = GetName(aThreshold)
738                 aCriterion.ThresholdID  = aThreshold.GetStudyEntry()
739                 if not aCriterion.ThresholdID:
740                     name = aCriterion.ThresholdStr
741                     if not name:
742                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
743                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
744             # or a name of GEOM object
745             elif isinstance( aThreshold, str ):
746                 aCriterion.ThresholdStr = aThreshold
747             else:
748                 raise TypeError, "The Threshold should be a shape."
749             if isinstance(UnaryOp,float):
750                 aCriterion.Tolerance = UnaryOp
751                 UnaryOp = FT_Undefined
752                 pass
753         elif CritType == FT_BelongToMeshGroup:
754             # Check that Threshold is a group
755             if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
756                 if aThreshold.GetType() != elementType:
757                     raise ValueError, "Group type mismatches Element type"
758                 aCriterion.ThresholdStr = aThreshold.GetName()
759                 aCriterion.ThresholdID  = salome.orb.object_to_string( aThreshold )
760                 study = self.GetCurrentStudy()
761                 if study:
762                     so = study.FindObjectIOR( aCriterion.ThresholdID )
763                     if so:
764                         entry = so.GetID()
765                         if entry:
766                             aCriterion.ThresholdID = entry
767             else:
768                 raise TypeError, "The Threshold should be a Mesh Group"
769         elif CritType == FT_RangeOfIds:
770             # Check that Threshold is string
771             if isinstance(aThreshold, str):
772                 aCriterion.ThresholdStr = aThreshold
773             else:
774                 raise TypeError, "The Threshold should be a string."
775         elif CritType == FT_CoplanarFaces:
776             # Check the Threshold
777             if isinstance(aThreshold, int):
778                 aCriterion.ThresholdID = str(aThreshold)
779             elif isinstance(aThreshold, str):
780                 ID = int(aThreshold)
781                 if ID < 1:
782                     raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
783                 aCriterion.ThresholdID = aThreshold
784             else:
785                 raise TypeError,\
786                       "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
787         elif CritType == FT_ConnectedElements:
788             # Check the Threshold
789             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
790                 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
791                 if not aCriterion.ThresholdID:
792                     name = aThreshold.GetName()
793                     if not name:
794                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
795                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
796             elif isinstance(aThreshold, int): # node id
797                 aCriterion.Threshold = aThreshold
798             elif isinstance(aThreshold, list): # 3 point coordinates
799                 if len( aThreshold ) < 3:
800                     raise ValueError, "too few point coordinates, must be 3"
801                 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
802             elif isinstance(aThreshold, str):
803                 if aThreshold.isdigit():
804                     aCriterion.Threshold = aThreshold # node id
805                 else:
806                     aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
807             else:
808                 raise TypeError,\
809                       "The Threshold should either a VERTEX, or a node ID, "\
810                       "or a list of point coordinates and not '%s'"%aThreshold
811         elif CritType == FT_ElemGeomType:
812             # Check the Threshold
813             try:
814                 aCriterion.Threshold = self.EnumToLong(aThreshold)
815                 assert( aThreshold in SMESH.GeometryType._items )
816             except:
817                 if isinstance(aThreshold, int):
818                     aCriterion.Threshold = aThreshold
819                 else:
820                     raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
821                 pass
822             pass
823         elif CritType == FT_EntityType:
824             # Check the Threshold
825             try:
826                 aCriterion.Threshold = self.EnumToLong(aThreshold)
827                 assert( aThreshold in SMESH.EntityType._items )
828             except:
829                 if isinstance(aThreshold, int):
830                     aCriterion.Threshold = aThreshold
831                 else:
832                     raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
833                 pass
834             pass
835         
836         elif CritType == FT_GroupColor:
837             # Check the Threshold
838             try:
839                 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
840             except:
841                 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
842             pass
843         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
844                           FT_LinearOrQuadratic, FT_BadOrientedVolume,
845                           FT_BareBorderFace, FT_BareBorderVolume,
846                           FT_OverConstrainedFace, FT_OverConstrainedVolume,
847                           FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
848             # At this point the Threshold is unnecessary
849             if aThreshold ==  FT_LogicalNOT:
850                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
851             elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
852                 aCriterion.BinaryOp = aThreshold
853         else:
854             # Check Threshold
855             try:
856                 aThreshold = float(aThreshold)
857                 aCriterion.Threshold = aThreshold
858             except:
859                 raise TypeError, "The Threshold should be a number."
860                 return None
861
862         if Threshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
863             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
864
865         if Threshold in [FT_LogicalAND, FT_LogicalOR]:
866             aCriterion.BinaryOp = self.EnumToLong(Threshold)
867
868         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
869             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
870
871         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
872             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
873
874         return aCriterion
875
876     ## Creates a filter with the given parameters
877     #  @param elementType the type of elements in the group
878     #  @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
879     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
880     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
881     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
882     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
883     #         FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
884     #  @param mesh the mesh to initialize the filter with
885     #  @return SMESH_Filter
886     #
887     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
888     #  @ingroup l1_controls
889     def GetFilter(self,elementType,
890                   CritType=FT_Undefined,
891                   Compare=FT_EqualTo,
892                   Threshold="",
893                   UnaryOp=FT_Undefined,
894                   Tolerance=1e-07,
895                   mesh=None):
896         aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
897         aFilterMgr = self.CreateFilterManager()
898         aFilter = aFilterMgr.CreateFilter()
899         aCriteria = []
900         aCriteria.append(aCriterion)
901         aFilter.SetCriteria(aCriteria)
902         if mesh:
903             if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
904             else                       : aFilter.SetMesh( mesh )
905         aFilterMgr.UnRegister()
906         return aFilter
907
908     ## Creates a filter from criteria
909     #  @param criteria a list of criteria
910     #  @param binOp binary operator used when binary operator of criteria is undefined
911     #  @return SMESH_Filter
912     #
913     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
914     #  @ingroup l1_controls
915     def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
916         for i in range( len( criteria ) - 1 ):
917             if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
918                 criteria[i].BinaryOp = self.EnumToLong( binOp )
919         aFilterMgr = self.CreateFilterManager()
920         aFilter = aFilterMgr.CreateFilter()
921         aFilter.SetCriteria(criteria)
922         aFilterMgr.UnRegister()
923         return aFilter
924
925     ## Creates a numerical functor by its type
926     #  @param theCriterion FT_...; functor type
927     #  @return SMESH_NumericalFunctor
928     #  @ingroup l1_controls
929     def GetFunctor(self,theCriterion):
930         if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
931             return theCriterion
932         aFilterMgr = self.CreateFilterManager()
933         functor = None
934         if theCriterion == FT_AspectRatio:
935             functor = aFilterMgr.CreateAspectRatio()
936         elif theCriterion == FT_AspectRatio3D:
937             functor = aFilterMgr.CreateAspectRatio3D()
938         elif theCriterion == FT_Warping:
939             functor = aFilterMgr.CreateWarping()
940         elif theCriterion == FT_MinimumAngle:
941             functor = aFilterMgr.CreateMinimumAngle()
942         elif theCriterion == FT_Taper:
943             functor = aFilterMgr.CreateTaper()
944         elif theCriterion == FT_Skew:
945             functor = aFilterMgr.CreateSkew()
946         elif theCriterion == FT_Area:
947             functor = aFilterMgr.CreateArea()
948         elif theCriterion == FT_Volume3D:
949             functor = aFilterMgr.CreateVolume3D()
950         elif theCriterion == FT_MaxElementLength2D:
951             functor = aFilterMgr.CreateMaxElementLength2D()
952         elif theCriterion == FT_MaxElementLength3D:
953             functor = aFilterMgr.CreateMaxElementLength3D()
954         elif theCriterion == FT_MultiConnection:
955             functor = aFilterMgr.CreateMultiConnection()
956         elif theCriterion == FT_MultiConnection2D:
957             functor = aFilterMgr.CreateMultiConnection2D()
958         elif theCriterion == FT_Length:
959             functor = aFilterMgr.CreateLength()
960         elif theCriterion == FT_Length2D:
961             functor = aFilterMgr.CreateLength2D()
962         else:
963             print "Error: given parameter is not numerical functor type."
964         aFilterMgr.UnRegister()
965         return functor
966
967     ## Creates hypothesis
968     #  @param theHType mesh hypothesis type (string)
969     #  @param theLibName mesh plug-in library name
970     #  @return created hypothesis instance
971     def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
972         hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
973
974         if isinstance( hyp, SMESH._objref_SMESH_Algo ):
975             return hyp
976
977         # wrap hypothesis methods
978         #print "HYPOTHESIS", theHType
979         for meth_name in dir( hyp.__class__ ):
980             if not meth_name.startswith("Get") and \
981                not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
982                 method = getattr ( hyp.__class__, meth_name )
983                 if callable(method):
984                     setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
985
986         return hyp
987
988     ## Gets the mesh statistic
989     #  @return dictionary "element type" - "count of elements"
990     #  @ingroup l1_meshinfo
991     def GetMeshInfo(self, obj):
992         if isinstance( obj, Mesh ):
993             obj = obj.GetMesh()
994         d = {}
995         if hasattr(obj, "GetMeshInfo"):
996             values = obj.GetMeshInfo()
997             for i in range(SMESH.Entity_Last._v):
998                 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
999             pass
1000         return d
1001
1002     ## Get minimum distance between two objects
1003     #
1004     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1005     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1006     #
1007     #  @param src1 first source object
1008     #  @param src2 second source object
1009     #  @param id1 node/element id from the first source
1010     #  @param id2 node/element id from the second (or first) source
1011     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1012     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1013     #  @return minimum distance value
1014     #  @sa GetMinDistance()
1015     #  @ingroup l1_measurements
1016     def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1017         result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1018         if result is None:
1019             result = 0.0
1020         else:
1021             result = result.value
1022         return result
1023
1024     ## Get measure structure specifying minimum distance data between two objects
1025     #
1026     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1027     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1028     #
1029     #  @param src1 first source object
1030     #  @param src2 second source object
1031     #  @param id1 node/element id from the first source
1032     #  @param id2 node/element id from the second (or first) source
1033     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1034     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1035     #  @return Measure structure or None if input data is invalid
1036     #  @sa MinDistance()
1037     #  @ingroup l1_measurements
1038     def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1039         if isinstance(src1, Mesh): src1 = src1.mesh
1040         if isinstance(src2, Mesh): src2 = src2.mesh
1041         if src2 is None and id2 != 0: src2 = src1
1042         if not hasattr(src1, "_narrow"): return None
1043         src1 = src1._narrow(SMESH.SMESH_IDSource)
1044         if not src1: return None
1045         unRegister = genObjUnRegister()
1046         if id1 != 0:
1047             m = src1.GetMesh()
1048             e = m.GetMeshEditor()
1049             if isElem1:
1050                 src1 = e.MakeIDSource([id1], SMESH.FACE)
1051             else:
1052                 src1 = e.MakeIDSource([id1], SMESH.NODE)
1053             unRegister.set( src1 )
1054             pass
1055         if hasattr(src2, "_narrow"):
1056             src2 = src2._narrow(SMESH.SMESH_IDSource)
1057             if src2 and id2 != 0:
1058                 m = src2.GetMesh()
1059                 e = m.GetMeshEditor()
1060                 if isElem2:
1061                     src2 = e.MakeIDSource([id2], SMESH.FACE)
1062                 else:
1063                     src2 = e.MakeIDSource([id2], SMESH.NODE)
1064                 unRegister.set( src2 )
1065                 pass
1066             pass
1067         aMeasurements = self.CreateMeasurements()
1068         unRegister.set( aMeasurements )
1069         result = aMeasurements.MinDistance(src1, src2)
1070         return result
1071
1072     ## Get bounding box of the specified object(s)
1073     #  @param objects single source object or list of source objects
1074     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1075     #  @sa GetBoundingBox()
1076     #  @ingroup l1_measurements
1077     def BoundingBox(self, objects):
1078         result = self.GetBoundingBox(objects)
1079         if result is None:
1080             result = (0.0,)*6
1081         else:
1082             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1083         return result
1084
1085     ## Get measure structure specifying bounding box data of the specified object(s)
1086     #  @param objects single source object or list of source objects
1087     #  @return Measure structure
1088     #  @sa BoundingBox()
1089     #  @ingroup l1_measurements
1090     def GetBoundingBox(self, objects):
1091         if isinstance(objects, tuple):
1092             objects = list(objects)
1093         if not isinstance(objects, list):
1094             objects = [objects]
1095         srclist = []
1096         for o in objects:
1097             if isinstance(o, Mesh):
1098                 srclist.append(o.mesh)
1099             elif hasattr(o, "_narrow"):
1100                 src = o._narrow(SMESH.SMESH_IDSource)
1101                 if src: srclist.append(src)
1102                 pass
1103             pass
1104         aMeasurements = self.CreateMeasurements()
1105         result = aMeasurements.BoundingBox(srclist)
1106         aMeasurements.UnRegister()
1107         return result
1108
1109     ## Get sum of lengths of all 1D elements in the mesh object.
1110     #  @param obj mesh, submesh or group
1111     #  @return sum of lengths of all 1D elements
1112     #  @ingroup l1_measurements
1113     def GetLength(self, obj):
1114         if isinstance(obj, Mesh): obj = obj.mesh
1115         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1116         aMeasurements = self.CreateMeasurements()
1117         value = aMeasurements.Length(obj)
1118         aMeasurements.UnRegister()
1119         return value
1120
1121     ## Get sum of areas of all 2D elements in the mesh object.
1122     #  @param obj mesh, submesh or group
1123     #  @return sum of areas of all 2D elements
1124     #  @ingroup l1_measurements
1125     def GetArea(self, obj):
1126         if isinstance(obj, Mesh): obj = obj.mesh
1127         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1128         aMeasurements = self.CreateMeasurements()
1129         value = aMeasurements.Area(obj)
1130         aMeasurements.UnRegister()
1131         return value
1132
1133     ## Get sum of volumes of all 3D elements in the mesh object.
1134     #  @param obj mesh, submesh or group
1135     #  @return sum of volumes of all 3D elements
1136     #  @ingroup l1_measurements
1137     def GetVolume(self, obj):
1138         if isinstance(obj, Mesh): obj = obj.mesh
1139         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1140         aMeasurements = self.CreateMeasurements()
1141         value = aMeasurements.Volume(obj)
1142         aMeasurements.UnRegister()
1143         return value
1144
1145     pass # end of class smeshBuilder
1146
1147 import omniORB
1148 #Registering the new proxy for SMESH_Gen
1149 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1150
1151 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1152 #  interface to create or load meshes.
1153 #
1154 #  Typical use is:
1155 #  \code
1156 #    import salome
1157 #    salome.salome_init()
1158 #    from salome.smesh import smeshBuilder
1159 #    smesh = smeshBuilder.New(theStudy)
1160 #  \endcode
1161 #  @param  study     SALOME study, generally obtained by salome.myStudy.
1162 #  @param  instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1163 #  @return smeshBuilder instance
1164
1165 def New( study, instance=None):
1166     """
1167     Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1168     interface to create or load meshes.
1169
1170     Typical use is:
1171         import salome
1172         salome.salome_init()
1173         from salome.smesh import smeshBuilder
1174         smesh = smeshBuilder.New(theStudy)
1175
1176     Parameters:
1177         study     SALOME study, generally obtained by salome.myStudy.
1178         instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1179     Returns:
1180         smeshBuilder instance
1181     """
1182     global engine
1183     global smeshInst
1184     global doLcc
1185     engine = instance
1186     if engine is None:
1187       doLcc = True
1188     smeshInst = smeshBuilder()
1189     assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1190     smeshInst.init_smesh(study)
1191     return smeshInst
1192
1193
1194 # Public class: Mesh
1195 # ==================
1196
1197 ## This class allows defining and managing a mesh.
1198 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1199 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1200 #  new nodes and elements and by changing the existing entities), to get information
1201 #  about a mesh and to export a mesh into different formats.
1202 class Mesh:
1203     __metaclass__ = MeshMeta
1204
1205     geom = 0
1206     mesh = 0
1207     editor = 0
1208
1209     ## Constructor
1210     #
1211     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1212     #  sets the GUI name of this mesh to \a name.
1213     #  @param smeshpyD an instance of smeshBuilder class
1214     #  @param geompyD an instance of geomBuilder class
1215     #  @param obj Shape to be meshed or SMESH_Mesh object
1216     #  @param name Study name of the mesh
1217     #  @ingroup l2_construct
1218     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1219         self.smeshpyD=smeshpyD
1220         self.geompyD=geompyD
1221         if obj is None:
1222             obj = 0
1223         objHasName = False
1224         if obj != 0:
1225             if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1226                 self.geom = obj
1227                 objHasName = True
1228                 # publish geom of mesh (issue 0021122)
1229                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1230                     objHasName = False
1231                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1232                     if studyID != geompyD.myStudyId:
1233                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
1234                         pass
1235                     if name:
1236                         geo_name = name + " shape"
1237                     else:
1238                         geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1239                     geompyD.addToStudy( self.geom, geo_name )
1240                 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1241
1242             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1243                 self.SetMesh(obj)
1244         else:
1245             self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1246         if name:
1247             self.smeshpyD.SetName(self.mesh, name)
1248         elif objHasName:
1249             self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1250
1251         if not self.geom:
1252             self.geom = self.mesh.GetShapeToMesh()
1253
1254         self.editor   = self.mesh.GetMeshEditor()
1255         self.functors = [None] * SMESH.FT_Undefined._v
1256
1257         # set self to algoCreator's
1258         for attrName in dir(self):
1259             attr = getattr( self, attrName )
1260             if isinstance( attr, algoCreator ):
1261                 setattr( self, attrName, attr.copy( self ))
1262                 pass
1263             pass
1264         pass
1265
1266     ## Destructor. Clean-up resources
1267     def __del__(self):
1268         if self.mesh:
1269             #self.mesh.UnRegister()
1270             pass
1271         pass
1272         
1273     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1274     #  @param theMesh a SMESH_Mesh object
1275     #  @ingroup l2_construct
1276     def SetMesh(self, theMesh):
1277         # do not call Register() as this prevents mesh servant deletion at closing study
1278         #if self.mesh: self.mesh.UnRegister()
1279         self.mesh = theMesh
1280         if self.mesh:
1281             #self.mesh.Register()
1282             self.geom = self.mesh.GetShapeToMesh()
1283         pass
1284
1285     ## Returns the mesh, that is an instance of SMESH_Mesh interface
1286     #  @return a SMESH_Mesh object
1287     #  @ingroup l2_construct
1288     def GetMesh(self):
1289         return self.mesh
1290
1291     ## Gets the name of the mesh
1292     #  @return the name of the mesh as a string
1293     #  @ingroup l2_construct
1294     def GetName(self):
1295         name = GetName(self.GetMesh())
1296         return name
1297
1298     ## Sets a name to the mesh
1299     #  @param name a new name of the mesh
1300     #  @ingroup l2_construct
1301     def SetName(self, name):
1302         self.smeshpyD.SetName(self.GetMesh(), name)
1303
1304     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1305     #  The subMesh object gives access to the IDs of nodes and elements.
1306     #  @param geom a geometrical object (shape)
1307     #  @param name a name for the submesh
1308     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1309     #  @ingroup l2_submeshes
1310     def GetSubMesh(self, geom, name):
1311         AssureGeomPublished( self, geom, name )
1312         submesh = self.mesh.GetSubMesh( geom, name )
1313         return submesh
1314
1315     ## Returns the shape associated to the mesh
1316     #  @return a GEOM_Object
1317     #  @ingroup l2_construct
1318     def GetShape(self):
1319         return self.geom
1320
1321     ## Associates the given shape to the mesh (entails the recreation of the mesh)
1322     #  @param geom the shape to be meshed (GEOM_Object)
1323     #  @ingroup l2_construct
1324     def SetShape(self, geom):
1325         self.mesh = self.smeshpyD.CreateMesh(geom)
1326
1327     ## Loads mesh from the study after opening the study
1328     def Load(self):
1329         self.mesh.Load()
1330
1331     ## Returns true if the hypotheses are defined well
1332     #  @param theSubObject a sub-shape of a mesh shape
1333     #  @return True or False
1334     #  @ingroup l2_construct
1335     def IsReadyToCompute(self, theSubObject):
1336         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1337
1338     ## Returns errors of hypotheses definition.
1339     #  The list of errors is empty if everything is OK.
1340     #  @param theSubObject a sub-shape of a mesh shape
1341     #  @return a list of errors
1342     #  @ingroup l2_construct
1343     def GetAlgoState(self, theSubObject):
1344         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1345
1346     ## Returns a geometrical object on which the given element was built.
1347     #  The returned geometrical object, if not nil, is either found in the
1348     #  study or published by this method with the given name
1349     #  @param theElementID the id of the mesh element
1350     #  @param theGeomName the user-defined name of the geometrical object
1351     #  @return GEOM::GEOM_Object instance
1352     #  @ingroup l2_construct
1353     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1354         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1355
1356     ## Returns the mesh dimension depending on the dimension of the underlying shape
1357     #  or, if the mesh is not based on any shape, basing on deimension of elements
1358     #  @return mesh dimension as an integer value [0,3]
1359     #  @ingroup l1_auxiliary
1360     def MeshDimension(self):
1361         if self.mesh.HasShapeToMesh():
1362             shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1363             if len( shells ) > 0 :
1364                 return 3
1365             elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1366                 return 2
1367             elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1368                 return 1
1369             else:
1370                 return 0;
1371         else:
1372             if self.NbVolumes() > 0: return 3
1373             if self.NbFaces()   > 0: return 2
1374             if self.NbEdges()   > 0: return 1
1375         return 0
1376
1377     ## Evaluates size of prospective mesh on a shape
1378     #  @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1379     #  To know predicted number of e.g. edges, inquire it this way
1380     #  Evaluate()[ EnumToLong( Entity_Edge )]
1381     def Evaluate(self, geom=0):
1382         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1383             if self.geom == 0:
1384                 geom = self.mesh.GetShapeToMesh()
1385             else:
1386                 geom = self.geom
1387         return self.smeshpyD.Evaluate(self.mesh, geom)
1388
1389
1390     ## Computes the mesh and returns the status of the computation
1391     #  @param geom geomtrical shape on which mesh data should be computed
1392     #  @param discardModifs if True and the mesh has been edited since
1393     #         a last total re-compute and that may prevent successful partial re-compute,
1394     #         then the mesh is cleaned before Compute()
1395     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1396     #  @return True or False
1397     #  @ingroup l2_construct
1398     def Compute(self, geom=0, discardModifs=False, refresh=False):
1399         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1400             if self.geom == 0:
1401                 geom = self.mesh.GetShapeToMesh()
1402             else:
1403                 geom = self.geom
1404         ok = False
1405         try:
1406             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1407                 self.mesh.Clear()
1408             ok = self.smeshpyD.Compute(self.mesh, geom)
1409         except SALOME.SALOME_Exception, ex:
1410             print "Mesh computation failed, exception caught:"
1411             print "    ", ex.details.text
1412         except:
1413             import traceback
1414             print "Mesh computation failed, exception caught:"
1415             traceback.print_exc()
1416         if True:#not ok:
1417             allReasons = ""
1418
1419             # Treat compute errors
1420             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1421             for err in computeErrors:
1422                 shapeText = ""
1423                 if self.mesh.HasShapeToMesh():
1424                     try:
1425                         mainIOR  = salome.orb.object_to_string(geom)
1426                         for sname in salome.myStudyManager.GetOpenStudies():
1427                             s = salome.myStudyManager.GetStudyByName(sname)
1428                             if not s: continue
1429                             mainSO = s.FindObjectIOR(mainIOR)
1430                             if not mainSO: continue
1431                             if err.subShapeID == 1:
1432                                 shapeText = ' on "%s"' % mainSO.GetName()
1433                             subIt = s.NewChildIterator(mainSO)
1434                             while subIt.More():
1435                                 subSO = subIt.Value()
1436                                 subIt.Next()
1437                                 obj = subSO.GetObject()
1438                                 if not obj: continue
1439                                 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1440                                 if not go: continue
1441                                 ids = go.GetSubShapeIndices()
1442                                 if len(ids) == 1 and ids[0] == err.subShapeID:
1443                                     shapeText = ' on "%s"' % subSO.GetName()
1444                                     break
1445                         if not shapeText:
1446                             shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1447                             if shape:
1448                                 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1449                             else:
1450                                 shapeText = " on subshape #%s" % (err.subShapeID)
1451                     except:
1452                         shapeText = " on subshape #%s" % (err.subShapeID)
1453                 errText = ""
1454                 stdErrors = ["OK",                   #COMPERR_OK
1455                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1456                              "std::exception",       #COMPERR_STD_EXCEPTION
1457                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1458                              "..",                   #COMPERR_SLM_EXCEPTION
1459                              "Unknown exception",    #COMPERR_EXCEPTION
1460                              "Memory allocation problem", #COMPERR_MEMORY_PB
1461                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1462                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1463                              "Warning",              #COMPERR_WARNING
1464                              "Computation cancelled",#COMPERR_CANCELED
1465                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1466                 if err.code > 0:
1467                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1468                 else:
1469                     errText = "code %s" % -err.code
1470                 if errText: errText += ". "
1471                 errText += err.comment
1472                 if allReasons != "":allReasons += "\n"
1473                 if ok:
1474                     allReasons += '-  "%s"%s - %s' %(err.algoName, shapeText, errText)
1475                 else:
1476                     allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1477                 pass
1478
1479             # Treat hyp errors
1480             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1481             for err in errors:
1482                 if err.isGlobalAlgo:
1483                     glob = "global"
1484                 else:
1485                     glob = "local"
1486                     pass
1487                 dim = err.algoDim
1488                 name = err.algoName
1489                 if len(name) == 0:
1490                     reason = '%s %sD algorithm is missing' % (glob, dim)
1491                 elif err.state == HYP_MISSING:
1492                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1493                               % (glob, dim, name, dim))
1494                 elif err.state == HYP_NOTCONFORM:
1495                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1496                 elif err.state == HYP_BAD_PARAMETER:
1497                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1498                               % ( glob, dim, name ))
1499                 elif err.state == HYP_BAD_GEOMETRY:
1500                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1501                               'geometry' % ( glob, dim, name ))
1502                 elif err.state == HYP_HIDDEN_ALGO:
1503                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1504                               'algorithm of upper dimension generating %sD mesh'
1505                               % ( glob, dim, name, glob, dim ))
1506                 else:
1507                     reason = ("For unknown reason. "
1508                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1509                     pass
1510                 if allReasons != "":allReasons += "\n"
1511                 allReasons += "-  " + reason
1512                 pass
1513             if not ok or allReasons != "":
1514                 msg = '"' + GetName(self.mesh) + '"'
1515                 if ok: msg += " has been computed with warnings"
1516                 else:  msg += " has not been computed"
1517                 if allReasons != "": msg += ":"
1518                 else:                msg += "."
1519                 print msg
1520                 print allReasons
1521             pass
1522         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1523             smeshgui = salome.ImportComponentGUI("SMESH")
1524             smeshgui.Init(self.mesh.GetStudyId())
1525             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1526             if refresh: salome.sg.updateObjBrowser(1)
1527             pass
1528         return ok
1529
1530     ## Return submesh objects list in meshing order
1531     #  @return list of list of submesh objects
1532     #  @ingroup l2_construct
1533     def GetMeshOrder(self):
1534         return self.mesh.GetMeshOrder()
1535
1536     ## Return submesh objects list in meshing order
1537     #  @return list of list of submesh objects
1538     #  @ingroup l2_construct
1539     def SetMeshOrder(self, submeshes):
1540         return self.mesh.SetMeshOrder(submeshes)
1541
1542     ## Removes all nodes and elements
1543     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1544     #  @ingroup l2_construct
1545     def Clear(self, refresh=False):
1546         self.mesh.Clear()
1547         if ( salome.sg.hasDesktop() and 
1548              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1549             smeshgui = salome.ImportComponentGUI("SMESH")
1550             smeshgui.Init(self.mesh.GetStudyId())
1551             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1552             if refresh: salome.sg.updateObjBrowser(1)
1553
1554     ## Removes all nodes and elements of indicated shape
1555     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1556     #  @param geomId the ID of a sub-shape to remove elements on
1557     #  @ingroup l2_construct
1558     def ClearSubMesh(self, geomId, refresh=False):
1559         self.mesh.ClearSubMesh(geomId)
1560         if salome.sg.hasDesktop():
1561             smeshgui = salome.ImportComponentGUI("SMESH")
1562             smeshgui.Init(self.mesh.GetStudyId())
1563             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1564             if refresh: salome.sg.updateObjBrowser(1)
1565
1566     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1567     #  @param fineness [0.0,1.0] defines mesh fineness
1568     #  @return True or False
1569     #  @ingroup l3_algos_basic
1570     def AutomaticTetrahedralization(self, fineness=0):
1571         dim = self.MeshDimension()
1572         # assign hypotheses
1573         self.RemoveGlobalHypotheses()
1574         self.Segment().AutomaticLength(fineness)
1575         if dim > 1 :
1576             self.Triangle().LengthFromEdges()
1577             pass
1578         if dim > 2 :
1579             self.Tetrahedron()
1580             pass
1581         return self.Compute()
1582
1583     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1584     #  @param fineness [0.0, 1.0] defines mesh fineness
1585     #  @return True or False
1586     #  @ingroup l3_algos_basic
1587     def AutomaticHexahedralization(self, fineness=0):
1588         dim = self.MeshDimension()
1589         # assign the hypotheses
1590         self.RemoveGlobalHypotheses()
1591         self.Segment().AutomaticLength(fineness)
1592         if dim > 1 :
1593             self.Quadrangle()
1594             pass
1595         if dim > 2 :
1596             self.Hexahedron()
1597             pass
1598         return self.Compute()
1599
1600     ## Assigns a hypothesis
1601     #  @param hyp a hypothesis to assign
1602     #  @param geom a subhape of mesh geometry
1603     #  @return SMESH.Hypothesis_Status
1604     #  @ingroup l2_hypotheses
1605     def AddHypothesis(self, hyp, geom=0):
1606         if isinstance( hyp, Mesh_Algorithm ):
1607             hyp = hyp.GetAlgorithm()
1608             pass
1609         if not geom:
1610             geom = self.geom
1611             if not geom:
1612                 geom = self.mesh.GetShapeToMesh()
1613             pass
1614         isApplicable = True
1615         if self.mesh.HasShapeToMesh():
1616             hyp_type     = hyp.GetName()
1617             lib_name     = hyp.GetLibName()
1618             checkAll    = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1619             if checkAll and geom:
1620                 checkAll = geom.GetType() == 37
1621             isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1622         if isApplicable:
1623             AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1624             status = self.mesh.AddHypothesis(geom, hyp)
1625         else:
1626             status = HYP_BAD_GEOMETRY,""
1627         hyp_name = GetName( hyp )
1628         geom_name = ""
1629         if geom:
1630             geom_name = geom.GetName()
1631         isAlgo = hyp._narrow( SMESH_Algo )
1632         TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1633         return status
1634
1635     ## Return True if an algorithm of hypothesis is assigned to a given shape
1636     #  @param hyp a hypothesis to check
1637     #  @param geom a subhape of mesh geometry
1638     #  @return True of False
1639     #  @ingroup l2_hypotheses
1640     def IsUsedHypothesis(self, hyp, geom):
1641         if not hyp: # or not geom
1642             return False
1643         if isinstance( hyp, Mesh_Algorithm ):
1644             hyp = hyp.GetAlgorithm()
1645             pass
1646         hyps = self.GetHypothesisList(geom)
1647         for h in hyps:
1648             if h.GetId() == hyp.GetId():
1649                 return True
1650         return False
1651
1652     ## Unassigns a hypothesis
1653     #  @param hyp a hypothesis to unassign
1654     #  @param geom a sub-shape of mesh geometry
1655     #  @return SMESH.Hypothesis_Status
1656     #  @ingroup l2_hypotheses
1657     def RemoveHypothesis(self, hyp, geom=0):
1658         if not hyp:
1659             return None
1660         if isinstance( hyp, Mesh_Algorithm ):
1661             hyp = hyp.GetAlgorithm()
1662             pass
1663         shape = geom
1664         if not shape:
1665             shape = self.geom
1666             pass
1667         if self.IsUsedHypothesis( hyp, shape ):
1668             return self.mesh.RemoveHypothesis( shape, hyp )
1669         hypName = GetName( hyp )
1670         geoName = GetName( shape )
1671         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1672         return None
1673
1674     ## Gets the list of hypotheses added on a geometry
1675     #  @param geom a sub-shape of mesh geometry
1676     #  @return the sequence of SMESH_Hypothesis
1677     #  @ingroup l2_hypotheses
1678     def GetHypothesisList(self, geom):
1679         return self.mesh.GetHypothesisList( geom )
1680
1681     ## Removes all global hypotheses
1682     #  @ingroup l2_hypotheses
1683     def RemoveGlobalHypotheses(self):
1684         current_hyps = self.mesh.GetHypothesisList( self.geom )
1685         for hyp in current_hyps:
1686             self.mesh.RemoveHypothesis( self.geom, hyp )
1687             pass
1688         pass
1689
1690    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1691     ## allowing to overwrite the file if it exists or add the exported data to its contents
1692     #  @param f is the file name
1693     #  @param auto_groups boolean parameter for creating/not creating
1694     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1695     #  the typical use is auto_groups=false.
1696     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1697     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1698     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1699     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1700     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1701     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1702     #         - 3D in the rest cases.
1703     #         If @a autoDimension is @c False, the space dimension is always 3.
1704     #  @param fields : list of GEOM fields defined on the shape to mesh.
1705     #  @param geomAssocFields : each character of this string means a need to export a 
1706     #         corresponding field; correspondence between fields and characters is following:
1707     #         - 'v' stands for _vertices_ field;
1708     #         - 'e' stands for _edges_ field;
1709     #         - 'f' stands for _faces_ field;
1710     #         - 's' stands for _solids_ field.
1711     #  @ingroup l2_impexp
1712     def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1713                   overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1714         if meshPart or fields or geomAssocFields:
1715             unRegister = genObjUnRegister()
1716             if isinstance( meshPart, list ):
1717                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1718                 unRegister.set( meshPart )
1719             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1720                                        fields, geomAssocFields)
1721         else:
1722             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1723
1724     ## Exports the mesh in a file in SAUV format
1725     #  @param f is the file name
1726     #  @param auto_groups boolean parameter for creating/not creating
1727     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1728     #  the typical use is auto_groups=false.
1729     #  @ingroup l2_impexp
1730     def ExportSAUV(self, f, auto_groups=0):
1731         self.mesh.ExportSAUV(f, auto_groups)
1732
1733     ## Exports the mesh in a file in DAT format
1734     #  @param f the file name
1735     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1736     #  @ingroup l2_impexp
1737     def ExportDAT(self, f, meshPart=None):
1738         if meshPart:
1739             unRegister = genObjUnRegister()
1740             if isinstance( meshPart, list ):
1741                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1742                 unRegister.set( meshPart )
1743             self.mesh.ExportPartToDAT( meshPart, f )
1744         else:
1745             self.mesh.ExportDAT(f)
1746
1747     ## Exports the mesh in a file in UNV format
1748     #  @param f the file name
1749     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1750     #  @ingroup l2_impexp
1751     def ExportUNV(self, f, meshPart=None):
1752         if meshPart:
1753             unRegister = genObjUnRegister()
1754             if isinstance( meshPart, list ):
1755                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1756                 unRegister.set( meshPart )
1757             self.mesh.ExportPartToUNV( meshPart, f )
1758         else:
1759             self.mesh.ExportUNV(f)
1760
1761     ## Export the mesh in a file in STL format
1762     #  @param f the file name
1763     #  @param ascii defines the file encoding
1764     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1765     #  @ingroup l2_impexp
1766     def ExportSTL(self, f, ascii=1, meshPart=None):
1767         if meshPart:
1768             unRegister = genObjUnRegister()
1769             if isinstance( meshPart, list ):
1770                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1771                 unRegister.set( meshPart )
1772             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1773         else:
1774             self.mesh.ExportSTL(f, ascii)
1775
1776     ## Exports the mesh in a file in CGNS format
1777     #  @param f is the file name
1778     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1779     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1780     #  @ingroup l2_impexp
1781     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1782         unRegister = genObjUnRegister()
1783         if isinstance( meshPart, list ):
1784             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1785             unRegister.set( meshPart )
1786         if isinstance( meshPart, Mesh ):
1787             meshPart = meshPart.mesh
1788         elif not meshPart:
1789             meshPart = self.mesh
1790         self.mesh.ExportCGNS(meshPart, f, overwrite)
1791
1792     ## Exports the mesh in a file in GMF format.
1793     #  GMF files must have .mesh extension for the ASCII format and .meshb for
1794     #  the bynary format. Other extensions are not allowed.
1795     #  @param f is the file name
1796     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1797     #  @ingroup l2_impexp
1798     def ExportGMF(self, f, meshPart=None):
1799         unRegister = genObjUnRegister()
1800         if isinstance( meshPart, list ):
1801             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1802             unRegister.set( meshPart )
1803         if isinstance( meshPart, Mesh ):
1804             meshPart = meshPart.mesh
1805         elif not meshPart:
1806             meshPart = self.mesh
1807         self.mesh.ExportGMF(meshPart, f, True)
1808
1809     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1810     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1811     ## allowing to overwrite the file if it exists or add the exported data to its contents
1812     #  @param f the file name
1813     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1814     #  @param opt boolean parameter for creating/not creating
1815     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1816     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1817     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1818     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1819     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1820     #         - 3D in the rest cases.
1821     #
1822     #         If @a autoDimension is @c False, the space dimension is always 3.
1823     #  @ingroup l2_impexp
1824     def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1825         self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1826
1827     # Operations with groups:
1828     # ----------------------
1829
1830     ## Creates an empty mesh group
1831     #  @param elementType the type of elements in the group
1832     #  @param name the name of the mesh group
1833     #  @return SMESH_Group
1834     #  @ingroup l2_grps_create
1835     def CreateEmptyGroup(self, elementType, name):
1836         return self.mesh.CreateGroup(elementType, name)
1837
1838     ## Creates a mesh group based on the geometric object \a grp
1839     #  and gives a \a name, \n if this parameter is not defined
1840     #  the name is the same as the geometric group name \n
1841     #  Note: Works like GroupOnGeom().
1842     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1843     #  @param name the name of the mesh group
1844     #  @return SMESH_GroupOnGeom
1845     #  @ingroup l2_grps_create
1846     def Group(self, grp, name=""):
1847         return self.GroupOnGeom(grp, name)
1848
1849     ## Creates a mesh group based on the geometrical object \a grp
1850     #  and gives a \a name, \n if this parameter is not defined
1851     #  the name is the same as the geometrical group name
1852     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1853     #  @param name the name of the mesh group
1854     #  @param typ  the type of elements in the group. If not set, it is
1855     #              automatically detected by the type of the geometry
1856     #  @return SMESH_GroupOnGeom
1857     #  @ingroup l2_grps_create
1858     def GroupOnGeom(self, grp, name="", typ=None):
1859         AssureGeomPublished( self, grp, name )
1860         if name == "":
1861             name = grp.GetName()
1862         if not typ:
1863             typ = self._groupTypeFromShape( grp )
1864         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1865
1866     ## Pivate method to get a type of group on geometry
1867     def _groupTypeFromShape( self, shape ):
1868         tgeo = str(shape.GetShapeType())
1869         if tgeo == "VERTEX":
1870             typ = NODE
1871         elif tgeo == "EDGE":
1872             typ = EDGE
1873         elif tgeo == "FACE" or tgeo == "SHELL":
1874             typ = FACE
1875         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1876             typ = VOLUME
1877         elif tgeo == "COMPOUND":
1878             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1879             if not sub:
1880                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1881             return self._groupTypeFromShape( sub[0] )
1882         else:
1883             raise ValueError, \
1884                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1885         return typ
1886
1887     ## Creates a mesh group with given \a name based on the \a filter which
1888     ## is a special type of group dynamically updating it's contents during
1889     ## mesh modification
1890     #  @param typ  the type of elements in the group
1891     #  @param name the name of the mesh group
1892     #  @param filter the filter defining group contents
1893     #  @return SMESH_GroupOnFilter
1894     #  @ingroup l2_grps_create
1895     def GroupOnFilter(self, typ, name, filter):
1896         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1897
1898     ## Creates a mesh group by the given ids of elements
1899     #  @param groupName the name of the mesh group
1900     #  @param elementType the type of elements in the group
1901     #  @param elemIDs the list of ids
1902     #  @return SMESH_Group
1903     #  @ingroup l2_grps_create
1904     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1905         group = self.mesh.CreateGroup(elementType, groupName)
1906         if hasattr( elemIDs, "GetIDs" ):
1907             if hasattr( elemIDs, "SetMesh" ):
1908                 elemIDs.SetMesh( self.GetMesh() )
1909             group.AddFrom( elemIDs )
1910         else:
1911             group.Add(elemIDs)
1912         return group
1913
1914     ## Creates a mesh group by the given conditions
1915     #  @param groupName the name of the mesh group
1916     #  @param elementType the type of elements in the group
1917     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1918     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1919     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
1920     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
1921     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1922     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
1923     #  @return SMESH_GroupOnFilter
1924     #  @ingroup l2_grps_create
1925     def MakeGroup(self,
1926                   groupName,
1927                   elementType,
1928                   CritType=FT_Undefined,
1929                   Compare=FT_EqualTo,
1930                   Threshold="",
1931                   UnaryOp=FT_Undefined,
1932                   Tolerance=1e-07):
1933         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1934         group = self.MakeGroupByCriterion(groupName, aCriterion)
1935         return group
1936
1937     ## Creates a mesh group by the given criterion
1938     #  @param groupName the name of the mesh group
1939     #  @param Criterion the instance of Criterion class
1940     #  @return SMESH_GroupOnFilter
1941     #  @ingroup l2_grps_create
1942     def MakeGroupByCriterion(self, groupName, Criterion):
1943         return self.MakeGroupByCriteria( groupName, [Criterion] )
1944
1945     ## Creates a mesh group by the given criteria (list of criteria)
1946     #  @param groupName the name of the mesh group
1947     #  @param theCriteria the list of criteria
1948     #  @param binOp binary operator used when binary operator of criteria is undefined
1949     #  @return SMESH_GroupOnFilter
1950     #  @ingroup l2_grps_create
1951     def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1952         aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1953         group = self.MakeGroupByFilter(groupName, aFilter)
1954         return group
1955
1956     ## Creates a mesh group by the given filter
1957     #  @param groupName the name of the mesh group
1958     #  @param theFilter the instance of Filter class
1959     #  @return SMESH_GroupOnFilter
1960     #  @ingroup l2_grps_create
1961     def MakeGroupByFilter(self, groupName, theFilter):
1962         #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1963         #theFilter.SetMesh( self.mesh )
1964         #group.AddFrom( theFilter )
1965         group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1966         return group
1967
1968     ## Removes a group
1969     #  @ingroup l2_grps_delete
1970     def RemoveGroup(self, group):
1971         self.mesh.RemoveGroup(group)
1972
1973     ## Removes a group with its contents
1974     #  @ingroup l2_grps_delete
1975     def RemoveGroupWithContents(self, group):
1976         self.mesh.RemoveGroupWithContents(group)
1977
1978     ## Gets the list of groups existing in the mesh in the order
1979     #  of creation (starting from the oldest one)
1980     #  @return a sequence of SMESH_GroupBase
1981     #  @ingroup l2_grps_create
1982     def GetGroups(self):
1983         return self.mesh.GetGroups()
1984
1985     ## Gets the number of groups existing in the mesh
1986     #  @return the quantity of groups as an integer value
1987     #  @ingroup l2_grps_create
1988     def NbGroups(self):
1989         return self.mesh.NbGroups()
1990
1991     ## Gets the list of names of groups existing in the mesh
1992     #  @return list of strings
1993     #  @ingroup l2_grps_create
1994     def GetGroupNames(self):
1995         groups = self.GetGroups()
1996         names = []
1997         for group in groups:
1998             names.append(group.GetName())
1999         return names
2000
2001     ## Produces a union of two groups.
2002     #  A new group is created. All mesh elements that are
2003     #  present in the initial groups are added to the new one
2004     #  @return an instance of SMESH_Group
2005     #  @ingroup l2_grps_operon
2006     def UnionGroups(self, group1, group2, name):
2007         return self.mesh.UnionGroups(group1, group2, name)
2008
2009     ## Produces a union list of groups.
2010     #  New group is created. All mesh elements that are present in
2011     #  initial groups are added to the new one
2012     #  @return an instance of SMESH_Group
2013     #  @ingroup l2_grps_operon
2014     def UnionListOfGroups(self, groups, name):
2015       return self.mesh.UnionListOfGroups(groups, name)
2016
2017     ## Prodices an intersection of two groups.
2018     #  A new group is created. All mesh elements that are common
2019     #  for the two initial groups are added to the new one.
2020     #  @return an instance of SMESH_Group
2021     #  @ingroup l2_grps_operon
2022     def IntersectGroups(self, group1, group2, name):
2023         return self.mesh.IntersectGroups(group1, group2, name)
2024
2025     ## Produces an intersection of groups.
2026     #  New group is created. All mesh elements that are present in all
2027     #  initial groups simultaneously are added to the new one
2028     #  @return an instance of SMESH_Group
2029     #  @ingroup l2_grps_operon
2030     def IntersectListOfGroups(self, groups, name):
2031       return self.mesh.IntersectListOfGroups(groups, name)
2032
2033     ## Produces a cut of two groups.
2034     #  A new group is created. All mesh elements that are present in
2035     #  the main group but are not present in the tool group are added to the new one
2036     #  @return an instance of SMESH_Group
2037     #  @ingroup l2_grps_operon
2038     def CutGroups(self, main_group, tool_group, name):
2039         return self.mesh.CutGroups(main_group, tool_group, name)
2040
2041     ## Produces a cut of groups.
2042     #  A new group is created. All mesh elements that are present in main groups
2043     #  but do not present in tool groups are added to the new one
2044     #  @return an instance of SMESH_Group
2045     #  @ingroup l2_grps_operon
2046     def CutListOfGroups(self, main_groups, tool_groups, name):
2047         return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2048
2049     ##
2050     #  Create a standalone group of entities basing on nodes of other groups.
2051     #  \param groups - list of groups, sub-meshes or filters, of any type.
2052     #  \param elemType - a type of elements to include to the new group.
2053     #  \param name - a name of the new group.
2054     #  \param nbCommonNodes - a criterion of inclusion of an element to the new group
2055     #         basing on number of element nodes common with reference \a groups.
2056     #         Meaning of possible values are:
2057     #         - SMESH.ALL_NODES - include if all nodes are common,
2058     #         - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2059     #         - SMESH.AT_LEAST_ONE - include if one or more node is common,
2060     #         - SMEHS.MAJORITY - include if half of nodes or more are common.
2061     #  \param underlyingOnly - if \c True (default), an element is included to the
2062     #         new group provided that it is based on nodes of one element of \a groups.
2063     #  @return an instance of SMESH_Group
2064     #  @ingroup l2_grps_operon
2065     def CreateDimGroup(self, groups, elemType, name,
2066                        nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2067         if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2068             groups = [groups]
2069         return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2070
2071
2072     ## Convert group on geom into standalone group
2073     #  @ingroup l2_grps_delete
2074     def ConvertToStandalone(self, group):
2075         return self.mesh.ConvertToStandalone(group)
2076
2077     # Get some info about mesh:
2078     # ------------------------
2079
2080     ## Returns the log of nodes and elements added or removed
2081     #  since the previous clear of the log.
2082     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
2083     #  @return list of log_block structures:
2084     #                                        commandType
2085     #                                        number
2086     #                                        coords
2087     #                                        indexes
2088     #  @ingroup l1_auxiliary
2089     def GetLog(self, clearAfterGet):
2090         return self.mesh.GetLog(clearAfterGet)
2091
2092     ## Clears the log of nodes and elements added or removed since the previous
2093     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
2094     #  @ingroup l1_auxiliary
2095     def ClearLog(self):
2096         self.mesh.ClearLog()
2097
2098     ## Toggles auto color mode on the object.
2099     #  @param theAutoColor the flag which toggles auto color mode.
2100     #  @ingroup l1_auxiliary
2101     def SetAutoColor(self, theAutoColor):
2102         self.mesh.SetAutoColor(theAutoColor)
2103
2104     ## Gets flag of object auto color mode.
2105     #  @return True or False
2106     #  @ingroup l1_auxiliary
2107     def GetAutoColor(self):
2108         return self.mesh.GetAutoColor()
2109
2110     ## Gets the internal ID
2111     #  @return integer value, which is the internal Id of the mesh
2112     #  @ingroup l1_auxiliary
2113     def GetId(self):
2114         return self.mesh.GetId()
2115
2116     ## Get the study Id
2117     #  @return integer value, which is the study Id of the mesh
2118     #  @ingroup l1_auxiliary
2119     def GetStudyId(self):
2120         return self.mesh.GetStudyId()
2121
2122     ## Checks the group names for duplications.
2123     #  Consider the maximum group name length stored in MED file.
2124     #  @return True or False
2125     #  @ingroup l1_auxiliary
2126     def HasDuplicatedGroupNamesMED(self):
2127         return self.mesh.HasDuplicatedGroupNamesMED()
2128
2129     ## Obtains the mesh editor tool
2130     #  @return an instance of SMESH_MeshEditor
2131     #  @ingroup l1_modifying
2132     def GetMeshEditor(self):
2133         return self.editor
2134
2135     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2136     #  can be passed as argument to a method accepting mesh, group or sub-mesh
2137     #  @return an instance of SMESH_IDSource
2138     #  @ingroup l1_auxiliary
2139     def GetIDSource(self, ids, elemType):
2140         return self.editor.MakeIDSource(ids, elemType)
2141
2142
2143     # Get informations about mesh contents:
2144     # ------------------------------------
2145
2146     ## Gets the mesh stattistic
2147     #  @return dictionary type element - count of elements
2148     #  @ingroup l1_meshinfo
2149     def GetMeshInfo(self, obj = None):
2150         if not obj: obj = self.mesh
2151         return self.smeshpyD.GetMeshInfo(obj)
2152
2153     ## Returns the number of nodes in the mesh
2154     #  @return an integer value
2155     #  @ingroup l1_meshinfo
2156     def NbNodes(self):
2157         return self.mesh.NbNodes()
2158
2159     ## Returns the number of elements in the mesh
2160     #  @return an integer value
2161     #  @ingroup l1_meshinfo
2162     def NbElements(self):
2163         return self.mesh.NbElements()
2164
2165     ## Returns the number of 0d elements in the mesh
2166     #  @return an integer value
2167     #  @ingroup l1_meshinfo
2168     def Nb0DElements(self):
2169         return self.mesh.Nb0DElements()
2170
2171     ## Returns the number of ball discrete elements in the mesh
2172     #  @return an integer value
2173     #  @ingroup l1_meshinfo
2174     def NbBalls(self):
2175         return self.mesh.NbBalls()
2176
2177     ## Returns the number of edges in the mesh
2178     #  @return an integer value
2179     #  @ingroup l1_meshinfo
2180     def NbEdges(self):
2181         return self.mesh.NbEdges()
2182
2183     ## Returns the number of edges with the given order in the mesh
2184     #  @param elementOrder the order of elements:
2185     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2186     #  @return an integer value
2187     #  @ingroup l1_meshinfo
2188     def NbEdgesOfOrder(self, elementOrder):
2189         return self.mesh.NbEdgesOfOrder(elementOrder)
2190
2191     ## Returns the number of faces in the mesh
2192     #  @return an integer value
2193     #  @ingroup l1_meshinfo
2194     def NbFaces(self):
2195         return self.mesh.NbFaces()
2196
2197     ## Returns the number of faces with the given order in the mesh
2198     #  @param elementOrder the order of elements:
2199     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2200     #  @return an integer value
2201     #  @ingroup l1_meshinfo
2202     def NbFacesOfOrder(self, elementOrder):
2203         return self.mesh.NbFacesOfOrder(elementOrder)
2204
2205     ## Returns the number of triangles in the mesh
2206     #  @return an integer value
2207     #  @ingroup l1_meshinfo
2208     def NbTriangles(self):
2209         return self.mesh.NbTriangles()
2210
2211     ## Returns the number of triangles with the given order in the mesh
2212     #  @param elementOrder is the order of elements:
2213     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2214     #  @return an integer value
2215     #  @ingroup l1_meshinfo
2216     def NbTrianglesOfOrder(self, elementOrder):
2217         return self.mesh.NbTrianglesOfOrder(elementOrder)
2218
2219     ## Returns the number of biquadratic triangles in the mesh
2220     #  @return an integer value
2221     #  @ingroup l1_meshinfo
2222     def NbBiQuadTriangles(self):
2223         return self.mesh.NbBiQuadTriangles()
2224
2225     ## Returns the number of quadrangles in the mesh
2226     #  @return an integer value
2227     #  @ingroup l1_meshinfo
2228     def NbQuadrangles(self):
2229         return self.mesh.NbQuadrangles()
2230
2231     ## Returns the number of quadrangles with the given order in the mesh
2232     #  @param elementOrder the order of elements:
2233     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2234     #  @return an integer value
2235     #  @ingroup l1_meshinfo
2236     def NbQuadranglesOfOrder(self, elementOrder):
2237         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2238
2239     ## Returns the number of biquadratic quadrangles in the mesh
2240     #  @return an integer value
2241     #  @ingroup l1_meshinfo
2242     def NbBiQuadQuadrangles(self):
2243         return self.mesh.NbBiQuadQuadrangles()
2244
2245     ## Returns the number of polygons in the mesh
2246     #  @return an integer value
2247     #  @ingroup l1_meshinfo
2248     def NbPolygons(self):
2249         return self.mesh.NbPolygons()
2250
2251     ## Returns the number of volumes in the mesh
2252     #  @return an integer value
2253     #  @ingroup l1_meshinfo
2254     def NbVolumes(self):
2255         return self.mesh.NbVolumes()
2256
2257     ## Returns the number of volumes with the given order in the mesh
2258     #  @param elementOrder  the order of elements:
2259     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2260     #  @return an integer value
2261     #  @ingroup l1_meshinfo
2262     def NbVolumesOfOrder(self, elementOrder):
2263         return self.mesh.NbVolumesOfOrder(elementOrder)
2264
2265     ## Returns the number of tetrahedrons in the mesh
2266     #  @return an integer value
2267     #  @ingroup l1_meshinfo
2268     def NbTetras(self):
2269         return self.mesh.NbTetras()
2270
2271     ## Returns the number of tetrahedrons with the given order in the mesh
2272     #  @param elementOrder  the order of elements:
2273     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2274     #  @return an integer value
2275     #  @ingroup l1_meshinfo
2276     def NbTetrasOfOrder(self, elementOrder):
2277         return self.mesh.NbTetrasOfOrder(elementOrder)
2278
2279     ## Returns the number of hexahedrons in the mesh
2280     #  @return an integer value
2281     #  @ingroup l1_meshinfo
2282     def NbHexas(self):
2283         return self.mesh.NbHexas()
2284
2285     ## Returns the number of hexahedrons with the given order in the mesh
2286     #  @param elementOrder  the order of elements:
2287     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2288     #  @return an integer value
2289     #  @ingroup l1_meshinfo
2290     def NbHexasOfOrder(self, elementOrder):
2291         return self.mesh.NbHexasOfOrder(elementOrder)
2292
2293     ## Returns the number of triquadratic hexahedrons in the mesh
2294     #  @return an integer value
2295     #  @ingroup l1_meshinfo
2296     def NbTriQuadraticHexas(self):
2297         return self.mesh.NbTriQuadraticHexas()
2298
2299     ## Returns the number of pyramids in the mesh
2300     #  @return an integer value
2301     #  @ingroup l1_meshinfo
2302     def NbPyramids(self):
2303         return self.mesh.NbPyramids()
2304
2305     ## Returns the number of pyramids with the given order in the mesh
2306     #  @param elementOrder  the order of elements:
2307     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2308     #  @return an integer value
2309     #  @ingroup l1_meshinfo
2310     def NbPyramidsOfOrder(self, elementOrder):
2311         return self.mesh.NbPyramidsOfOrder(elementOrder)
2312
2313     ## Returns the number of prisms in the mesh
2314     #  @return an integer value
2315     #  @ingroup l1_meshinfo
2316     def NbPrisms(self):
2317         return self.mesh.NbPrisms()
2318
2319     ## Returns the number of prisms with the given order in the mesh
2320     #  @param elementOrder  the order of elements:
2321     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2322     #  @return an integer value
2323     #  @ingroup l1_meshinfo
2324     def NbPrismsOfOrder(self, elementOrder):
2325         return self.mesh.NbPrismsOfOrder(elementOrder)
2326
2327     ## Returns the number of hexagonal prisms in the mesh
2328     #  @return an integer value
2329     #  @ingroup l1_meshinfo
2330     def NbHexagonalPrisms(self):
2331         return self.mesh.NbHexagonalPrisms()
2332
2333     ## Returns the number of polyhedrons in the mesh
2334     #  @return an integer value
2335     #  @ingroup l1_meshinfo
2336     def NbPolyhedrons(self):
2337         return self.mesh.NbPolyhedrons()
2338
2339     ## Returns the number of submeshes in the mesh
2340     #  @return an integer value
2341     #  @ingroup l1_meshinfo
2342     def NbSubMesh(self):
2343         return self.mesh.NbSubMesh()
2344
2345     ## Returns the list of mesh elements IDs
2346     #  @return the list of integer values
2347     #  @ingroup l1_meshinfo
2348     def GetElementsId(self):
2349         return self.mesh.GetElementsId()
2350
2351     ## Returns the list of IDs of mesh elements with the given type
2352     #  @param elementType  the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2353     #  @return list of integer values
2354     #  @ingroup l1_meshinfo
2355     def GetElementsByType(self, elementType):
2356         return self.mesh.GetElementsByType(elementType)
2357
2358     ## Returns the list of mesh nodes IDs
2359     #  @return the list of integer values
2360     #  @ingroup l1_meshinfo
2361     def GetNodesId(self):
2362         return self.mesh.GetNodesId()
2363
2364     # Get the information about mesh elements:
2365     # ------------------------------------
2366
2367     ## Returns the type of mesh element
2368     #  @return the value from SMESH::ElementType enumeration
2369     #  @ingroup l1_meshinfo
2370     def GetElementType(self, id, iselem):
2371         return self.mesh.GetElementType(id, iselem)
2372
2373     ## Returns the geometric type of mesh element
2374     #  @return the value from SMESH::EntityType enumeration
2375     #  @ingroup l1_meshinfo
2376     def GetElementGeomType(self, id):
2377         return self.mesh.GetElementGeomType(id)
2378
2379     ## Returns the shape type of mesh element
2380     #  @return the value from SMESH::GeometryType enumeration
2381     #  @ingroup l1_meshinfo
2382     def GetElementShape(self, id):
2383         return self.mesh.GetElementShape(id)
2384
2385     ## Returns the list of submesh elements IDs
2386     #  @param Shape a geom object(sub-shape) IOR
2387     #         Shape must be the sub-shape of a ShapeToMesh()
2388     #  @return the list of integer values
2389     #  @ingroup l1_meshinfo
2390     def GetSubMeshElementsId(self, Shape):
2391         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2392             ShapeID = Shape.GetSubShapeIndices()[0]
2393         else:
2394             ShapeID = Shape
2395         return self.mesh.GetSubMeshElementsId(ShapeID)
2396
2397     ## Returns the list of submesh nodes IDs
2398     #  @param Shape a geom object(sub-shape) IOR
2399     #         Shape must be the sub-shape of a ShapeToMesh()
2400     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2401     #  @return the list of integer values
2402     #  @ingroup l1_meshinfo
2403     def GetSubMeshNodesId(self, Shape, all):
2404         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2405             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2406         else:
2407             ShapeID = Shape
2408         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2409
2410     ## Returns type of elements on given shape
2411     #  @param Shape a geom object(sub-shape) IOR
2412     #         Shape must be a sub-shape of a ShapeToMesh()
2413     #  @return element type
2414     #  @ingroup l1_meshinfo
2415     def GetSubMeshElementType(self, Shape):
2416         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2417             ShapeID = Shape.GetSubShapeIndices()[0]
2418         else:
2419             ShapeID = Shape
2420         return self.mesh.GetSubMeshElementType(ShapeID)
2421
2422     ## Gets the mesh description
2423     #  @return string value
2424     #  @ingroup l1_meshinfo
2425     def Dump(self):
2426         return self.mesh.Dump()
2427
2428
2429     # Get the information about nodes and elements of a mesh by its IDs:
2430     # -----------------------------------------------------------
2431
2432     ## Gets XYZ coordinates of a node
2433     #  \n If there is no nodes for the given ID - returns an empty list
2434     #  @return a list of double precision values
2435     #  @ingroup l1_meshinfo
2436     def GetNodeXYZ(self, id):
2437         return self.mesh.GetNodeXYZ(id)
2438
2439     ## Returns list of IDs of inverse elements for the given node
2440     #  \n If there is no node for the given ID - returns an empty list
2441     #  @return a list of integer values
2442     #  @ingroup l1_meshinfo
2443     def GetNodeInverseElements(self, id):
2444         return self.mesh.GetNodeInverseElements(id)
2445
2446     ## @brief Returns the position of a node on the shape
2447     #  @return SMESH::NodePosition
2448     #  @ingroup l1_meshinfo
2449     def GetNodePosition(self,NodeID):
2450         return self.mesh.GetNodePosition(NodeID)
2451
2452     ## @brief Returns the position of an element on the shape
2453     #  @return SMESH::ElementPosition
2454     #  @ingroup l1_meshinfo
2455     def GetElementPosition(self,ElemID):
2456         return self.mesh.GetElementPosition(ElemID)
2457
2458     ## If the given element is a node, returns the ID of shape
2459     #  \n If there is no node for the given ID - returns -1
2460     #  @return an integer value
2461     #  @ingroup l1_meshinfo
2462     def GetShapeID(self, id):
2463         return self.mesh.GetShapeID(id)
2464
2465     ## Returns the ID of the result shape after
2466     #  FindShape() from SMESH_MeshEditor for the given element
2467     #  \n If there is no element for the given ID - returns -1
2468     #  @return an integer value
2469     #  @ingroup l1_meshinfo
2470     def GetShapeIDForElem(self,id):
2471         return self.mesh.GetShapeIDForElem(id)
2472
2473     ## Returns the number of nodes for the given element
2474     #  \n If there is no element for the given ID - returns -1
2475     #  @return an integer value
2476     #  @ingroup l1_meshinfo
2477     def GetElemNbNodes(self, id):
2478         return self.mesh.GetElemNbNodes(id)
2479
2480     ## Returns the node ID the given (zero based) index for the given element
2481     #  \n If there is no element for the given ID - returns -1
2482     #  \n If there is no node for the given index - returns -2
2483     #  @return an integer value
2484     #  @ingroup l1_meshinfo
2485     def GetElemNode(self, id, index):
2486         return self.mesh.GetElemNode(id, index)
2487
2488     ## Returns the IDs of nodes of the given element
2489     #  @return a list of integer values
2490     #  @ingroup l1_meshinfo
2491     def GetElemNodes(self, id):
2492         return self.mesh.GetElemNodes(id)
2493
2494     ## Returns true if the given node is the medium node in the given quadratic element
2495     #  @ingroup l1_meshinfo
2496     def IsMediumNode(self, elementID, nodeID):
2497         return self.mesh.IsMediumNode(elementID, nodeID)
2498
2499     ## Returns true if the given node is the medium node in one of quadratic elements
2500     #  @ingroup l1_meshinfo
2501     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2502         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2503
2504     ## Returns the number of edges for the given element
2505     #  @ingroup l1_meshinfo
2506     def ElemNbEdges(self, id):
2507         return self.mesh.ElemNbEdges(id)
2508
2509     ## Returns the number of faces for the given element
2510     #  @ingroup l1_meshinfo
2511     def ElemNbFaces(self, id):
2512         return self.mesh.ElemNbFaces(id)
2513
2514     ## Returns nodes of given face (counted from zero) for given volumic element.
2515     #  @ingroup l1_meshinfo
2516     def GetElemFaceNodes(self,elemId, faceIndex):
2517         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2518
2519     ## Returns three components of normal of given mesh face
2520     #  (or an empty array in KO case)
2521     #  @ingroup l1_meshinfo
2522     def GetFaceNormal(self, faceId, normalized=False):
2523         return self.mesh.GetFaceNormal(faceId,normalized)
2524
2525     ## Returns an element based on all given nodes.
2526     #  @ingroup l1_meshinfo
2527     def FindElementByNodes(self,nodes):
2528         return self.mesh.FindElementByNodes(nodes)
2529
2530     ## Returns true if the given element is a polygon
2531     #  @ingroup l1_meshinfo
2532     def IsPoly(self, id):
2533         return self.mesh.IsPoly(id)
2534
2535     ## Returns true if the given element is quadratic
2536     #  @ingroup l1_meshinfo
2537     def IsQuadratic(self, id):
2538         return self.mesh.IsQuadratic(id)
2539
2540     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2541     #  @ingroup l1_meshinfo
2542     def GetBallDiameter(self, id):
2543         return self.mesh.GetBallDiameter(id)
2544
2545     ## Returns XYZ coordinates of the barycenter of the given element
2546     #  \n If there is no element for the given ID - returns an empty list
2547     #  @return a list of three double values
2548     #  @ingroup l1_meshinfo
2549     def BaryCenter(self, id):
2550         return self.mesh.BaryCenter(id)
2551
2552     ## Passes mesh elements through the given filter and return IDs of fitting elements
2553     #  @param theFilter SMESH_Filter
2554     #  @return a list of ids
2555     #  @ingroup l1_controls
2556     def GetIdsFromFilter(self, theFilter):
2557         theFilter.SetMesh( self.mesh )
2558         return theFilter.GetIDs()
2559
2560     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2561     #  Returns a list of special structures (borders).
2562     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2563     #  @ingroup l1_controls
2564     def GetFreeBorders(self):
2565         aFilterMgr = self.smeshpyD.CreateFilterManager()
2566         aPredicate = aFilterMgr.CreateFreeEdges()
2567         aPredicate.SetMesh(self.mesh)
2568         aBorders = aPredicate.GetBorders()
2569         aFilterMgr.UnRegister()
2570         return aBorders
2571
2572
2573     # Get mesh measurements information:
2574     # ------------------------------------
2575
2576     ## Get minimum distance between two nodes, elements or distance to the origin
2577     #  @param id1 first node/element id
2578     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2579     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2580     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2581     #  @return minimum distance value
2582     #  @sa GetMinDistance()
2583     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2584         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2585         return aMeasure.value
2586
2587     ## Get measure structure specifying minimum distance data between two objects
2588     #  @param id1 first node/element id
2589     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2590     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2591     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2592     #  @return Measure structure
2593     #  @sa MinDistance()
2594     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2595         if isElem1:
2596             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2597         else:
2598             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2599         if id2 != 0:
2600             if isElem2:
2601                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2602             else:
2603                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2604             pass
2605         else:
2606             id2 = None
2607
2608         aMeasurements = self.smeshpyD.CreateMeasurements()
2609         aMeasure = aMeasurements.MinDistance(id1, id2)
2610         genObjUnRegister([aMeasurements,id1, id2])
2611         return aMeasure
2612
2613     ## Get bounding box of the specified object(s)
2614     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2615     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2616     #  @c False specifies that @a objects are nodes
2617     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2618     #  @sa GetBoundingBox()
2619     def BoundingBox(self, objects=None, isElem=False):
2620         result = self.GetBoundingBox(objects, isElem)
2621         if result is None:
2622             result = (0.0,)*6
2623         else:
2624             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2625         return result
2626
2627     ## Get measure structure specifying bounding box data of the specified object(s)
2628     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2629     #  @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2630     #  @c False specifies that @a objects are nodes
2631     #  @return Measure structure
2632     #  @sa BoundingBox()
2633     def GetBoundingBox(self, IDs=None, isElem=False):
2634         if IDs is None:
2635             IDs = [self.mesh]
2636         elif isinstance(IDs, tuple):
2637             IDs = list(IDs)
2638         if not isinstance(IDs, list):
2639             IDs = [IDs]
2640         if len(IDs) > 0 and isinstance(IDs[0], int):
2641             IDs = [IDs]
2642         srclist = []
2643         unRegister = genObjUnRegister()
2644         for o in IDs:
2645             if isinstance(o, Mesh):
2646                 srclist.append(o.mesh)
2647             elif hasattr(o, "_narrow"):
2648                 src = o._narrow(SMESH.SMESH_IDSource)
2649                 if src: srclist.append(src)
2650                 pass
2651             elif isinstance(o, list):
2652                 if isElem:
2653                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2654                 else:
2655                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2656                 unRegister.set( srclist[-1] )
2657                 pass
2658             pass
2659         aMeasurements = self.smeshpyD.CreateMeasurements()
2660         unRegister.set( aMeasurements )
2661         aMeasure = aMeasurements.BoundingBox(srclist)
2662         return aMeasure
2663
2664     # Mesh edition (SMESH_MeshEditor functionality):
2665     # ---------------------------------------------
2666
2667     ## Removes the elements from the mesh by ids
2668     #  @param IDsOfElements is a list of ids of elements to remove
2669     #  @return True or False
2670     #  @ingroup l2_modif_del
2671     def RemoveElements(self, IDsOfElements):
2672         return self.editor.RemoveElements(IDsOfElements)
2673
2674     ## Removes nodes from mesh by ids
2675     #  @param IDsOfNodes is a list of ids of nodes to remove
2676     #  @return True or False
2677     #  @ingroup l2_modif_del
2678     def RemoveNodes(self, IDsOfNodes):
2679         return self.editor.RemoveNodes(IDsOfNodes)
2680
2681     ## Removes all orphan (free) nodes from mesh
2682     #  @return number of the removed nodes
2683     #  @ingroup l2_modif_del
2684     def RemoveOrphanNodes(self):
2685         return self.editor.RemoveOrphanNodes()
2686
2687     ## Add a node to the mesh by coordinates
2688     #  @return Id of the new node
2689     #  @ingroup l2_modif_add
2690     def AddNode(self, x, y, z):
2691         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2692         if hasVars: self.mesh.SetParameters(Parameters)
2693         return self.editor.AddNode( x, y, z)
2694
2695     ## Creates a 0D element on a node with given number.
2696     #  @param IDOfNode the ID of node for creation of the element.
2697     #  @return the Id of the new 0D element
2698     #  @ingroup l2_modif_add
2699     def Add0DElement(self, IDOfNode):
2700         return self.editor.Add0DElement(IDOfNode)
2701
2702     ## Create 0D elements on all nodes of the given elements except those 
2703     #  nodes on which a 0D element already exists.
2704     #  @param theObject an object on whose nodes 0D elements will be created.
2705     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2706     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2707     #  @param theGroupName optional name of a group to add 0D elements created
2708     #         and/or found on nodes of \a theObject.
2709     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2710     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2711     #          can be retrieved from the returned object by calling GetIDs()
2712     #  @ingroup l2_modif_add
2713     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2714         unRegister = genObjUnRegister()
2715         if isinstance( theObject, Mesh ):
2716             theObject = theObject.GetMesh()
2717         if isinstance( theObject, list ):
2718             theObject = self.GetIDSource( theObject, SMESH.ALL )
2719             unRegister.set( theObject )
2720         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2721
2722     ## Creates a ball element on a node with given ID.
2723     #  @param IDOfNode the ID of node for creation of the element.
2724     #  @param diameter the bal diameter.
2725     #  @return the Id of the new ball element
2726     #  @ingroup l2_modif_add
2727     def AddBall(self, IDOfNode, diameter):
2728         return self.editor.AddBall( IDOfNode, diameter )
2729
2730     ## Creates a linear or quadratic edge (this is determined
2731     #  by the number of given nodes).
2732     #  @param IDsOfNodes the list of node IDs for creation of the element.
2733     #  The order of nodes in this list should correspond to the description
2734     #  of MED. \n This description is located by the following link:
2735     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2736     #  @return the Id of the new edge
2737     #  @ingroup l2_modif_add
2738     def AddEdge(self, IDsOfNodes):
2739         return self.editor.AddEdge(IDsOfNodes)
2740
2741     ## Creates a linear or quadratic face (this is determined
2742     #  by the number of given nodes).
2743     #  @param IDsOfNodes the list of node IDs for creation of the element.
2744     #  The order of nodes in this list should correspond to the description
2745     #  of MED. \n This description is located by the following link:
2746     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2747     #  @return the Id of the new face
2748     #  @ingroup l2_modif_add
2749     def AddFace(self, IDsOfNodes):
2750         return self.editor.AddFace(IDsOfNodes)
2751
2752     ## Adds a polygonal face to the mesh by the list of node IDs
2753     #  @param IdsOfNodes the list of node IDs for creation of the element.
2754     #  @return the Id of the new face
2755     #  @ingroup l2_modif_add
2756     def AddPolygonalFace(self, IdsOfNodes):
2757         return self.editor.AddPolygonalFace(IdsOfNodes)
2758
2759     ## Creates both simple and quadratic volume (this is determined
2760     #  by the number of given nodes).
2761     #  @param IDsOfNodes the list of node IDs for creation of the element.
2762     #  The order of nodes in this list should correspond to the description
2763     #  of MED. \n This description is located by the following link:
2764     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2765     #  @return the Id of the new volumic element
2766     #  @ingroup l2_modif_add
2767     def AddVolume(self, IDsOfNodes):
2768         return self.editor.AddVolume(IDsOfNodes)
2769
2770     ## Creates a volume of many faces, giving nodes for each face.
2771     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2772     #  @param Quantities the list of integer values, Quantities[i]
2773     #         gives the quantity of nodes in face number i.
2774     #  @return the Id of the new volumic element
2775     #  @ingroup l2_modif_add
2776     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2777         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2778
2779     ## Creates a volume of many faces, giving the IDs of the existing faces.
2780     #  @param IdsOfFaces the list of face IDs for volume creation.
2781     #
2782     #  Note:  The created volume will refer only to the nodes
2783     #         of the given faces, not to the faces themselves.
2784     #  @return the Id of the new volumic element
2785     #  @ingroup l2_modif_add
2786     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2787         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2788
2789
2790     ## @brief Binds a node to a vertex
2791     #  @param NodeID a node ID
2792     #  @param Vertex a vertex or vertex ID
2793     #  @return True if succeed else raises an exception
2794     #  @ingroup l2_modif_add
2795     def SetNodeOnVertex(self, NodeID, Vertex):
2796         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2797             VertexID = Vertex.GetSubShapeIndices()[0]
2798         else:
2799             VertexID = Vertex
2800         try:
2801             self.editor.SetNodeOnVertex(NodeID, VertexID)
2802         except SALOME.SALOME_Exception, inst:
2803             raise ValueError, inst.details.text
2804         return True
2805
2806
2807     ## @brief Stores the node position on an edge
2808     #  @param NodeID a node ID
2809     #  @param Edge an edge or edge ID
2810     #  @param paramOnEdge a parameter on the edge where the node is located
2811     #  @return True if succeed else raises an exception
2812     #  @ingroup l2_modif_add
2813     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2814         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2815             EdgeID = Edge.GetSubShapeIndices()[0]
2816         else:
2817             EdgeID = Edge
2818         try:
2819             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2820         except SALOME.SALOME_Exception, inst:
2821             raise ValueError, inst.details.text
2822         return True
2823
2824     ## @brief Stores node position on a face
2825     #  @param NodeID a node ID
2826     #  @param Face a face or face ID
2827     #  @param u U parameter on the face where the node is located
2828     #  @param v V parameter on the face where the node is located
2829     #  @return True if succeed else raises an exception
2830     #  @ingroup l2_modif_add
2831     def SetNodeOnFace(self, NodeID, Face, u, v):
2832         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2833             FaceID = Face.GetSubShapeIndices()[0]
2834         else:
2835             FaceID = Face
2836         try:
2837             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2838         except SALOME.SALOME_Exception, inst:
2839             raise ValueError, inst.details.text
2840         return True
2841
2842     ## @brief Binds a node to a solid
2843     #  @param NodeID a node ID
2844     #  @param Solid  a solid or solid ID
2845     #  @return True if succeed else raises an exception
2846     #  @ingroup l2_modif_add
2847     def SetNodeInVolume(self, NodeID, Solid):
2848         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2849             SolidID = Solid.GetSubShapeIndices()[0]
2850         else:
2851             SolidID = Solid
2852         try:
2853             self.editor.SetNodeInVolume(NodeID, SolidID)
2854         except SALOME.SALOME_Exception, inst:
2855             raise ValueError, inst.details.text
2856         return True
2857
2858     ## @brief Bind an element to a shape
2859     #  @param ElementID an element ID
2860     #  @param Shape a shape or shape ID
2861     #  @return True if succeed else raises an exception
2862     #  @ingroup l2_modif_add
2863     def SetMeshElementOnShape(self, ElementID, Shape):
2864         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2865             ShapeID = Shape.GetSubShapeIndices()[0]
2866         else:
2867             ShapeID = Shape
2868         try:
2869             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2870         except SALOME.SALOME_Exception, inst:
2871             raise ValueError, inst.details.text
2872         return True
2873
2874
2875     ## Moves the node with the given id
2876     #  @param NodeID the id of the node
2877     #  @param x  a new X coordinate
2878     #  @param y  a new Y coordinate
2879     #  @param z  a new Z coordinate
2880     #  @return True if succeed else False
2881     #  @ingroup l2_modif_movenode
2882     def MoveNode(self, NodeID, x, y, z):
2883         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2884         if hasVars: self.mesh.SetParameters(Parameters)
2885         return self.editor.MoveNode(NodeID, x, y, z)
2886
2887     ## Finds the node closest to a point and moves it to a point location
2888     #  @param x  the X coordinate of a point
2889     #  @param y  the Y coordinate of a point
2890     #  @param z  the Z coordinate of a point
2891     #  @param NodeID if specified (>0), the node with this ID is moved,
2892     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
2893     #  @return the ID of a node
2894     #  @ingroup l2_modif_throughp
2895     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2896         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2897         if hasVars: self.mesh.SetParameters(Parameters)
2898         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2899
2900     ## Finds the node closest to a point
2901     #  @param x  the X coordinate of a point
2902     #  @param y  the Y coordinate of a point
2903     #  @param z  the Z coordinate of a point
2904     #  @return the ID of a node
2905     #  @ingroup l2_modif_throughp
2906     def FindNodeClosestTo(self, x, y, z):
2907         #preview = self.mesh.GetMeshEditPreviewer()
2908         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2909         return self.editor.FindNodeClosestTo(x, y, z)
2910
2911     ## Finds the elements where a point lays IN or ON
2912     #  @param x  the X coordinate of a point
2913     #  @param y  the Y coordinate of a point
2914     #  @param z  the Z coordinate of a point
2915     #  @param elementType type of elements to find (SMESH.ALL type
2916     #         means elements of any type excluding nodes, discrete and 0D elements)
2917     #  @param meshPart a part of mesh (group, sub-mesh) to search within
2918     #  @return list of IDs of found elements
2919     #  @ingroup l2_modif_throughp
2920     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2921         if meshPart:
2922             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2923         else:
2924             return self.editor.FindElementsByPoint(x, y, z, elementType)
2925
2926     # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2927     # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2928     # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2929
2930     def GetPointState(self, x, y, z):
2931         return self.editor.GetPointState(x, y, z)
2932
2933     ## Finds the node closest to a point and moves it to a point location
2934     #  @param x  the X coordinate of a point
2935     #  @param y  the Y coordinate of a point
2936     #  @param z  the Z coordinate of a point
2937     #  @return the ID of a moved node
2938     #  @ingroup l2_modif_throughp
2939     def MeshToPassThroughAPoint(self, x, y, z):
2940         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2941
2942     ## Replaces two neighbour triangles sharing Node1-Node2 link
2943     #  with the triangles built on the same 4 nodes but having other common link.
2944     #  @param NodeID1  the ID of the first node
2945     #  @param NodeID2  the ID of the second node
2946     #  @return false if proper faces were not found
2947     #  @ingroup l2_modif_invdiag
2948     def InverseDiag(self, NodeID1, NodeID2):
2949         return self.editor.InverseDiag(NodeID1, NodeID2)
2950
2951     ## Replaces two neighbour triangles sharing Node1-Node2 link
2952     #  with a quadrangle built on the same 4 nodes.
2953     #  @param NodeID1  the ID of the first node
2954     #  @param NodeID2  the ID of the second node
2955     #  @return false if proper faces were not found
2956     #  @ingroup l2_modif_unitetri
2957     def DeleteDiag(self, NodeID1, NodeID2):
2958         return self.editor.DeleteDiag(NodeID1, NodeID2)
2959
2960     ## Reorients elements by ids
2961     #  @param IDsOfElements if undefined reorients all mesh elements
2962     #  @return True if succeed else False
2963     #  @ingroup l2_modif_changori
2964     def Reorient(self, IDsOfElements=None):
2965         if IDsOfElements == None:
2966             IDsOfElements = self.GetElementsId()
2967         return self.editor.Reorient(IDsOfElements)
2968
2969     ## Reorients all elements of the object
2970     #  @param theObject mesh, submesh or group
2971     #  @return True if succeed else False
2972     #  @ingroup l2_modif_changori
2973     def ReorientObject(self, theObject):
2974         if ( isinstance( theObject, Mesh )):
2975             theObject = theObject.GetMesh()
2976         return self.editor.ReorientObject(theObject)
2977
2978     ## Reorient faces contained in \a the2DObject.
2979     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2980     #  @param theDirection is a desired direction of normal of \a theFace.
2981     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
2982     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2983     #         compared with theDirection. It can be either ID of face or a point
2984     #         by which the face will be found. The point can be given as either
2985     #         a GEOM vertex or a list of point coordinates.
2986     #  @return number of reoriented faces
2987     #  @ingroup l2_modif_changori
2988     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2989         unRegister = genObjUnRegister()
2990         # check the2DObject
2991         if isinstance( the2DObject, Mesh ):
2992             the2DObject = the2DObject.GetMesh()
2993         if isinstance( the2DObject, list ):
2994             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2995             unRegister.set( the2DObject )
2996         # check theDirection
2997         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2998             theDirection = self.smeshpyD.GetDirStruct( theDirection )
2999         if isinstance( theDirection, list ):
3000             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
3001         # prepare theFace and thePoint
3002         theFace = theFaceOrPoint
3003         thePoint = PointStruct(0,0,0)
3004         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3005             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3006             theFace = -1
3007         if isinstance( theFaceOrPoint, list ):
3008             thePoint = PointStruct( *theFaceOrPoint )
3009             theFace = -1
3010         if isinstance( theFaceOrPoint, PointStruct ):
3011             thePoint = theFaceOrPoint
3012             theFace = -1
3013         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3014
3015     ## Reorient faces according to adjacent volumes.
3016     #  @param the2DObject is a mesh, sub-mesh, group or list of
3017     #         either IDs of faces or face groups.
3018     #  @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3019     #  @param theOutsideNormal to orient faces to have their normals
3020     #         pointing either \a outside or \a inside the adjacent volumes.
3021     #  @return number of reoriented faces.
3022     #  @ingroup l2_modif_changori
3023     def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3024         unRegister = genObjUnRegister()
3025         # check the2DObject
3026         if not isinstance( the2DObject, list ):
3027             the2DObject = [ the2DObject ]
3028         elif the2DObject and isinstance( the2DObject[0], int ):
3029             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3030             unRegister.set( the2DObject )
3031             the2DObject = [ the2DObject ]
3032         for i,obj2D in enumerate( the2DObject ):
3033             if isinstance( obj2D, Mesh ):
3034                 the2DObject[i] = obj2D.GetMesh()
3035             if isinstance( obj2D, list ):
3036                 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3037                 unRegister.set( the2DObject[i] )
3038         # check the3DObject
3039         if isinstance( the3DObject, Mesh ):
3040             the3DObject = the3DObject.GetMesh()
3041         if isinstance( the3DObject, list ):
3042             the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3043             unRegister.set( the3DObject )
3044         return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3045
3046     ## Fuses the neighbouring triangles into quadrangles.
3047     #  @param IDsOfElements The triangles to be fused,
3048     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
3049     #                       choose a neighbour to fuse with.
3050     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
3051     #                       is still performed; theMaxAngle is mesured in radians.
3052     #                       Also it could be a name of variable which defines angle in degrees.
3053     #  @return TRUE in case of success, FALSE otherwise.
3054     #  @ingroup l2_modif_unitetri
3055     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3056         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3057         self.mesh.SetParameters(Parameters)
3058         if not IDsOfElements:
3059             IDsOfElements = self.GetElementsId()
3060         Functor = self.smeshpyD.GetFunctor(theCriterion)
3061         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3062
3063     ## Fuses the neighbouring triangles of the object into quadrangles
3064     #  @param theObject is mesh, submesh or group
3065     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3066     #         choose a neighbour to fuse with.
3067     #  @param MaxAngle   a max angle between element normals at which the fusion
3068     #                   is still performed; theMaxAngle is mesured in radians.
3069     #  @return TRUE in case of success, FALSE otherwise.
3070     #  @ingroup l2_modif_unitetri
3071     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3072         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3073         self.mesh.SetParameters(Parameters)
3074         if isinstance( theObject, Mesh ):
3075             theObject = theObject.GetMesh()
3076         Functor = self.smeshpyD.GetFunctor(theCriterion)
3077         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3078
3079     ## Splits quadrangles into triangles.
3080     #  @param IDsOfElements the faces to be splitted.
3081     #  @param theCriterion   is a numerical functor, in terms of enum SMESH.FunctorType, used to
3082     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3083     #         value, then quadrangles will be split by the smallest diagonal.
3084     #  @return TRUE in case of success, FALSE otherwise.
3085     #  @ingroup l2_modif_cutquadr
3086     def QuadToTri (self, IDsOfElements, theCriterion = None):
3087         if IDsOfElements == []:
3088             IDsOfElements = self.GetElementsId()
3089         if theCriterion is None:
3090             theCriterion = FT_MaxElementLength2D
3091         Functor = self.smeshpyD.GetFunctor(theCriterion)
3092         return self.editor.QuadToTri(IDsOfElements, Functor)
3093
3094     ## Splits quadrangles into triangles.
3095     #  @param theObject the object from which the list of elements is taken,
3096     #         this is mesh, submesh or group
3097     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3098     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3099     #         value, then quadrangles will be split by the smallest diagonal.
3100     #  @return TRUE in case of success, FALSE otherwise.
3101     #  @ingroup l2_modif_cutquadr
3102     def QuadToTriObject (self, theObject, theCriterion = None):
3103         if ( isinstance( theObject, Mesh )):
3104             theObject = theObject.GetMesh()
3105         if theCriterion is None:
3106             theCriterion = FT_MaxElementLength2D
3107         Functor = self.smeshpyD.GetFunctor(theCriterion)
3108         return self.editor.QuadToTriObject(theObject, Functor)
3109
3110     ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3111     #  a quadrangle.
3112     #  @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3113     #         group or a list of face IDs. By default all quadrangles are split
3114     #  @ingroup l2_modif_cutquadr
3115     def QuadTo4Tri (self, theElements=[]):
3116         unRegister = genObjUnRegister()
3117         if isinstance( theElements, Mesh ):
3118             theElements = theElements.mesh
3119         elif not theElements:
3120             theElements = self.mesh
3121         elif isinstance( theElements, list ):
3122             theElements = self.GetIDSource( theElements, SMESH.FACE )
3123             unRegister.set( theElements )
3124         return self.editor.QuadTo4Tri( theElements )
3125
3126     ## Splits quadrangles into triangles.
3127     #  @param IDsOfElements the faces to be splitted
3128     #  @param Diag13        is used to choose a diagonal for splitting.
3129     #  @return TRUE in case of success, FALSE otherwise.
3130     #  @ingroup l2_modif_cutquadr
3131     def SplitQuad (self, IDsOfElements, Diag13):
3132         if IDsOfElements == []:
3133             IDsOfElements = self.GetElementsId()
3134         return self.editor.SplitQuad(IDsOfElements, Diag13)
3135
3136     ## Splits quadrangles into triangles.
3137     #  @param theObject the object from which the list of elements is taken,
3138     #         this is mesh, submesh or group
3139     #  @param Diag13    is used to choose a diagonal for splitting.
3140     #  @return TRUE in case of success, FALSE otherwise.
3141     #  @ingroup l2_modif_cutquadr
3142     def SplitQuadObject (self, theObject, Diag13):
3143         if ( isinstance( theObject, Mesh )):
3144             theObject = theObject.GetMesh()
3145         return self.editor.SplitQuadObject(theObject, Diag13)
3146
3147     ## Finds a better splitting of the given quadrangle.
3148     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
3149     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
3150     #         choose a diagonal for splitting.
3151     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
3152     #          diagonal is better, 0 if error occurs.
3153     #  @ingroup l2_modif_cutquadr
3154     def BestSplit (self, IDOfQuad, theCriterion):
3155         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3156
3157     ## Splits volumic elements into tetrahedrons
3158     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3159     #  @param method  flags passing splitting method:
3160     #         smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3161     #         smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3162     #  @ingroup l2_modif_cutquadr
3163     def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3164         unRegister = genObjUnRegister()
3165         if isinstance( elems, Mesh ):
3166             elems = elems.GetMesh()
3167         if ( isinstance( elems, list )):
3168             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3169             unRegister.set( elems )
3170         self.editor.SplitVolumesIntoTetra(elems, method)
3171
3172     ## Splits hexahedra into prisms
3173     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3174     #  @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3175     #         gives a normal vector defining facets to split into triangles.
3176     #         @a startHexPoint can be either a triple of coordinates or a vertex.
3177     #  @param facetNormal a normal to a facet to split into triangles of a
3178     #         hexahedron found by @a startHexPoint.
3179     #         @a facetNormal can be either a triple of coordinates or an edge.
3180     #  @param method  flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3181     #         smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3182     #  @param allDomains if @c False, only hexahedra adjacent to one closest
3183     #         to @a startHexPoint are split, else @a startHexPoint
3184     #         is used to find the facet to split in all domains present in @a elems.
3185     #  @ingroup l2_modif_cutquadr
3186     def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3187                                  method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3188         # IDSource
3189         unRegister = genObjUnRegister()
3190         if isinstance( elems, Mesh ):
3191             elems = elems.GetMesh()
3192         if ( isinstance( elems, list )):
3193             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3194             unRegister.set( elems )
3195             pass
3196         # axis
3197         if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3198             startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3199         elif isinstance( startHexPoint, list ):
3200             startHexPoint = SMESH.PointStruct( startHexPoint[0],
3201                                                startHexPoint[1],
3202                                                startHexPoint[2])
3203         if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3204             facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3205         elif isinstance( facetNormal, list ):
3206             facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3207                                                        facetNormal[1],
3208                                                        facetNormal[2])
3209         self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3210
3211         self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3212
3213     ## Splits quadrangle faces near triangular facets of volumes
3214     #
3215     #  @ingroup l1_auxiliary
3216     def SplitQuadsNearTriangularFacets(self):
3217         faces_array = self.GetElementsByType(SMESH.FACE)
3218         for face_id in faces_array:
3219             if self.GetElemNbNodes(face_id) == 4: # quadrangle
3220                 quad_nodes = self.mesh.GetElemNodes(face_id)
3221                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3222                 isVolumeFound = False
3223                 for node1_elem in node1_elems:
3224                     if not isVolumeFound:
3225                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3226                             nb_nodes = self.GetElemNbNodes(node1_elem)
3227                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3228                                 volume_elem = node1_elem
3229                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3230                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3231                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3232                                         isVolumeFound = True
3233                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3234                                             self.SplitQuad([face_id], False) # diagonal 2-4
3235                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3236                                         isVolumeFound = True
3237                                         self.SplitQuad([face_id], True) # diagonal 1-3
3238                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3239                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3240                                         isVolumeFound = True
3241                                         self.SplitQuad([face_id], True) # diagonal 1-3
3242
3243     ## @brief Splits hexahedrons into tetrahedrons.
3244     #
3245     #  This operation uses pattern mapping functionality for splitting.
3246     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3247     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3248     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3249     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3250     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3251     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3252     #  @return TRUE in case of success, FALSE otherwise.
3253     #  @ingroup l1_auxiliary
3254     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3255         # Pattern:     5.---------.6
3256         #              /|#*      /|
3257         #             / | #*    / |
3258         #            /  |  # * /  |
3259         #           /   |   # /*  |
3260         # (0,0,1) 4.---------.7 * |
3261         #          |#*  |1   | # *|
3262         #          | # *.----|---#.2
3263         #          |  #/ *   |   /
3264         #          |  /#  *  |  /
3265         #          | /   # * | /
3266         #          |/      #*|/
3267         # (0,0,0) 0.---------.3
3268         pattern_tetra = "!!! Nb of points: \n 8 \n\
3269         !!! Points: \n\
3270         0 0 0  !- 0 \n\
3271         0 1 0  !- 1 \n\
3272         1 1 0  !- 2 \n\
3273         1 0 0  !- 3 \n\
3274         0 0 1  !- 4 \n\
3275         0 1 1  !- 5 \n\
3276         1 1 1  !- 6 \n\
3277         1 0 1  !- 7 \n\
3278         !!! Indices of points of 6 tetras: \n\
3279         0 3 4 1 \n\
3280         7 4 3 1 \n\
3281         4 7 5 1 \n\
3282         6 2 5 7 \n\
3283         1 5 2 7 \n\
3284         2 3 1 7 \n"
3285
3286         pattern = self.smeshpyD.GetPattern()
3287         isDone  = pattern.LoadFromFile(pattern_tetra)
3288         if not isDone:
3289             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3290             return isDone
3291
3292         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3293         isDone = pattern.MakeMesh(self.mesh, False, False)
3294         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3295
3296         # split quafrangle faces near triangular facets of volumes
3297         self.SplitQuadsNearTriangularFacets()
3298
3299         return isDone
3300
3301     ## @brief Split hexahedrons into prisms.
3302     #
3303     #  Uses the pattern mapping functionality for splitting.
3304     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3305     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3306     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3307     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3308     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3309     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3310     #  @return TRUE in case of success, FALSE otherwise.
3311     #  @ingroup l1_auxiliary
3312     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3313         # Pattern:     5.---------.6
3314         #              /|#       /|
3315         #             / | #     / |
3316         #            /  |  #   /  |
3317         #           /   |   # /   |
3318         # (0,0,1) 4.---------.7   |
3319         #          |    |    |    |
3320         #          |   1.----|----.2
3321         #          |   / *   |   /
3322         #          |  /   *  |  /
3323         #          | /     * | /
3324         #          |/       *|/
3325         # (0,0,0) 0.---------.3
3326         pattern_prism = "!!! Nb of points: \n 8 \n\
3327         !!! Points: \n\
3328         0 0 0  !- 0 \n\
3329         0 1 0  !- 1 \n\
3330         1 1 0  !- 2 \n\
3331         1 0 0  !- 3 \n\
3332         0 0 1  !- 4 \n\
3333         0 1 1  !- 5 \n\
3334         1 1 1  !- 6 \n\
3335         1 0 1  !- 7 \n\
3336         !!! Indices of points of 2 prisms: \n\
3337         0 1 3 4 5 7 \n\
3338         2 3 1 6 7 5 \n"
3339
3340         pattern = self.smeshpyD.GetPattern()
3341         isDone  = pattern.LoadFromFile(pattern_prism)
3342         if not isDone:
3343             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3344             return isDone
3345
3346         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3347         isDone = pattern.MakeMesh(self.mesh, False, False)
3348         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3349
3350         # Splits quafrangle faces near triangular facets of volumes
3351         self.SplitQuadsNearTriangularFacets()
3352
3353         return isDone
3354
3355     ## Smoothes elements
3356     #  @param IDsOfElements the list if ids of elements to smooth
3357     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3358     #  Note that nodes built on edges and boundary nodes are always fixed.
3359     #  @param MaxNbOfIterations the maximum number of iterations
3360     #  @param MaxAspectRatio varies in range [1.0, inf]
3361     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3362     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3363     #  @return TRUE in case of success, FALSE otherwise.
3364     #  @ingroup l2_modif_smooth
3365     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3366                MaxNbOfIterations, MaxAspectRatio, Method):
3367         if IDsOfElements == []:
3368             IDsOfElements = self.GetElementsId()
3369         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3370         self.mesh.SetParameters(Parameters)
3371         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3372                                   MaxNbOfIterations, MaxAspectRatio, Method)
3373
3374     ## Smoothes elements which belong to the given object
3375     #  @param theObject the object to smooth
3376     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3377     #  Note that nodes built on edges and boundary nodes are always fixed.
3378     #  @param MaxNbOfIterations the maximum number of iterations
3379     #  @param MaxAspectRatio varies in range [1.0, inf]
3380     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3381     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3382     #  @return TRUE in case of success, FALSE otherwise.
3383     #  @ingroup l2_modif_smooth
3384     def SmoothObject(self, theObject, IDsOfFixedNodes,
3385                      MaxNbOfIterations, MaxAspectRatio, Method):
3386         if ( isinstance( theObject, Mesh )):
3387             theObject = theObject.GetMesh()
3388         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3389                                         MaxNbOfIterations, MaxAspectRatio, Method)
3390
3391     ## Parametrically smoothes the given elements
3392     #  @param IDsOfElements the list if ids of elements to smooth
3393     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3394     #  Note that nodes built on edges and boundary nodes are always fixed.
3395     #  @param MaxNbOfIterations the maximum number of iterations
3396     #  @param MaxAspectRatio varies in range [1.0, inf]
3397     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3398     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3399     #  @return TRUE in case of success, FALSE otherwise.
3400     #  @ingroup l2_modif_smooth
3401     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3402                          MaxNbOfIterations, MaxAspectRatio, Method):
3403         if IDsOfElements == []:
3404             IDsOfElements = self.GetElementsId()
3405         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3406         self.mesh.SetParameters(Parameters)
3407         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3408                                             MaxNbOfIterations, MaxAspectRatio, Method)
3409
3410     ## Parametrically smoothes the elements which belong to the given object
3411     #  @param theObject the object to smooth
3412     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3413     #  Note that nodes built on edges and boundary nodes are always fixed.
3414     #  @param MaxNbOfIterations the maximum number of iterations
3415     #  @param MaxAspectRatio varies in range [1.0, inf]
3416     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3417     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3418     #  @return TRUE in case of success, FALSE otherwise.
3419     #  @ingroup l2_modif_smooth
3420     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3421                                MaxNbOfIterations, MaxAspectRatio, Method):
3422         if ( isinstance( theObject, Mesh )):
3423             theObject = theObject.GetMesh()
3424         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3425                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3426
3427     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3428     #  them with quadratic with the same id.
3429     #  @param theForce3d new node creation method:
3430     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3431     #         1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3432     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3433     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3434     #  @ingroup l2_modif_tofromqu
3435     def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3436         if isinstance( theSubMesh, Mesh ):
3437             theSubMesh = theSubMesh.mesh
3438         if theToBiQuad:
3439             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3440         else:
3441             if theSubMesh:
3442                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3443             else:
3444                 self.editor.ConvertToQuadratic(theForce3d)
3445         error = self.editor.GetLastError()
3446         if error and error.comment:
3447             print error.comment
3448             
3449     ## Converts the mesh from quadratic to ordinary,
3450     #  deletes old quadratic elements, \n replacing
3451     #  them with ordinary mesh elements with the same id.
3452     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3453     #  @ingroup l2_modif_tofromqu
3454     def ConvertFromQuadratic(self, theSubMesh=None):
3455         if theSubMesh:
3456             self.editor.ConvertFromQuadraticObject(theSubMesh)
3457         else:
3458             return self.editor.ConvertFromQuadratic()
3459
3460     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3461     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3462     #  @ingroup l2_modif_edit
3463     def  Make2DMeshFrom3D(self):
3464         return self.editor. Make2DMeshFrom3D()
3465
3466     ## Creates missing boundary elements
3467     #  @param elements - elements whose boundary is to be checked:
3468     #                    mesh, group, sub-mesh or list of elements
3469     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3470     #  @param dimension - defines type of boundary elements to create:
3471     #                     SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3472     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3473     #  @param groupName - a name of group to store created boundary elements in,
3474     #                     "" means not to create the group
3475     #  @param meshName - a name of new mesh to store created boundary elements in,
3476     #                     "" means not to create the new mesh
3477     #  @param toCopyElements - if true, the checked elements will be copied into
3478     #     the new mesh else only boundary elements will be copied into the new mesh
3479     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3480     #     boundary elements will be copied into the new mesh
3481     #  @return tuple (mesh, group) where boundary elements were added to
3482     #  @ingroup l2_modif_edit
3483     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3484                          toCopyElements=False, toCopyExistingBondary=False):
3485         unRegister = genObjUnRegister()
3486         if isinstance( elements, Mesh ):
3487             elements = elements.GetMesh()
3488         if ( isinstance( elements, list )):
3489             elemType = SMESH.ALL
3490             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3491             elements = self.editor.MakeIDSource(elements, elemType)
3492             unRegister.set( elements )
3493         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3494                                                    toCopyElements,toCopyExistingBondary)
3495         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3496         return mesh, group
3497
3498     ##
3499     # @brief Creates missing boundary elements around either the whole mesh or 
3500     #    groups of elements
3501     #  @param dimension - defines type of boundary elements to create
3502     #  @param groupName - a name of group to store all boundary elements in,
3503     #    "" means not to create the group
3504     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3505     #    mesh + created boundary elements; "" means not to create the new mesh
3506     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3507     #    the new mesh else only boundary elements will be copied into the new mesh
3508     #  @param groups - groups of elements to make boundary around
3509     #  @retval tuple( long, mesh, groups )
3510     #                 long - number of added boundary elements
3511     #                 mesh - the mesh where elements were added to
3512     #                 group - the group of boundary elements or None
3513     #
3514     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3515                              toCopyAll=False, groups=[]):
3516         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3517                                                            toCopyAll,groups)
3518         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3519         return nb, mesh, group
3520
3521     ## Renumber mesh nodes (Obsolete, does nothing)
3522     #  @ingroup l2_modif_renumber
3523     def RenumberNodes(self):
3524         self.editor.RenumberNodes()
3525
3526     ## Renumber mesh elements (Obsole, does nothing)
3527     #  @ingroup l2_modif_renumber
3528     def RenumberElements(self):
3529         self.editor.RenumberElements()
3530
3531     ## Private method converting \a arg into a list of SMESH_IdSource's
3532     def _getIdSourceList(self, arg, idType, unRegister):
3533         if arg and isinstance( arg, list ):
3534             if isinstance( arg[0], int ):
3535                 arg = self.GetIDSource( arg, idType )
3536                 unRegister.set( arg )
3537             elif isinstance( arg[0], Mesh ):
3538                 arg[0] = arg[0].GetMesh()
3539         elif isinstance( arg, Mesh ):
3540             arg = arg.GetMesh()
3541         if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3542             arg = [arg]
3543         return arg
3544
3545     ## Generates new elements by rotation of the given elements and nodes around the axis
3546     #  @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3547     #  @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3548     #  @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3549     #  @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3550     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3551     #         which defines angle in degrees
3552     #  @param NbOfSteps the number of steps
3553     #  @param Tolerance tolerance
3554     #  @param MakeGroups forces the generation of new groups from existing ones
3555     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3556     #                    of all steps, else - size of each step
3557     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3558     #  @ingroup l2_modif_extrurev
3559     def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3560                              MakeGroups=False, TotalAngle=False):
3561         unRegister = genObjUnRegister()
3562         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3563         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3564         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3565
3566         if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3567             Axis = self.smeshpyD.GetAxisStruct( Axis )
3568         if isinstance( Axis, list ):
3569             Axis = SMESH.AxisStruct( *Axis )
3570
3571         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3572         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3573         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3574         self.mesh.SetParameters(Parameters)
3575         if TotalAngle and NbOfSteps:
3576             AngleInRadians /= NbOfSteps
3577         return self.editor.RotationSweepObjects( nodes, edges, faces,
3578                                                  Axis, AngleInRadians,
3579                                                  NbOfSteps, Tolerance, MakeGroups)
3580
3581     ## Generates new elements by rotation of the elements around the axis
3582     #  @param IDsOfElements the list of ids of elements to sweep
3583     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3584     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3585     #  @param NbOfSteps the number of steps
3586     #  @param Tolerance tolerance
3587     #  @param MakeGroups forces the generation of new groups from existing ones
3588     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3589     #                    of all steps, else - size of each step
3590     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3591     #  @ingroup l2_modif_extrurev
3592     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3593                       MakeGroups=False, TotalAngle=False):
3594         return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3595                                          AngleInRadians, NbOfSteps, Tolerance,
3596                                          MakeGroups, TotalAngle)
3597
3598     ## Generates new elements by rotation of the elements of object around the axis
3599     #  @param theObject object which elements should be sweeped.
3600     #                   It can be a mesh, a sub mesh or a group.
3601     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3602     #  @param AngleInRadians the angle of Rotation
3603     #  @param NbOfSteps number of steps
3604     #  @param Tolerance tolerance
3605     #  @param MakeGroups forces the generation of new groups from existing ones
3606     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3607     #                    of all steps, else - size of each step
3608     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3609     #  @ingroup l2_modif_extrurev
3610     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3611                             MakeGroups=False, TotalAngle=False):
3612         return self.RotationSweepObjects( [], theObject, theObject, Axis,
3613                                           AngleInRadians, NbOfSteps, Tolerance,
3614                                           MakeGroups, TotalAngle )
3615
3616     ## Generates new elements by rotation of the elements of object around the axis
3617     #  @param theObject object which elements should be sweeped.
3618     #                   It can be a mesh, a sub mesh or a group.
3619     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3620     #  @param AngleInRadians the angle of Rotation
3621     #  @param NbOfSteps number of steps
3622     #  @param Tolerance tolerance
3623     #  @param MakeGroups forces the generation of new groups from existing ones
3624     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3625     #                    of all steps, else - size of each step
3626     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3627     #  @ingroup l2_modif_extrurev
3628     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3629                               MakeGroups=False, TotalAngle=False):
3630         return self.RotationSweepObjects([],theObject,[], Axis,
3631                                          AngleInRadians, NbOfSteps, Tolerance,
3632                                          MakeGroups, TotalAngle)
3633
3634     ## Generates new elements by rotation of the elements of object around the axis
3635     #  @param theObject object which elements should be sweeped.
3636     #                   It can be a mesh, a sub mesh or a group.
3637     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3638     #  @param AngleInRadians the angle of Rotation
3639     #  @param NbOfSteps number of steps
3640     #  @param Tolerance tolerance
3641     #  @param MakeGroups forces the generation of new groups from existing ones
3642     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3643     #                    of all steps, else - size of each step
3644     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3645     #  @ingroup l2_modif_extrurev
3646     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3647                               MakeGroups=False, TotalAngle=False):
3648         return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3649                                          NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3650
3651     ## Generates new elements by extrusion of the given elements and nodes
3652     #  @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3653     #  @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3654     #  @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3655     #  @param StepVector vector or DirStruct or 3 vector components, defining
3656     #         the direction and value of extrusion for one step (the total extrusion
3657     #         length will be NbOfSteps * ||StepVector||)
3658     #  @param NbOfSteps the number of steps
3659     #  @param MakeGroups forces the generation of new groups from existing ones
3660     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3661     #  @ingroup l2_modif_extrurev
3662     def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3663         unRegister = genObjUnRegister()
3664         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3665         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3666         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3667
3668         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3669             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3670         if isinstance( StepVector, list ):
3671             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3672
3673         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3674         Parameters = StepVector.PS.parameters + var_separator + Parameters
3675         self.mesh.SetParameters(Parameters)
3676
3677         return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3678                                                   StepVector, NbOfSteps, MakeGroups)
3679
3680
3681     ## Generates new elements by extrusion of the elements with given ids
3682     #  @param IDsOfElements the list of elements ids for extrusion
3683     #  @param StepVector vector or DirStruct or 3 vector components, defining
3684     #         the direction and value of extrusion for one step (the total extrusion
3685     #         length will be NbOfSteps * ||StepVector||)
3686     #  @param NbOfSteps the number of steps
3687     #  @param MakeGroups forces the generation of new groups from existing ones
3688     #  @param IsNodes is True if elements with given ids are nodes
3689     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3690     #  @ingroup l2_modif_extrurev
3691     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3692         n,e,f = [],[],[]
3693         if IsNodes: n = IDsOfElements
3694         else      : e,f, = IDsOfElements,IDsOfElements
3695         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3696
3697     ## Generates new elements by extrusion along the normal to a discretized surface or wire
3698     #  @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh
3699     #         Only faces can be extruded so far. Sub-mesh should be a sub-mesh on geom faces.
3700     #  @param StepSize length of one extrusion step (the total extrusion
3701     #         length will be \a NbOfSteps * \a StepSize ).
3702     #  @param NbOfSteps number of extrusion steps.
3703     #  @param ByAverageNormal if True each node is translated by \a StepSize
3704     #         along the average of the normal vectors to the faces sharing the node;
3705     #         else each node is translated along the same average normal till
3706     #         intersection with the plane got by translation of the face sharing
3707     #         the node along its own normal by \a StepSize.
3708     #  @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3709     #         for every node of \a Elements.
3710     #  @param MakeGroups forces generation of new groups from existing ones.
3711     #  @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3712     #         is not yet implemented. This parameter is used if \a Elements contains
3713     #         both faces and edges, i.e. \a Elements is a Mesh.
3714     #  @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3715     #          empty list otherwise.
3716     #  @ingroup l2_modif_extrurev
3717     def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3718                           ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3719         unRegister = genObjUnRegister()
3720         if isinstance( Elements, Mesh ):
3721             Elements = [ Elements.GetMesh() ]
3722         if isinstance( Elements, list ):
3723             if not Elements:
3724                 raise RuntimeError, "Elements empty!"
3725             if isinstance( Elements[0], int ):
3726                 Elements = self.GetIDSource( Elements, SMESH.ALL )
3727                 unRegister.set( Elements )
3728         if not isinstance( Elements, list ):
3729             Elements = [ Elements ]
3730         StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3731         self.mesh.SetParameters(Parameters)
3732         return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3733                                              ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3734
3735     ## Generates new elements by extrusion of the elements which belong to the object
3736     #  @param theObject the object which elements should be processed.
3737     #                   It can be a mesh, a sub mesh or a group.
3738     #  @param StepVector vector or DirStruct or 3 vector components, defining
3739     #         the direction and value of extrusion for one step (the total extrusion
3740     #         length will be NbOfSteps * ||StepVector||)
3741     #  @param NbOfSteps the number of steps
3742     #  @param MakeGroups forces the generation of new groups from existing ones
3743     #  @param  IsNodes is True if elements to extrude are nodes
3744     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3745     #  @ingroup l2_modif_extrurev
3746     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3747         n,e,f = [],[],[]
3748         if IsNodes: n    = theObject
3749         else      : e,f, = theObject,theObject
3750         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3751
3752     ## Generates new elements by extrusion of the elements which belong to the object
3753     #  @param theObject object which elements should be processed.
3754     #                   It can be a mesh, a sub mesh or a group.
3755     #  @param StepVector vector or DirStruct or 3 vector components, defining
3756     #         the direction and value of extrusion for one step (the total extrusion
3757     #         length will be NbOfSteps * ||StepVector||)
3758     #  @param NbOfSteps the number of steps
3759     #  @param MakeGroups to generate new groups from existing ones
3760     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3761     #  @ingroup l2_modif_extrurev
3762     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3763         return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3764
3765     ## Generates new elements by extrusion of the elements which belong to the object
3766     #  @param theObject object which elements should be processed.
3767     #                   It can be a mesh, a sub mesh or a group.
3768     #  @param StepVector vector or DirStruct or 3 vector components, defining
3769     #         the direction and value of extrusion for one step (the total extrusion
3770     #         length will be NbOfSteps * ||StepVector||)
3771     #  @param NbOfSteps the number of steps
3772     #  @param MakeGroups forces the generation of new groups from existing ones
3773     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3774     #  @ingroup l2_modif_extrurev
3775     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3776         return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3777
3778     ## Generates new elements by extrusion of the elements with given ids
3779     #  @param IDsOfElements is ids of elements
3780     #  @param StepVector vector or DirStruct or 3 vector components, defining
3781     #         the direction and value of extrusion for one step (the total extrusion
3782     #         length will be NbOfSteps * ||StepVector||)
3783     #  @param NbOfSteps the number of steps
3784     #  @param ExtrFlags sets flags for extrusion
3785     #  @param SewTolerance uses for comparing locations of nodes if flag
3786     #         EXTRUSION_FLAG_SEW is set
3787     #  @param MakeGroups forces the generation of new groups from existing ones
3788     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3789     #  @ingroup l2_modif_extrurev
3790     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3791                           ExtrFlags, SewTolerance, MakeGroups=False):
3792         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3793             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3794         if isinstance( StepVector, list ):
3795             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3796         return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3797                                              ExtrFlags, SewTolerance, MakeGroups)
3798
3799     ## Generates new elements by extrusion of the given elements and nodes along the path.
3800     #  The path of extrusion must be a meshed edge.
3801     #  @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3802     #  @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3803     #  @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3804     #  @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3805     #  @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3806     #         contains not only path segments, else it can be None
3807     #  @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3808     #  @param HasAngles allows the shape to be rotated around the path
3809     #                   to get the resulting mesh in a helical fashion
3810     #  @param Angles list of angles
3811     #  @param LinearVariation forces the computation of rotation angles as linear
3812     #                         variation of the given Angles along path steps
3813     #  @param HasRefPoint allows using the reference point
3814     #  @param RefPoint the point around which the shape is rotated (the mass center of the
3815     #         shape by default). The User can specify any point as the Reference Point.
3816     #  @param MakeGroups forces the generation of new groups from existing ones
3817     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3818     #  @ingroup l2_modif_extrurev
3819     def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3820                                   NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3821                                   HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3822         unRegister = genObjUnRegister()
3823         Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3824         Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3825         Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3826
3827         if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3828             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3829         if isinstance( RefPoint, list ):
3830             RefPoint = SMESH.PointStruct( *RefPoint )
3831         if isinstance( PathMesh, Mesh ):
3832             PathMesh = PathMesh.GetMesh()
3833         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3834         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3835         self.mesh.SetParameters(Parameters)
3836         return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3837                                                      PathMesh, PathShape, NodeStart,
3838                                                      HasAngles, Angles, LinearVariation,
3839                                                      HasRefPoint, RefPoint, MakeGroups)
3840
3841     ## Generates new elements by extrusion of the given elements
3842     #  The path of extrusion must be a meshed edge.
3843     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3844     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3845     #  @param NodeStart the start node from Path. Defines the direction of extrusion
3846     #  @param HasAngles allows the shape to be rotated around the path
3847     #                   to get the resulting mesh in a helical fashion
3848     #  @param Angles list of angles in radians
3849     #  @param LinearVariation forces the computation of rotation angles as linear
3850     #                         variation of the given Angles along path steps
3851     #  @param HasRefPoint allows using the reference point
3852     #  @param RefPoint the point around which the elements are rotated (the mass
3853     #         center of the elements by default).
3854     #         The User can specify any point as the Reference Point.
3855     #         RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3856     #  @param MakeGroups forces the generation of new groups from existing ones
3857     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
3858     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3859     #          only SMESH::Extrusion_Error otherwise
3860     #  @ingroup l2_modif_extrurev
3861     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3862                             HasAngles, Angles, LinearVariation,
3863                             HasRefPoint, RefPoint, MakeGroups, ElemType):
3864         n,e,f = [],[],[]
3865         if ElemType == SMESH.NODE: n = Base
3866         if ElemType == SMESH.EDGE: e = Base
3867         if ElemType == SMESH.FACE: f = Base
3868         gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
3869                                                HasAngles, Angles, LinearVariation,
3870                                                HasRefPoint, RefPoint, MakeGroups)
3871         if MakeGroups: return gr,er
3872         return er
3873
3874     ## Generates new elements by extrusion of the given elements
3875     #  The path of extrusion must be a meshed edge.
3876     #  @param IDsOfElements ids of elements
3877     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3878     #  @param PathShape shape(edge) defines the sub-mesh for the path
3879     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3880     #  @param HasAngles allows the shape to be rotated around the path
3881     #                   to get the resulting mesh in a helical fashion
3882     #  @param Angles list of angles in radians
3883     #  @param HasRefPoint allows using the reference point
3884     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3885     #         The User can specify any point as the Reference Point.
3886     #  @param MakeGroups forces the generation of new groups from existing ones
3887     #  @param LinearVariation forces the computation of rotation angles as linear
3888     #                         variation of the given Angles along path steps
3889     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3890     #          only SMESH::Extrusion_Error otherwise
3891     #  @ingroup l2_modif_extrurev
3892     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3893                            HasAngles, Angles, HasRefPoint, RefPoint,
3894                            MakeGroups=False, LinearVariation=False):
3895         n,e,f = [],IDsOfElements,IDsOfElements
3896         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
3897                                                NodeStart, HasAngles, Angles,
3898                                                LinearVariation,
3899                                                HasRefPoint, RefPoint, MakeGroups)
3900         if MakeGroups: return gr,er
3901         return er
3902
3903     ## Generates new elements by extrusion of the elements which belong to the object
3904     #  The path of extrusion must be a meshed edge.
3905     #  @param theObject the object which elements should be processed.
3906     #                   It can be a mesh, a sub-mesh or a group.
3907     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3908     #  @param PathShape shape(edge) defines the sub-mesh for the path
3909     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3910     #  @param HasAngles allows the shape to be rotated around the path
3911     #                   to get the resulting mesh in a helical fashion
3912     #  @param Angles list of angles
3913     #  @param HasRefPoint allows using the reference point
3914     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3915     #         The User can specify any point as the Reference Point.
3916     #  @param MakeGroups forces the generation of new groups from existing ones
3917     #  @param LinearVariation forces the computation of rotation angles as linear
3918     #                         variation of the given Angles along path steps
3919     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3920     #          only SMESH::Extrusion_Error otherwise
3921     #  @ingroup l2_modif_extrurev
3922     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3923                                  HasAngles, Angles, HasRefPoint, RefPoint,
3924                                  MakeGroups=False, LinearVariation=False):
3925         n,e,f = [],theObject,theObject
3926         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3927                                                HasAngles, Angles, LinearVariation,
3928                                                HasRefPoint, RefPoint, MakeGroups)
3929         if MakeGroups: return gr,er
3930         return er
3931
3932     ## Generates new elements by extrusion of the elements which belong to the object
3933     #  The path of extrusion must be a meshed edge.
3934     #  @param theObject the object which elements should be processed.
3935     #                   It can be a mesh, a sub mesh or a group.
3936     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3937     #  @param PathShape shape(edge) defines the sub-mesh for the path
3938     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3939     #  @param HasAngles allows the shape to be rotated around the path
3940     #                   to get the resulting mesh in a helical fashion
3941     #  @param Angles list of angles
3942     #  @param HasRefPoint allows using the reference point
3943     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3944     #         The User can specify any point as the Reference Point.
3945     #  @param MakeGroups forces the generation of new groups from existing ones
3946     #  @param LinearVariation forces the computation of rotation angles as linear
3947     #                         variation of the given Angles along path steps
3948     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3949     #          only SMESH::Extrusion_Error otherwise
3950     #  @ingroup l2_modif_extrurev
3951     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3952                                    HasAngles, Angles, HasRefPoint, RefPoint,
3953                                    MakeGroups=False, LinearVariation=False):
3954         n,e,f = [],theObject,[]
3955         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3956                                                HasAngles, Angles, LinearVariation,
3957                                                HasRefPoint, RefPoint, MakeGroups)
3958         if MakeGroups: return gr,er
3959         return er
3960
3961     ## Generates new elements by extrusion of the elements which belong to the object
3962     #  The path of extrusion must be a meshed edge.
3963     #  @param theObject the object which elements should be processed.
3964     #                   It can be a mesh, a sub mesh or a group.
3965     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3966     #  @param PathShape shape(edge) defines the sub-mesh for the path
3967     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3968     #  @param HasAngles allows the shape to be rotated around the path
3969     #                   to get the resulting mesh in a helical fashion
3970     #  @param Angles list of angles
3971     #  @param HasRefPoint allows using the reference point
3972     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3973     #         The User can specify any point as the Reference Point.
3974     #  @param MakeGroups forces the generation of new groups from existing ones
3975     #  @param LinearVariation forces the computation of rotation angles as linear
3976     #                         variation of the given Angles along path steps
3977     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3978     #          only SMESH::Extrusion_Error otherwise
3979     #  @ingroup l2_modif_extrurev
3980     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3981                                    HasAngles, Angles, HasRefPoint, RefPoint,
3982                                    MakeGroups=False, LinearVariation=False):
3983         n,e,f = [],[],theObject
3984         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3985                                                HasAngles, Angles, LinearVariation,
3986                                                HasRefPoint, RefPoint, MakeGroups)
3987         if MakeGroups: return gr,er
3988         return er
3989
3990     ## Creates a symmetrical copy of mesh elements
3991     #  @param IDsOfElements list of elements ids
3992     #  @param Mirror is AxisStruct or geom object(point, line, plane)
3993     #  @param theMirrorType is  POINT, AXIS or PLANE
3994     #  If the Mirror is a geom object this parameter is unnecessary
3995     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3996     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3997     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3998     #  @ingroup l2_modif_trsf
3999     def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4000         if IDsOfElements == []:
4001             IDsOfElements = self.GetElementsId()
4002         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4003             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4004             theMirrorType = Mirror._mirrorType
4005         else:
4006             self.mesh.SetParameters(Mirror.parameters)
4007         if Copy and MakeGroups:
4008             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4009         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4010         return []
4011
4012     ## Creates a new mesh by a symmetrical copy of mesh elements
4013     #  @param IDsOfElements the list of elements ids
4014     #  @param Mirror is AxisStruct or geom object (point, line, plane)
4015     #  @param theMirrorType is  POINT, AXIS or PLANE
4016     #  If the Mirror is a geom object this parameter is unnecessary
4017     #  @param MakeGroups to generate new groups from existing ones
4018     #  @param NewMeshName a name of the new mesh to create
4019     #  @return instance of Mesh class
4020     #  @ingroup l2_modif_trsf
4021     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4022         if IDsOfElements == []:
4023             IDsOfElements = self.GetElementsId()
4024         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4025             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4026             theMirrorType = Mirror._mirrorType
4027         else:
4028             self.mesh.SetParameters(Mirror.parameters)
4029         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4030                                           MakeGroups, NewMeshName)
4031         return Mesh(self.smeshpyD,self.geompyD,mesh)
4032
4033     ## Creates a symmetrical copy of the object
4034     #  @param theObject mesh, submesh or group
4035     #  @param Mirror AxisStruct or geom object (point, line, plane)
4036     #  @param theMirrorType is  POINT, AXIS or PLANE
4037     #  If the Mirror is a geom object this parameter is unnecessary
4038     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4039     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4040     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4041     #  @ingroup l2_modif_trsf
4042     def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4043         if ( isinstance( theObject, Mesh )):
4044             theObject = theObject.GetMesh()
4045         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4046             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4047             theMirrorType = Mirror._mirrorType
4048         else:
4049             self.mesh.SetParameters(Mirror.parameters)
4050         if Copy and MakeGroups:
4051             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4052         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4053         return []
4054
4055     ## Creates a new mesh by a symmetrical copy of the object
4056     #  @param theObject mesh, submesh or group
4057     #  @param Mirror AxisStruct or geom object (point, line, plane)
4058     #  @param theMirrorType POINT, AXIS or PLANE
4059     #  If the Mirror is a geom object this parameter is unnecessary
4060     #  @param MakeGroups forces the generation of new groups from existing ones
4061     #  @param NewMeshName the name of the new mesh to create
4062     #  @return instance of Mesh class
4063     #  @ingroup l2_modif_trsf
4064     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4065         if ( isinstance( theObject, Mesh )):
4066             theObject = theObject.GetMesh()
4067         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4068             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4069             theMirrorType = Mirror._mirrorType
4070         else:
4071             self.mesh.SetParameters(Mirror.parameters)
4072         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4073                                                 MakeGroups, NewMeshName)
4074         return Mesh( self.smeshpyD,self.geompyD,mesh )
4075
4076     ## Translates the elements
4077     #  @param IDsOfElements list of elements ids
4078     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4079     #  @param Copy allows copying the translated elements
4080     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4081     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4082     #  @ingroup l2_modif_trsf
4083     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4084         if IDsOfElements == []:
4085             IDsOfElements = self.GetElementsId()
4086         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4087             Vector = self.smeshpyD.GetDirStruct(Vector)
4088         if isinstance( Vector, list ):
4089             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4090         self.mesh.SetParameters(Vector.PS.parameters)
4091         if Copy and MakeGroups:
4092             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4093         self.editor.Translate(IDsOfElements, Vector, Copy)
4094         return []
4095
4096     ## Creates a new mesh of translated elements
4097     #  @param IDsOfElements list of elements ids
4098     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4099     #  @param MakeGroups forces the generation of new groups from existing ones
4100     #  @param NewMeshName the name of the newly created mesh
4101     #  @return instance of Mesh class
4102     #  @ingroup l2_modif_trsf
4103     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4104         if IDsOfElements == []:
4105             IDsOfElements = self.GetElementsId()
4106         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4107             Vector = self.smeshpyD.GetDirStruct(Vector)
4108         if isinstance( Vector, list ):
4109             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4110         self.mesh.SetParameters(Vector.PS.parameters)
4111         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4112         return Mesh ( self.smeshpyD, self.geompyD, mesh )
4113
4114     ## Translates the object
4115     #  @param theObject the object to translate (mesh, submesh, or group)
4116     #  @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4117     #  @param Copy allows copying the translated elements
4118     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4119     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4120     #  @ingroup l2_modif_trsf
4121     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4122         if ( isinstance( theObject, Mesh )):
4123             theObject = theObject.GetMesh()
4124         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4125             Vector = self.smeshpyD.GetDirStruct(Vector)
4126         if isinstance( Vector, list ):
4127             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4128         self.mesh.SetParameters(Vector.PS.parameters)
4129         if Copy and MakeGroups:
4130             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4131         self.editor.TranslateObject(theObject, Vector, Copy)
4132         return []
4133
4134     ## Creates a new mesh from the translated object
4135     #  @param theObject the object to translate (mesh, submesh, or group)
4136     #  @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4137     #  @param MakeGroups forces the generation of new groups from existing ones
4138     #  @param NewMeshName the name of the newly created mesh
4139     #  @return instance of Mesh class
4140     #  @ingroup l2_modif_trsf
4141     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4142         if isinstance( theObject, Mesh ):
4143             theObject = theObject.GetMesh()
4144         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4145             Vector = self.smeshpyD.GetDirStruct(Vector)
4146         if isinstance( Vector, list ):
4147             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4148         self.mesh.SetParameters(Vector.PS.parameters)
4149         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4150         return Mesh( self.smeshpyD, self.geompyD, mesh )
4151
4152
4153
4154     ## Scales the object
4155     #  @param theObject - the object to translate (mesh, submesh, or group)
4156     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4157     #  @param theScaleFact - list of 1-3 scale factors for axises
4158     #  @param Copy - allows copying the translated elements
4159     #  @param MakeGroups - forces the generation of new groups from existing
4160     #                      ones (if Copy)
4161     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4162     #          empty list otherwise
4163     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4164         unRegister = genObjUnRegister()
4165         if ( isinstance( theObject, Mesh )):
4166             theObject = theObject.GetMesh()
4167         if ( isinstance( theObject, list )):
4168             theObject = self.GetIDSource(theObject, SMESH.ALL)
4169             unRegister.set( theObject )
4170         if ( isinstance( thePoint, list )):
4171             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4172         if ( isinstance( theScaleFact, float )):
4173              theScaleFact = [theScaleFact]
4174         if ( isinstance( theScaleFact, int )):
4175              theScaleFact = [ float(theScaleFact)]
4176
4177         self.mesh.SetParameters(thePoint.parameters)
4178
4179         if Copy and MakeGroups:
4180             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4181         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4182         return []
4183
4184     ## Creates a new mesh from the translated object
4185     #  @param theObject - the object to translate (mesh, submesh, or group)
4186     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4187     #  @param theScaleFact - list of 1-3 scale factors for axises
4188     #  @param MakeGroups - forces the generation of new groups from existing ones
4189     #  @param NewMeshName - the name of the newly created mesh
4190     #  @return instance of Mesh class
4191     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4192         unRegister = genObjUnRegister()
4193         if (isinstance(theObject, Mesh)):
4194             theObject = theObject.GetMesh()
4195         if ( isinstance( theObject, list )):
4196             theObject = self.GetIDSource(theObject,SMESH.ALL)
4197             unRegister.set( theObject )
4198         if ( isinstance( thePoint, list )):
4199             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4200         if ( isinstance( theScaleFact, float )):
4201              theScaleFact = [theScaleFact]
4202         if ( isinstance( theScaleFact, int )):
4203              theScaleFact = [ float(theScaleFact)]
4204
4205         self.mesh.SetParameters(thePoint.parameters)
4206         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4207                                          MakeGroups, NewMeshName)
4208         return Mesh( self.smeshpyD, self.geompyD, mesh )
4209
4210
4211
4212     ## Rotates the elements
4213     #  @param IDsOfElements list of elements ids
4214     #  @param Axis the axis of rotation (AxisStruct or geom line)
4215     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4216     #  @param Copy allows copying the rotated elements
4217     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4218     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4219     #  @ingroup l2_modif_trsf
4220     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4221         if IDsOfElements == []:
4222             IDsOfElements = self.GetElementsId()
4223         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4224             Axis = self.smeshpyD.GetAxisStruct(Axis)
4225         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4226         Parameters = Axis.parameters + var_separator + Parameters
4227         self.mesh.SetParameters(Parameters)
4228         if Copy and MakeGroups:
4229             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4230         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4231         return []
4232
4233     ## Creates a new mesh of rotated elements
4234     #  @param IDsOfElements list of element ids
4235     #  @param Axis the axis of rotation (AxisStruct or geom line)
4236     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4237     #  @param MakeGroups forces the generation of new groups from existing ones
4238     #  @param NewMeshName the name of the newly created mesh
4239     #  @return instance of Mesh class
4240     #  @ingroup l2_modif_trsf
4241     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4242         if IDsOfElements == []:
4243             IDsOfElements = self.GetElementsId()
4244         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4245             Axis = self.smeshpyD.GetAxisStruct(Axis)
4246         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4247         Parameters = Axis.parameters + var_separator + Parameters
4248         self.mesh.SetParameters(Parameters)
4249         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4250                                           MakeGroups, NewMeshName)
4251         return Mesh( self.smeshpyD, self.geompyD, mesh )
4252
4253     ## Rotates the object
4254     #  @param theObject the object to rotate( mesh, submesh, or group)
4255     #  @param Axis the axis of rotation (AxisStruct or geom line)
4256     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4257     #  @param Copy allows copying the rotated elements
4258     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4259     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4260     #  @ingroup l2_modif_trsf
4261     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4262         if (isinstance(theObject, Mesh)):
4263             theObject = theObject.GetMesh()
4264         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4265             Axis = self.smeshpyD.GetAxisStruct(Axis)
4266         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4267         Parameters = Axis.parameters + ":" + Parameters
4268         self.mesh.SetParameters(Parameters)
4269         if Copy and MakeGroups:
4270             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4271         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4272         return []
4273
4274     ## Creates a new mesh from the rotated object
4275     #  @param theObject the object to rotate (mesh, submesh, or group)
4276     #  @param Axis the axis of rotation (AxisStruct or geom line)
4277     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
4278     #  @param MakeGroups forces the generation of new groups from existing ones
4279     #  @param NewMeshName the name of the newly created mesh
4280     #  @return instance of Mesh class
4281     #  @ingroup l2_modif_trsf
4282     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4283         if (isinstance( theObject, Mesh )):
4284             theObject = theObject.GetMesh()
4285         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4286             Axis = self.smeshpyD.GetAxisStruct(Axis)
4287         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4288         Parameters = Axis.parameters + ":" + Parameters
4289         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4290                                                        MakeGroups, NewMeshName)
4291         self.mesh.SetParameters(Parameters)
4292         return Mesh( self.smeshpyD, self.geompyD, mesh )
4293
4294     ## Finds groups of adjacent nodes within Tolerance.
4295     #  @param Tolerance the value of tolerance
4296     #  @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4297     #  @ingroup l2_modif_trsf
4298     def FindCoincidentNodes (self, Tolerance):
4299         return self.editor.FindCoincidentNodes(Tolerance)
4300
4301     ## Finds groups of ajacent nodes within Tolerance.
4302     #  @param Tolerance the value of tolerance
4303     #  @param SubMeshOrGroup SubMesh or Group
4304     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4305     #  @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4306     #  @ingroup l2_modif_trsf
4307     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4308         unRegister = genObjUnRegister()
4309         if (isinstance( SubMeshOrGroup, Mesh )):
4310             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4311         if not isinstance( exceptNodes, list):
4312             exceptNodes = [ exceptNodes ]
4313         if exceptNodes and isinstance( exceptNodes[0], int):
4314             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4315             unRegister.set( exceptNodes )
4316         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4317
4318     ## Merges nodes
4319     #  @param GroupsOfNodes a list of pairs of nodes IDs for merging
4320     #         (e.g. [[1,12],[25,4]], then nodes 12 and 4 will be removed and replaced
4321     #         by nodes 1 and 25 correspondingly in all elements and groups
4322     #  @ingroup l2_modif_trsf
4323     def MergeNodes (self, GroupsOfNodes):
4324         self.editor.MergeNodes(GroupsOfNodes)
4325
4326     ## Finds the elements built on the same nodes.
4327     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4328     #  @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4329     #  @ingroup l2_modif_trsf
4330     def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4331         if not MeshOrSubMeshOrGroup:
4332             MeshOrSubMeshOrGroup=self.mesh
4333         elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4334             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4335         return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4336
4337     ## Merges elements in each given group.
4338     #  @param GroupsOfElementsID a list of pairs of elements IDs for merging
4339     #        (e.g. [[1,12],[25,4]], then elements 12 and 4 will be removed and
4340     #        replaced by elements 1 and 25 in all groups)
4341     #  @ingroup l2_modif_trsf
4342     def MergeElements(self, GroupsOfElementsID):
4343         self.editor.MergeElements(GroupsOfElementsID)
4344
4345     ## Leaves one element and removes all other elements built on the same nodes.
4346     #  @ingroup l2_modif_trsf
4347     def MergeEqualElements(self):
4348         self.editor.MergeEqualElements()
4349
4350     ## Sews free borders
4351     #  @return SMESH::Sew_Error
4352     #  @ingroup l2_modif_trsf
4353     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4354                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4355                         CreatePolygons, CreatePolyedrs):
4356         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4357                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4358                                           CreatePolygons, CreatePolyedrs)
4359
4360     ## Sews conform free borders
4361     #  @return SMESH::Sew_Error
4362     #  @ingroup l2_modif_trsf
4363     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4364                                FirstNodeID2, SecondNodeID2):
4365         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4366                                                  FirstNodeID2, SecondNodeID2)
4367
4368     ## Sews border to side
4369     #  @return SMESH::Sew_Error
4370     #  @ingroup l2_modif_trsf
4371     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4372                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4373         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4374                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4375
4376     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4377     #  merged with the nodes of elements of Side2.
4378     #  The number of elements in theSide1 and in theSide2 must be
4379     #  equal and they should have similar nodal connectivity.
4380     #  The nodes to merge should belong to side borders and
4381     #  the first node should be linked to the second.
4382     #  @return SMESH::Sew_Error
4383     #  @ingroup l2_modif_trsf
4384     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4385                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4386                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4387         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4388                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4389                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4390
4391     ## Sets new nodes for the given element.
4392     #  @param ide the element id
4393     #  @param newIDs nodes ids
4394     #  @return If the number of nodes does not correspond to the type of element - returns false
4395     #  @ingroup l2_modif_edit
4396     def ChangeElemNodes(self, ide, newIDs):
4397         return self.editor.ChangeElemNodes(ide, newIDs)
4398
4399     ## If during the last operation of MeshEditor some nodes were
4400     #  created, this method returns the list of their IDs, \n
4401     #  if new nodes were not created - returns empty list
4402     #  @return the list of integer values (can be empty)
4403     #  @ingroup l1_auxiliary
4404     def GetLastCreatedNodes(self):
4405         return self.editor.GetLastCreatedNodes()
4406
4407     ## If during the last operation of MeshEditor some elements were
4408     #  created this method returns the list of their IDs, \n
4409     #  if new elements were not created - returns empty list
4410     #  @return the list of integer values (can be empty)
4411     #  @ingroup l1_auxiliary
4412     def GetLastCreatedElems(self):
4413         return self.editor.GetLastCreatedElems()
4414
4415     ## Clears sequences of nodes and elements created by mesh edition oparations
4416     #  @ingroup l1_auxiliary
4417     def ClearLastCreated(self):
4418         self.editor.ClearLastCreated()
4419
4420     ## Creates Duplicates given elements, i.e. creates new elements based on the 
4421     #  same nodes as the given ones.
4422     #  @param theElements - container of elements to duplicate. It can be a Mesh,
4423     #         sub-mesh, group, filter or a list of element IDs.
4424     # @param theGroupName - a name of group to contain the generated elements.
4425     #                    If a group with such a name already exists, the new elements
4426     #                    are added to the existng group, else a new group is created.
4427     #                    If \a theGroupName is empty, new elements are not added 
4428     #                    in any group.
4429     # @return a group where the new elements are added. None if theGroupName == "".
4430     #  @ingroup l2_modif_edit
4431     def DoubleElements(self, theElements, theGroupName=""):
4432         unRegister = genObjUnRegister()
4433         if isinstance( theElements, Mesh ):
4434             theElements = theElements.mesh
4435         elif isinstance( theElements, list ):
4436             theElements = self.GetIDSource( theElements, SMESH.ALL )
4437             unRegister.set( theElements )
4438         return self.editor.DoubleElements(theElements, theGroupName)
4439
4440     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4441     #  @param theNodes identifiers of nodes to be doubled
4442     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4443     #         nodes. If list of element identifiers is empty then nodes are doubled but
4444     #         they not assigned to elements
4445     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4446     #  @ingroup l2_modif_edit
4447     def DoubleNodes(self, theNodes, theModifiedElems):
4448         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4449
4450     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4451     #  This method provided for convenience works as DoubleNodes() described above.
4452     #  @param theNodeId identifiers of node to be doubled
4453     #  @param theModifiedElems identifiers of elements to be updated
4454     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4455     #  @ingroup l2_modif_edit
4456     def DoubleNode(self, theNodeId, theModifiedElems):
4457         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4458
4459     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4460     #  This method provided for convenience works as DoubleNodes() described above.
4461     #  @param theNodes group of nodes to be doubled
4462     #  @param theModifiedElems group of elements to be updated.
4463     #  @param theMakeGroup forces the generation of a group containing new nodes.
4464     #  @return TRUE or a created group if operation has been completed successfully,
4465     #          FALSE or None otherwise
4466     #  @ingroup l2_modif_edit
4467     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4468         if theMakeGroup:
4469             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4470         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4471
4472     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4473     #  This method provided for convenience works as DoubleNodes() described above.
4474     #  @param theNodes list of groups of nodes to be doubled
4475     #  @param theModifiedElems list of groups of elements to be updated.
4476     #  @param theMakeGroup forces the generation of a group containing new nodes.
4477     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4478     #  @ingroup l2_modif_edit
4479     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4480         if theMakeGroup:
4481             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4482         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4483
4484     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4485     #  @param theElems - the list of elements (edges or faces) to be replicated
4486     #         The nodes for duplication could be found from these elements
4487     #  @param theNodesNot - list of nodes to NOT replicate
4488     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4489     #         replicated nodes should be associated to.
4490     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4491     #  @ingroup l2_modif_edit
4492     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4493         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4494
4495     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4496     #  @param theElems - the list of elements (edges or faces) to be replicated
4497     #         The nodes for duplication could be found from these elements
4498     #  @param theNodesNot - list of nodes to NOT replicate
4499     #  @param theShape - shape to detect affected elements (element which geometric center
4500     #         located on or inside shape).
4501     #         The replicated nodes should be associated to affected elements.
4502     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4503     #  @ingroup l2_modif_edit
4504     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4505         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4506
4507     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4508     #  This method provided for convenience works as DoubleNodes() described above.
4509     #  @param theElems - group of of elements (edges or faces) to be replicated
4510     #  @param theNodesNot - group of nodes not to replicated
4511     #  @param theAffectedElems - group of elements to which the replicated nodes
4512     #         should be associated to.
4513     #  @param theMakeGroup forces the generation of a group containing new elements.
4514     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4515     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4516     #          FALSE or None otherwise
4517     #  @ingroup l2_modif_edit
4518     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4519                              theMakeGroup=False, theMakeNodeGroup=False):
4520         if theMakeGroup or theMakeNodeGroup:
4521             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4522                                                             theAffectedElems,
4523                                                             theMakeGroup, theMakeNodeGroup)
4524             if theMakeGroup and theMakeNodeGroup:
4525                 return twoGroups
4526             else:
4527                 return twoGroups[ int(theMakeNodeGroup) ]
4528         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4529
4530     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4531     #  This method provided for convenience works as DoubleNodes() described above.
4532     #  @param theElems - group of of elements (edges or faces) to be replicated
4533     #  @param theNodesNot - group of nodes not to replicated
4534     #  @param theShape - shape to detect affected elements (element which geometric center
4535     #         located on or inside shape).
4536     #         The replicated nodes should be associated to affected elements.
4537     #  @ingroup l2_modif_edit
4538     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4539         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4540
4541     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4542     #  This method provided for convenience works as DoubleNodes() described above.
4543     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4544     #  @param theNodesNot - list of groups of nodes not to replicated
4545     #  @param theAffectedElems - group of elements to which the replicated nodes
4546     #         should be associated to.
4547     #  @param theMakeGroup forces the generation of a group containing new elements.
4548     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4549     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4550     #          FALSE or None otherwise
4551     #  @ingroup l2_modif_edit
4552     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4553                              theMakeGroup=False, theMakeNodeGroup=False):
4554         if theMakeGroup or theMakeNodeGroup:
4555             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4556                                                              theAffectedElems,
4557                                                              theMakeGroup, theMakeNodeGroup)
4558             if theMakeGroup and theMakeNodeGroup:
4559                 return twoGroups
4560             else:
4561                 return twoGroups[ int(theMakeNodeGroup) ]
4562         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4563
4564     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4565     #  This method provided for convenience works as DoubleNodes() described above.
4566     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4567     #  @param theNodesNot - list of groups of nodes not to replicated
4568     #  @param theShape - shape to detect affected elements (element which geometric center
4569     #         located on or inside shape).
4570     #         The replicated nodes should be associated to affected elements.
4571     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4572     #  @ingroup l2_modif_edit
4573     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4574         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4575
4576     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4577     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4578     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4579     #  @param theNodesNot - list of groups of nodes not to replicated
4580     #  @param theShape - shape to detect affected elements (element which geometric center
4581     #         located on or inside shape).
4582     #         The replicated nodes should be associated to affected elements.
4583     #  @return groups of affected elements
4584     #  @ingroup l2_modif_edit
4585     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4586         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4587
4588     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4589     # The list of groups must describe a partition of the mesh volumes.
4590     # The nodes of the internal faces at the boundaries of the groups are doubled.
4591     # In option, the internal faces are replaced by flat elements.
4592     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4593     # @param theDomains - list of groups of volumes
4594     # @param createJointElems - if TRUE, create the elements
4595     # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4596     #        the boundary between \a theDomains and the rest mesh
4597     # @return TRUE if operation has been completed successfully, FALSE otherwise
4598     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4599        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4600
4601     ## Double nodes on some external faces and create flat elements.
4602     # Flat elements are mainly used by some types of mechanic calculations.
4603     #
4604     # Each group of the list must be constituted of faces.
4605     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4606     # @param theGroupsOfFaces - list of groups of faces
4607     # @return TRUE if operation has been completed successfully, FALSE otherwise
4608     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4609         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4610     
4611     ## identify all the elements around a geom shape, get the faces delimiting the hole
4612     #
4613     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4614         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4615
4616     def _getFunctor(self, funcType ):
4617         fn = self.functors[ funcType._v ]
4618         if not fn:
4619             fn = self.smeshpyD.GetFunctor(funcType)
4620             fn.SetMesh(self.mesh)
4621             self.functors[ funcType._v ] = fn
4622         return fn
4623
4624     ## Returns value of a functor for a given element
4625     #  @param funcType an item of SMESH.FunctorType enum
4626     #  @param elemId element or node ID
4627     #  @param isElem @a elemId is ID of element or node
4628     #  @return the functor value or zero in case of invalid arguments
4629     def FunctorValue(self, funcType, elemId, isElem=True):
4630         fn = self._getFunctor( funcType )
4631         if fn.GetElementType() == self.GetElementType(elemId, isElem):
4632             val = fn.GetValue(elemId)
4633         else:
4634             val = 0
4635         return val
4636
4637     ## Get length of 1D element or sum of lengths of all 1D mesh elements
4638     #  @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4639     #  @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4640     #  @ingroup l1_measurements
4641     def GetLength(self, elemId=None):
4642         length = 0
4643         if elemId == None:
4644             length = self.smeshpyD.GetLength(self)
4645         else:
4646             length = self.FunctorValue(SMESH.FT_Length, elemId)
4647         return length
4648
4649     ## Get area of 2D element or sum of areas of all 2D mesh elements
4650     #  @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4651     #  @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4652     #  @ingroup l1_measurements
4653     def GetArea(self, elemId=None):
4654         area = 0
4655         if elemId == None:
4656             area = self.smeshpyD.GetArea(self)
4657         else:
4658             area = self.FunctorValue(SMESH.FT_Area, elemId)
4659         return area
4660
4661     ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4662     #  @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4663     #  @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4664     #  @ingroup l1_measurements
4665     def GetVolume(self, elemId=None):
4666         volume = 0
4667         if elemId == None:
4668             volume = self.smeshpyD.GetVolume(self)
4669         else:
4670             volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4671         return volume
4672
4673     ## Get maximum element length.
4674     #  @param elemId mesh element ID
4675     #  @return element's maximum length value
4676     #  @ingroup l1_measurements
4677     def GetMaxElementLength(self, elemId):
4678         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4679             ftype = SMESH.FT_MaxElementLength3D
4680         else:
4681             ftype = SMESH.FT_MaxElementLength2D
4682         return self.FunctorValue(ftype, elemId)
4683
4684     ## Get aspect ratio of 2D or 3D element.
4685     #  @param elemId mesh element ID
4686     #  @return element's aspect ratio value
4687     #  @ingroup l1_measurements
4688     def GetAspectRatio(self, elemId):
4689         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4690             ftype = SMESH.FT_AspectRatio3D
4691         else:
4692             ftype = SMESH.FT_AspectRatio
4693         return self.FunctorValue(ftype, elemId)
4694
4695     ## Get warping angle of 2D element.
4696     #  @param elemId mesh element ID
4697     #  @return element's warping angle value
4698     #  @ingroup l1_measurements
4699     def GetWarping(self, elemId):
4700         return self.FunctorValue(SMESH.FT_Warping, elemId)
4701
4702     ## Get minimum angle of 2D element.
4703     #  @param elemId mesh element ID
4704     #  @return element's minimum angle value
4705     #  @ingroup l1_measurements
4706     def GetMinimumAngle(self, elemId):
4707         return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4708
4709     ## Get taper of 2D element.
4710     #  @param elemId mesh element ID
4711     #  @return element's taper value
4712     #  @ingroup l1_measurements
4713     def GetTaper(self, elemId):
4714         return self.FunctorValue(SMESH.FT_Taper, elemId)
4715
4716     ## Get skew of 2D element.
4717     #  @param elemId mesh element ID
4718     #  @return element's skew value
4719     #  @ingroup l1_measurements
4720     def GetSkew(self, elemId):
4721         return self.FunctorValue(SMESH.FT_Skew, elemId)
4722
4723     ## Return minimal and maximal value of a given functor.
4724     #  @param funType a functor type, an item of SMESH.FunctorType enum
4725     #         (one of SMESH.FunctorType._items)
4726     #  @param meshPart a part of mesh (group, sub-mesh) to treat
4727     #  @return tuple (min,max)
4728     #  @ingroup l1_measurements
4729     def GetMinMax(self, funType, meshPart=None):
4730         unRegister = genObjUnRegister()
4731         if isinstance( meshPart, list ):
4732             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4733             unRegister.set( meshPart )
4734         if isinstance( meshPart, Mesh ):
4735             meshPart = meshPart.mesh
4736         fun = self._getFunctor( funType )
4737         if fun:
4738             if meshPart:
4739                 hist = fun.GetLocalHistogram( 1, False, meshPart )
4740             else:
4741                 hist = fun.GetHistogram( 1, False )
4742             if hist:
4743                 return hist[0].min, hist[0].max
4744         return None
4745
4746     pass # end of Mesh class
4747
4748 ## class used to add to SMESH_MeshEditor methods removed from its CORBA API
4749 #
4750 class meshEditor(SMESH._objref_SMESH_MeshEditor):
4751     def __init__(self):
4752         SMESH._objref_SMESH_MeshEditor.__init__(self)
4753         self.mesh = None
4754     def __getattr__(self, name ): # method called if an attribute not found
4755         if not self.mesh:         # look for name() method in Mesh class
4756             self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
4757         if hasattr( self.mesh, name ):
4758             return getattr( self.mesh, name )
4759         if name == "ExtrusionAlongPathObjX":
4760             return getattr( self.mesh, "ExtrusionAlongPathX" )
4761         print name, "NOT FOUND"
4762         return None
4763     pass
4764 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
4765
4766 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4767 #
4768 class Pattern(SMESH._objref_SMESH_Pattern):
4769
4770     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4771         decrFun = lambda i: i-1
4772         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4773         theMesh.SetParameters(Parameters)
4774         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4775
4776     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4777         decrFun = lambda i: i-1
4778         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4779         theMesh.SetParameters(Parameters)
4780         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4781
4782 # Registering the new proxy for Pattern
4783 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4784
4785 ## Private class used to bind methods creating algorithms to the class Mesh
4786 #
4787 class algoCreator:
4788     def __init__(self):
4789         self.mesh = None
4790         self.defaultAlgoType = ""
4791         self.algoTypeToClass = {}
4792
4793     # Stores a python class of algorithm
4794     def add(self, algoClass):
4795         if type( algoClass ).__name__ == 'classobj' and \
4796            hasattr( algoClass, "algoType"):
4797             self.algoTypeToClass[ algoClass.algoType ] = algoClass
4798             if not self.defaultAlgoType and \
4799                hasattr( algoClass, "isDefault") and algoClass.isDefault:
4800                 self.defaultAlgoType = algoClass.algoType
4801             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4802
4803     # creates a copy of self and assign mesh to the copy
4804     def copy(self, mesh):
4805         other = algoCreator()
4806         other.defaultAlgoType = self.defaultAlgoType
4807         other.algoTypeToClass  = self.algoTypeToClass
4808         other.mesh = mesh
4809         return other
4810
4811     # creates an instance of algorithm
4812     def __call__(self,algo="",geom=0,*args):
4813         algoType = self.defaultAlgoType
4814         for arg in args + (algo,geom):
4815             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4816                 geom = arg
4817             if isinstance( arg, str ) and arg:
4818                 algoType = arg
4819         if not algoType and self.algoTypeToClass:
4820             algoType = self.algoTypeToClass.keys()[0]
4821         if self.algoTypeToClass.has_key( algoType ):
4822             #print "Create algo",algoType
4823             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4824         raise RuntimeError, "No class found for algo type %s" % algoType
4825         return None
4826
4827 # Private class used to substitute and store variable parameters of hypotheses.
4828 #
4829 class hypMethodWrapper:
4830     def __init__(self, hyp, method):
4831         self.hyp    = hyp
4832         self.method = method
4833         #print "REBIND:", method.__name__
4834         return
4835
4836     # call a method of hypothesis with calling SetVarParameter() before
4837     def __call__(self,*args):
4838         if not args:
4839             return self.method( self.hyp, *args ) # hypothesis method with no args
4840
4841         #print "MethWrapper.__call__",self.method.__name__, args
4842         try:
4843             parsed = ParseParameters(*args)     # replace variables with their values
4844             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4845             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4846         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4847             # maybe there is a replaced string arg which is not variable
4848             result = self.method( self.hyp, *args )
4849         except ValueError, detail: # raised by ParseParameters()
4850             try:
4851                 result = self.method( self.hyp, *args )
4852             except omniORB.CORBA.BAD_PARAM:
4853                 raise ValueError, detail # wrong variable name
4854
4855         return result
4856     pass
4857
4858 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4859 class genObjUnRegister:
4860
4861     def __init__(self, genObj=None):
4862         self.genObjList = []
4863         self.set( genObj )
4864         return
4865
4866     def set(self, genObj):
4867         "Store one or a list of of SALOME.GenericObj'es"
4868         if isinstance( genObj, list ):
4869             self.genObjList.extend( genObj )
4870         else:
4871             self.genObjList.append( genObj )
4872         return
4873
4874     def __del__(self):
4875         for genObj in self.genObjList:
4876             if genObj and hasattr( genObj, "UnRegister" ):
4877                 genObj.UnRegister()
4878
4879 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4880     #
4881     #print "pluginName: ", pluginName
4882     pluginBuilderName = pluginName + "Builder"
4883     try:
4884         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4885     except Exception, e:
4886         from salome_utils import verbose
4887         if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4888         continue
4889     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4890     plugin = eval( pluginBuilderName )
4891     #print "  plugin:" , str(plugin)
4892
4893     # add methods creating algorithms to Mesh
4894     for k in dir( plugin ):
4895         if k[0] == '_': continue
4896         algo = getattr( plugin, k )
4897         #print "             algo:", str(algo)
4898         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4899             #print "                     meshMethod:" , str(algo.meshMethod)
4900             if not hasattr( Mesh, algo.meshMethod ):
4901                 setattr( Mesh, algo.meshMethod, algoCreator() )
4902                 pass
4903             getattr( Mesh, algo.meshMethod ).add( algo )
4904             pass
4905         pass
4906     pass
4907 del pluginName