#http://www.salome-platform.org/forum/forum_11/418354072

import smesh, SMESH, geompy

# 1) Make a sample stl surface from a sphere

sphere = geompy.MakeSphere( 50,50,1, 30 )
import tempfile
f = tempfile.NamedTemporaryFile(suffix=".stl")
stlFile = f.name
f.close()
geompy.Export( sphere, stlFile, "STL_Bin" )

stlMesh = smesh.CreateMeshesFromSTL( stlFile )

# 2) Create a large box, whose one side represents a plane of interest

box = geompy.MakeBoxDXDYDZ( 200, 200, 200 )
geompy.addToStudy( box, "box")
boxForWorkAround = geompy.MakeScaleTransform( box,
                                              geompy.MakeCDG( box ),
                                              1.01 )
geompy.addToStudy( boxForWorkAround, "boxForWorkAround")
# 3) Create mesh groups on filter with "Belong to geom" and "Lying on
# geom" criteria. "Belong to geom" is to find triangles being fully
# inside the box and "Lying on geom", partially.

groupInsideBox = stlMesh.MakeGroup( "groupInsideBox", smesh.FACE,
                                    SMESH.FT_BelongToGeom, "=", box )
groupOutsideBox = stlMesh.MakeGroup( "groupOutsideBox", smesh.FACE,
                                     SMESH.FT_LyingOnGeom, "=", boxForWorkAround )
groupToCut = stlMesh.CutGroups( groupOutsideBox, groupInsideBox,"groupToCut")

# 4) Create geometrical triangles equal to the intersected triangles

geomTrias = []
for tria in groupToCut.GetIDs():
    points = []
    for n in stlMesh.GetElemNodes( tria ):
        xyz = stlMesh.GetNodeXYZ( n )
        points.append( geompy.MakeVertex( *xyz ))
    wire = geompy.MakePolyline( points, theIsClosed=True )
    face = geompy.MakeFace( wire, True )
    geomTrias.append( face )
geomTrias = geompy.MakeCompound( geomTrias )
geompy.addToStudy( geomTrias, "triaToCut" )

# 5) Find common of the geometrical triangles and the box used to create the
# groups on filters. Export them in an STL file.

common = geompy.MakeCommon( geomTrias, box )
geompy.Export( common, stlFile, "STL_Bin" )

# 6) Import the new STL file in MESH module, make a compound mesh of
# the group fully inside the box and the new STL mesh.

cutTriaMesh   = smesh.CreateMeshesFromSTL( stlFile )
insideBoxMesh = smesh.CopyMesh( groupInsideBox, "insideBoxMesh" )

finalMesh     = smesh.Concatenate( [cutTriaMesh, insideBoxMesh], False )
