Exemplo n.º 1
0
    def getSphericalMap( self, **args ):
        thetaResolution = args.get( "thetaRes", 32 )
        phiResolution = args.get( "phiRes", 32 )
        radius = args.get( "radius", 100 )
        if self.sphereActor == None: 
            self.sphere = vtk.vtkSphereSource()
            self.sphere.SetThetaResolution( thetaResolution )
            self.sphere.SetPhiResolution( phiResolution )
            self.sphere.SetRadius( radius )   
            self.sphere.SetEndTheta( 359.999 )    
            mesh = self.sphere.GetOutput()
            
            self.sphereTexmapper = vtk.vtkTextureMapToSphere()
            if vtk.VTK_MAJOR_VERSION <= 5:  self.sphereTexmapper.SetInput(mesh)
            else:                           self.sphereTexmapper.SetInputData(mesh)        
            self.sphereTexmapper.PreventSeamOff()
            
            self.sphereMapper = vtk.vtkPolyDataMapper()
            self.sphereMapper.SetInputConnection(self.sphereTexmapper.GetOutputPort())
                                   
            imageFlipper = vtk.vtkImageFlip()
            if vtk.VTK_MAJOR_VERSION <= 5:  imageFlipper.SetInput(self.sphericalBaseImage)
            else:                           imageFlipper.SetInputData(self.sphericalBaseImage)        
            imageFlipper.SetFilteredAxis( 1 ) 
            
            self.sphereTexture = vtk.vtkTexture()
            self.sphereTexture.SetInputConnection( imageFlipper.GetOutputPort()  )
            
            self.sphereActor = vtk.vtkActor()
            self.sphereActor.SetMapper(self.sphereMapper)
            self.sphereActor.SetTexture(self.sphereTexture)
#            self.sphereActor.GetProperty().SetOpacity( self.map_opacity )
            self.sphereActor.SetVisibility( False )  

        return self.sphereActor
Exemplo n.º 2
0
    def __init_renderer(self, list_of_planets):

        for planet in list_of_planets:
            actor = vtk.vtkActor()
            #sphere = vtk.vtkSphereSource()
            sphere = vtk.vtkTexturedSphereSource()
            mapper = vtk.vtkPolyDataMapper()
            sphere.SetPhiResolution(20)
            sphere.SetThetaResolution(20)
            scaled_radius = planet.get_radius() * self.__scale_planet_radius 
            if(planet.id == 0):
                scaled_radius = planet.get_radius() * self.__scale_sun_radius
            
            sphere.SetRadius(scaled_radius)
            mapper.SetInput(sphere.GetOutput())
            graphic_name = "../textures/"+planet.get_name()+".jpg"
            graphic_reader = vtk.vtkJPEGReader()
            graphic_reader.SetFileName(graphic_name)
            graphic_texture = vtk.vtkTexture()
            graphic_texture.SetInputConnection(graphic_reader.GetOutputPort())
            graphic_texture.InterpolateOn()
            actor.SetTexture(graphic_texture)
            actor.SetMapper(mapper)
            actor.SetScale(1,1,1)
            actor.SetPosition(int(self.__scale_planet_orbit_inner*planet.get_posVector_x()), 
                              int(self.__scale_planet_orbit_inner*planet.get_posVector_y()), 
                              int(self.__scale_planet_orbit_inner*planet.get_posVector_z()))
            self.__renderer.AddActor(actor)
            self.__list_of_actors.append(actor)
Exemplo n.º 3
0
    def addCube(self,pos,tam,img=False):
        jpegfile = "struct.jpg"
        
        # Read the image data from a file
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(jpegfile)
         
        (x,y,z) = pos
        (i,j,k) = tam

        cubito = vtk.vtkCubeSource()
        cubito.SetXLength(0.2*i)
        cubito.SetYLength(0.2*j)
        cubito.SetZLength(0.2*k)
        cubito.SetCenter((x,y,z)) 
        if img == True:
            
            # Create texture object
            texture = vtk.vtkTexture()
            if vtk.VTK_MAJOR_VERSION <= 5:
                texture.SetInput(reader.GetOutput())
            else:
                texture.SetInputConnection(reader.GetOutputPort())
            # Map texture coordinates
            map_to_sphere = vtk.vtkTextureMapToPlane()
            if vtk.VTK_MAJOR_VERSION <= 5:
                map_to_sphere.SetInput(cubito.GetOutput())
            else:
                map_to_sphere.SetInputConnection(cubito.GetOutputPort())
            #map_to_sphere.PreventSeamOn()
             
            # Create mapper and set the mapped texture as input
            mapper = vtk.vtkPolyDataMapper()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mapper.SetInput(map_to_sphere.GetOutput())
            else:
                mapper.SetInputConnection(map_to_sphere.GetOutputPort())
            
        

        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(cubito.GetOutputPort())
        planeActor = (vtk.vtkActor())
        if (img == True):
            planeActor.SetMapper(mapper)
        else:
            planeActor.SetMapper(planeMapper)# mapper planeMapper
        planeActor.DragableOn()
        planeActor.SetDragable(1)
        if (img== True):
            planeActor.SetTexture(texture)
        else:
            planeActor.GetProperty().SetColor(.0,.3,.6)
            planeActor.GetProperty().SetOpacity(0.95)
        #planeActor.GetProperty().SetAmbient(0)
        #planeActor.GetProperty().SetDiffuse(0.9)
        #planeActor.GetProperty().SetSpecular(0.1)
        self.render.AddActor(planeActor)
        
        return planeActor
def GetTexture(image_path):
    """
    Read an image and convert it to a texture
    :param image_path: The image path.
    :return: The texture.
    """
    # Read the image which will be the texture
    path = Path(image_path)
    if not path.is_file():
        print('Nonexistent texture file:', path)
        return None
    extension = path.suffix.lower()
    validExtensions = ['.jpg', '.png', '.bmp', '.tiff', '.pnm', '.pgm', '.ppm']
    if extension not in validExtensions:
        print('Unable to read the texture file (wrong extension):', path)
        return None
    texture = vtk.vtkTexture()
    # Read the images
    readerFactory = vtk.vtkImageReader2Factory()
    imgReader = readerFactory.CreateImageReader2(str(path))
    imgReader.SetFileName(str(path))

    texture.SetInputConnection(imgReader.GetOutputPort())
    texture.Update()

    return texture
Exemplo n.º 5
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkTexture(), 'Processing.',
         ('vtkImageData',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 6
0
def GetTexture(file_name):
    """
    Read an image and convert it to a texture
    :param file_name: The image path.
    :return: The texture.
    """
    # Read the image which will be the texture
    path, extension = os.path.splitext(file_name)
    extension = extension.lower()
    # Make the extension lowercase
    extension = extension.lower()
    validExtensions = ['.jpg', '.png', '.bmp', '.tiff', '.pnm', '.pgm', '.ppm']
    texture = vtk.vtkTexture()
    if not os.path.isfile(file_name):
        print('Nonexistent texture file:', file_name)
        return texture
    if extension not in validExtensions:
        print('Unable to read the texture file:', file_name)
        return texture
    # Read the images
    readerFactory = vtk.vtkImageReader2Factory()
    imgReader = readerFactory.CreateImageReader2(file_name)
    imgReader.SetFileName(file_name)

    texture.SetInputConnection(imgReader.GetOutputPort())
    texture.Update()
    texture.InterpolateOn()
    texture.MipmapOn()

    return texture
    def add_eye_ball(self, pose, orientation):
        # Eye ball
        sphere = vtk.vtkSphereSource()
        sphere.SetThetaResolution(64)
        sphere.SetPhiResolution(64)
        sphere.SetRadius(0.5)

        reader = vtk.vtkJPEGReader()
        reader.SetFileName(os.path.join(rospkg.RosPack().get_path('motion_renderer'), 'resource', 'green_eye.jpg'))

        texture = vtk.vtkTexture()
        texture.SetInputConnection(reader.GetOutputPort())

        map_to_sphere = vtk.vtkTextureMapToSphere()
        map_to_sphere.SetInputConnection(sphere.GetOutputPort())
        map_to_sphere.PreventSeamOn()

        xform = vtk.vtkTransformTextureCoords()
        xform.SetInputConnection(map_to_sphere.GetOutputPort())
        xform.SetScale(1.5, 1.5, 1)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(xform.GetOutputPort())

        # Left Eye Actor
        eye_actor = vtk.vtkActor()
        eye_actor.SetMapper(mapper)
        eye_actor.SetTexture(texture)
        eye_actor.SetPosition(pose[0], pose[1], pose[2])
        eye_actor.RotateX(orientation[0])
        eye_actor.RotateY(orientation[1])
        eye_actor.RotateZ(orientation[2])

        self.ren.AddActor(eye_actor)
        return eye_actor
Exemplo n.º 8
0
def insert_plane():
    img = 'floor.jpg'
    cube_source = vtk.vtkCubeSource()

    cube_source.SetCenter(0.49, 10, 10)
    cube_source.SetXLength(0.0010)
    cube_source.SetYLength(20)
    cube_source.SetZLength(20)
    cube_source.Update()

    reader = vtk.vtkJPEGReader()
    reader.SetFileName(img)

    # Create texture object
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    # Map texture coordinates
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(cube_source.GetOutputPort())

    # Create mapper and set the mapped texture as input
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(map_to_plane.GetOutputPort())

    # Create actor and set the mapper and the texture . uncomment if no texture

    #  mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputConnection(cube_source.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    return actor
Exemplo n.º 9
0
    def setActorTexture(self, actor, image_path):
        if actor.__class__ == Billboards.TextBillboard:
            # text billboards have no texture
            return
        if image_path[-4:].lower() == '.jpg' or image_path[-4:].lower(
        ) == '.jpeg':
            reader = vtk.vtkJPEGReader()
            reader.SetFileName(image_path)
            reader.Update()
        elif image_path[-4:].lower() == '.png':
            reader = vtk.vtkPNGReader()
            reader.SetFileName(image_path)
            reader.Update()
        texture = vtk.vtkTexture()
        texture.RepeatOn()
        texture.SetInputConnection(reader.GetOutputPort())

        actor.SetTexture(texture)

        # polydata = actor.GetMapper().GetInput()
        # pointdata = polydata.GetPointData()
        # celldata = polydata.GetCellData()
        # numtuples = celldata.GetNumberOfTuples()
        # numpolygons = polydata.GetNumberOfPolys()

        self.vtk_interactor.Render()
Exemplo n.º 10
0
 def showTexture(self):
     self.reader  = vtk.vtkJPEGReader()
     self.reader.SetFileName(os.path.join(os.path.split(__file__)[0], 'earth.jpg'))
     self.texture = vtk.vtkTexture()
     self.texture.SetInput(self.reader.GetOutput())
     self.sphere._actor.GetProperty().SetColor(1.0, 1.0, 1.0)
     self.sphere._actor.SetTexture(self.texture)
Exemplo n.º 11
0
def image_to_texture(image):
    """Converts ``vtkImageData`` (:class:`pyvista.UniformGrid`) to a ``vtkTexture``
    """
    vtex = vtk.vtkTexture()
    vtex.SetInputDataObject(image)
    vtex.Update()
    return vtex
Exemplo n.º 12
0
    def Texture(self, currentElement):
        self.logger.debug('  inside a <Texture> element: "%s"' % currentElement.get('name'))
        texture = vtk.vtkTexture()

        # Datatype(s) I need for input: ImageReader
        ImageReaderNode = ''
        for childElement in currentElement.getchildren():
            if childElement.tag in vtkTypes['ImageReader']:
                ImageReaderNode = childElement
        if ImageReaderNode != '':
            imageReader = self.namesToFunctions[ImageReaderNode.tag](ImageReaderNode)
            try:
                texture.SetInputConnection(imageReader.GetOutputPort())
            except:
                self.logger.error('  .. <Texture> failed to SetInputConnection')
        else:
            self.logger.error('  .. <Texture> needs an ImageReader-type childElement.')

        if 'SetRepeat' in currentElement.keys():
            try:
                texture.SetRepeat(int( currentElement.get('SetRepeat')))
            except:
                self.logger.error('  .. <Texture> failed to SetRepeat')
        if 'SetInterpolate' in currentElement.keys():
            try:
                texture.SetInterpolate(int( currentElement.get('SetInterpolate')))
            except:
                self.logger.error('  .. <Texture> failed to SetInterpolate')
        return texture
Exemplo n.º 13
0
def Model(model_path, model_image_path=None):
    if model_path[-4:].lower() == '.obj':
        reader = vtk.vtkOBJReader()
        reader.SetFileName(model_path)
        reader.Update()

        polyData = reader.GetOutput()

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(polyData)

        objActor = vtk.vtkActor()
        objActor.SetMapper(mapper)

        # texture from image
        if model_image_path is not None:
            texture = vtk.vtkTexture()

            if model_image_path[-4:].lower(
            ) == '.jpg' or model_image_path[-4:].lower() == '.jpeg':
                jpgReader = vtk.vtkJPEGReader()
                jpgReader.SetFileName(model_image_path)
                jpgReader.Update()
                texture.SetInputConnection(jpgReader.GetOutputPort())
            elif model_image_path[-4:].lower() == '.png':
                pngReader = vtk.vtkPNGReader()
                pngReader.SetFileName(model_image_path)
                pngReader.Update()
                texture.SetInputConnection(pngReader.GetOutputPort())

            objActor.SetTexture(texture)

        return objActor
Exemplo n.º 14
0
    def __init__(self, level=0, textureFile=TEXTURE, shift=0.5):

        self.transf = vtk.vtkTransform()
        self.globe = vtk.vtkTexturedSphereSource()
        self.texture = vtk.vtkTexture()

        #self.transf.Scale(0.25, 1., 1.)
        # may need to shift the picture to match the start longitude
        self.transf.Translate(shift, 0., 0.)
        self.texture.SetTransform(self.transf)
        self.texture.SetInterpolate(1)

        if re.search(r'jpe?g', textureFile.split('.')[-1]):
            self.reader = vtk.vtkJPEGReader()
        elif textureFile.split('.')[-1] == 'png':
            self.reader = vtk.vtkPNGReader()

        self.mapper = vtk.vtkPolyDataMapper()
        self.actor = vtk.vtkActor()

        # connect
        self.actor.SetMapper(self.mapper)
        self.actor.SetTexture(self.texture)

        self.mapper.SetInputConnection(self.globe.GetOutputPort())
        self.texture.SetInputConnection(self.reader.GetOutputPort())
        self.reader.SetFileName(textureFile)

        self.globe.SetThetaResolution(256)
        self.globe.SetPhiResolution(128)
        self.globe.SetRadius(1. + 0.01 * level)
Exemplo n.º 15
0
def ReadHDR(path):

    # hdr_equilateral=GetTexture(path)


    #read hdr https://blog.kitware.com/pbrj1/
    reader=vtk.vtkHDRReader()
    reader.SetFileName(path)
    reader.Update()

    texture=vtk.vtkTexture()
    texture.SetColorModeToDirectScalars()
    texture.MipmapOn()
    texture.InterpolateOn()
    texture.SetInputConnection(reader.GetOutputPort())
    texture.Update()
    # hdr_equilateral=texture

    # equi2cube = vtk.vtkEquirectangularToCubeMapTexture()
    # # help(equi2cube)
    # # print("nr outputs", equi2cube.GetNumberOfOutputPorts() )
    # # exit(1)
    # equi2cube.SetInputTexture(hdr_equilateral)
    # equi2cube.SetCubeMapSize(512)

    # return equi2cube
    return texture
Exemplo n.º 16
0
    def render_ground(self):
        self.ren.RemoveActor(self.ground_actor)
        if not self.config["GROUND"][0]:
            return
        ## Read the image
        png_reader = vtk.vtkPNGReader()
        png_reader.SetFileName(self.base_dir + self.data_folders["GROUND"])
        png_reader.Update()

        plane = vtk.vtkPlaneSource()
        plane.SetXResolution(500)
        plane.SetYResolution(500)
        plane.SetOrigin(0, 0, 0)
        plane.SetPoint1(1921, 0, 0)
        plane.SetPoint2(0, 2003.98, 0)

        atext = vtk.vtkTexture()
        atext.SetInputConnection(png_reader.GetOutputPort())
        atext.InterpolateOn()

        texturePlane = vtk.vtkTextureMapToPlane()
        texturePlane.SetInputConnection(plane.GetOutputPort())

        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(texturePlane.GetOutputPort())

        ## Position the primitives
        actor = vtk.vtkActor()
        actor.SetMapper(planeMapper)
        actor.SetTexture(atext)
        self.ground_actor = actor
        self.ren.AddActor(actor)
Exemplo n.º 17
0
 def create_texture_from_jpeg(jpeg_ifp):
     reader_jpeg = vtk.vtkJPEGReader()
     reader_jpeg.SetFileName(jpeg_ifp)
     reader_jpeg.Update()
     texture = vtk.vtkTexture()
     texture.SetInputData(reader_jpeg.GetOutput())
     texture.InterpolateOn()
     return texture
Exemplo n.º 18
0
def main():
    colors = vtk.vtkNamedColors()

    renWin = vtk.vtkRenderWindow()

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    aren = vtk.vtkRenderer()

    # define two elliptical cylinders
    quadric1 = vtk.vtkQuadric()
    quadric1.SetCoefficients(1, 2, 0, 0, 0, 0, 0, 0, 0, -.07)

    quadric2 = vtk.vtkQuadric()
    quadric2.SetCoefficients(2, 1, 0, 0, 0, 0, 0, 0, 0, -.07)

    # Create a sphere for all to use.
    aSphere = vtk.vtkSphereSource()
    aSphere.SetPhiResolution(21)
    aSphere.SetThetaResolution(21)

    # Create texture coordinates for all.
    tcoords = vtk.vtkImplicitTextureCoords()
    tcoords.SetInputConnection(aSphere.GetOutputPort())
    tcoords.SetRFunction(quadric1)
    tcoords.SetSFunction(quadric2)

    aMapper = vtk.vtkDataSetMapper()
    aMapper.SetInputConnection(tcoords.GetOutputPort())

    # Create a mapper, sphere and texture map for each case.
    for i in range(0, 16):
        aBoolean = MakeBooleanTexture(i, 64, 0)

        aTexture2 = vtk.vtkTexture()
        aTexture2.SetInputConnection(aBoolean.GetOutputPort())
        aTexture2.InterpolateOff()
        aTexture2.RepeatOff()

        anActor2 = vtk.vtkActor()

        anActor2.SetMapper(aMapper)
        anActor2.SetTexture(aTexture2)
        anActor2.SetPosition(positions[i])
        anActor2.SetScale(2.0, 2.0, 2.0)
        anActor2.GetProperty().SetColor(colors.GetColor3d('MistyRose'))
        aren.AddActor(anActor2)

    aren.SetBackground(colors.GetColor3d('SlateGray'))
    renWin.SetSize(500, 500)
    renWin.AddRenderer(aren)
    renWin.SetWindowName('TextureCutQuadric')

    # Interact with the data.
    renWin.Render()

    iren.Start()
Exemplo n.º 19
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkTexture(),
                                       'Processing.', ('vtkImageData', ),
                                       (),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemplo n.º 20
0
def get_texture():
    """
    Get texture from jpeg image
    """
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(TEXTURE_IMG)
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())
    return texture
Exemplo n.º 21
0
 def __init__(self):
     # ODE initialization
     self.world = ode.World()
     self.world.setGravity(GRAVITY)
     self.world.setERP(ERP)
     self.world.setCFM(CFM)
     self.space = ode.Space()
     self.floor = ode.GeomPlane(self.space, (0.0,1.0,0.0), 0.0)
     self.jointGroup = ode.JointGroup()
     self.time = 0.0
     # VTK initialization
     self.renderer = vtk.vtkRenderer()
     self.renderer.SetBackground(102.0/255.0,204/255.0,1.0)
     self.window = vtk.vtkRenderWindow()
     self.window.SetSize(WINDOW_WIDTH,WINDOW_HEIGHT)
     self.window.AddRenderer(self.renderer)
     self.interactor = vtk.vtkRenderWindowInteractor()
     self.interactor.SetRenderWindow(self.window)
     self.axes = vtk.vtkAxesActor()
     self.axes.SetAxisLabels(0)
     transform = vtk.vtkTransform()
     transform.Scale(0.1,0.1,0.1)
     self.axes.SetUserTransform(transform)
     self.renderer.AddActor(self.axes)
     # Create ground plane visualization
     self.floorVisual = vtk.vtkPlaneSource()
     self.floorVisual.SetNormal((0.0,1.0,0.0))
     self.floorVisual.SetResolution(10,10)
     self.floorReader = vtk.vtkJPEGReader()
     self.floorReader.SetFileName(FLOOR_IMAGE)
     self.floorTexture = vtk.vtkTexture()
     transform = vtk.vtkTransform()
     transform.Scale(50.0,50.0,50.0)
     self.floorTexture.SetTransform(transform)
     self.floorTexture.SetInput(self.floorReader.GetOutput())
     self.floorMap = vtk.vtkTextureMapToPlane()
     self.floorMap.SetInput(self.floorVisual.GetOutput())
     self.floorMapper = vtk.vtkPolyDataMapper()
     self.floorMapper.SetInput(self.floorMap.GetOutput())
     self.floorActor = vtk.vtkActor()
     transform = vtk.vtkTransform()
     transform.Scale(100.0,100.0,100.0)
     self.floorActor.SetUserTransform(transform)
     self.floorActor.SetMapper(self.floorMapper)
     self.floorActor.SetTexture(self.floorTexture)
     self.renderer.AddActor(self.floorActor)
     # VTK camera setup
     self.camera = vtk.vtkCamera()
     self.renderer.SetActiveCamera(self.camera)
     self.cameraFocus = [0.0, 0.0, 0.0]
     self.cameraPos = [4.0, 2.5, 1.5]
     self.cameraOffset = [0.0,1.0,3.0]
     self.cameraRoll = 0.0
     # Keep track of the simulated bodies and robots
     self.bodies = []
     self.robots = []
     self.controllers = []
Exemplo n.º 22
0
def generate_texture(texture_file):
    texture_file = read_file(texture_file)
    if(texture_file):
        texture = vtk.vtkTexture()
        texture.SetInputConnection(texture_file.GetOutputPort())
        texture.InterpolateOn()
    else: 
        texture = None
    return texture
Exemplo n.º 23
0
def create_3dquad_imageactor(image):
    w=image.shape[0]
    h=image.shape[1]
    p0 = [-w/2, h/2, 0.0]
    p1 = [w/2, h/2, 0.0]
    p2 = [w/2, -h/2, 0.0]
    p3 = [-w/2, -h/2, 0.0]
    
    points = vtk.vtkPoints()
    points.InsertNextPoint(p0)
    points.InsertNextPoint(p1)
    points.InsertNextPoint(p2)
    points.InsertNextPoint(p3)

    quad = vtk.vtkQuad()
    quad.GetPointIds().SetNumberOfIds(4)
    quad.GetPointIds().SetId(0,0)
    quad.GetPointIds().SetId(1,1)
    quad.GetPointIds().SetId(2,2)
    quad.GetPointIds().SetId(3,3)

    quads = vtk.vtkCellArray()
    quads.InsertNextCell(quad)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(quads)

    textureCoordinates = vtk.vtkFloatArray()
    textureCoordinates.SetNumberOfComponents(2)
    textureCoordinates.InsertNextTuple2(0.0, 0.0)
    textureCoordinates.InsertNextTuple2(1.0, 0.0)
    textureCoordinates.InsertNextTuple2(1.0, 1.0)
    textureCoordinates.InsertNextTuple2(0.0, 1.0)
    polydata.GetPointData().SetTCoords(textureCoordinates)
    
    reader = vtkImageImportFromArray()
    reader.SetArray(image)

    texture = vtk.vtkTexture()
    if vtk.VTK_MAJOR_VERSION <= 5:
        texture.SetInput(reader.GetOutput())
    else:
        texture.SetInputConnection(reader.GetOutputPort())

    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(polydata)
    else:
        mapper.SetInputData(polydata)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)

    return actor
Exemplo n.º 24
0
    def _MakeXYActors(self, reduce=1):
        # get a texture-mapped actor
        extent = self._ImageReslice.GetOutputExtent()
        origin = self._ImageReslice.GetOutputOrigin()
        spacing = self._ImageReslice.GetOutputSpacing()

        bounds = [
            origin[0] + spacing[0] * (extent[0] - 0.5),
            origin[0] + spacing[0] * (extent[1] + 0.5),
            origin[1] + spacing[1] * (extent[2] - 0.5),
            origin[1] + spacing[1] * (extent[3] + 0.5),
            origin[2] + spacing[2] * (extent[4] - 0.5),
            origin[2] + spacing[2] * (extent[5] + 0.5)
        ]

        for sliceNumber in range(extent[4], old_div((extent[5] + 1), reduce)):
            # the z position of the slice
            z = origin[2] + reduce * sliceNumber * spacing[2]

            plane = vtk.vtkPlaneSource()
            plane.SetXResolution(1)
            plane.SetYResolution(1)
            plane.SetOrigin(bounds[0], bounds[2], z)
            plane.SetPoint1(bounds[1], bounds[2], z)
            plane.SetPoint2(bounds[0], bounds[3], z)

            imageClip = vtk.vtkExtractVOI()
            imageClip.SetInput(self._ImageToStructuredPoints.GetOutput())
            imageClip.SetVOI(extent[0], extent[1], extent[2], extent[3],
                             reduce * sliceNumber, reduce * sliceNumber)
            imageClip.ReleaseDataFlagOn()

            texture = vtk.vtkTexture()
            texture.SetQualityTo32Bit()
            texture.SetInput(imageClip.GetOutput())
            texture.RepeatOff()
            texture.InterpolateOn()
            texture.MapColorScalarsThroughLookupTableOff()

            for i in range(3):
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(plane.GetOutput())
                mapper.SetClippingPlanes(self._ClippingPlanes[i])

                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                actor.SetTexture(texture)
                actor.PickableOff()
                actor.SetProperty(self._PropertyXY)

                self._PlanesXY.append(plane)
                self._ImageClipsXY.append(imageClip)
                self._ActorsXY.append(actor)

        numberOfPlanes = (extent[5] - extent[4] + 1) / reduce * 3
        return self._ActorsXY[-numberOfPlanes:]
Exemplo n.º 25
0
    def __init__(self, topic, color=(1, 0, 0)):
        self.bridge = CvBridge()
        self.vtkImage = None

        #Subscriber
        sub = rospy.Subscriber(topic, Image, self.imageCB, queue_size=1)
        self.texture = vtk.vtkTexture()
        self.texture.EdgeClampOff()
        self.color = color
        self.textureOnOff(False)
    def _MakeXYActors(self, reduce=1):
        # get a texture-mapped actor
        extent = self._ImageReslice.GetOutputExtent()
        origin = self._ImageReslice.GetOutputOrigin()
        spacing = self._ImageReslice.GetOutputSpacing()

        bounds = [origin[0] + spacing[0] * (extent[0] - 0.5),
                  origin[0] + spacing[0] * (extent[1] + 0.5),
                  origin[1] + spacing[1] * (extent[2] - 0.5),
                  origin[1] + spacing[1] * (extent[3] + 0.5),
                  origin[2] + spacing[2] * (extent[4] - 0.5),
                  origin[2] + spacing[2] * (extent[5] + 0.5)]

        for sliceNumber in range(extent[4], old_div((extent[5] + 1), reduce)):
            # the z position of the slice
            z = origin[2] + reduce * sliceNumber * spacing[2]

            plane = vtk.vtkPlaneSource()
            plane.SetXResolution(1)
            plane.SetYResolution(1)
            plane.SetOrigin(bounds[0], bounds[2], z)
            plane.SetPoint1(bounds[1], bounds[2], z)
            plane.SetPoint2(bounds[0], bounds[3], z)

            imageClip = vtk.vtkExtractVOI()
            imageClip.SetInput(self._ImageToStructuredPoints.GetOutput())
            imageClip.SetVOI(extent[0], extent[1],
                             extent[2], extent[3],
                             reduce * sliceNumber, reduce * sliceNumber)
            imageClip.ReleaseDataFlagOn()

            texture = vtk.vtkTexture()
            texture.SetQualityTo32Bit()
            texture.SetInput(imageClip.GetOutput())
            texture.RepeatOff()
            texture.InterpolateOn()
            texture.MapColorScalarsThroughLookupTableOff()

            for i in range(3):
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInput(plane.GetOutput())
                mapper.SetClippingPlanes(self._ClippingPlanes[i])

                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                actor.SetTexture(texture)
                actor.PickableOff()
                actor.SetProperty(self._PropertyXY)

                self._PlanesXY.append(plane)
                self._ImageClipsXY.append(imageClip)
                self._ActorsXY.append(actor)

        numberOfPlanes = (extent[5] - extent[4] + 1) / reduce * 3
        return self._ActorsXY[-numberOfPlanes:]
Exemplo n.º 27
0
def main(argv):
    colors = vtk.vtkNamedColors()

    if (len(argv) < 2):
        print("Usage: " + argv[0] + " texture(.png/.ppm) e.g. earth.ppm" +
              " [translate]")
        sys.exit(-1)
    translate = [0.0, 0.0, 0.0]
    if len(argv) > 2:
        translate[0] = float(argv[2])
    else:
        translate[0] = 0.0
    translate[1] = 0.0
    translate[2] = 0.0
    print("%f, %f, %f" % (translate[0], translate[1], translate[2]))

    # Create a sphere with texture coordinates
    source = vtk.vtkTexturedSphereSource()
    source.SetThetaResolution(100)
    source.SetPhiResolution(100)

    # Read texture file
    readerFactory = vtk.vtkImageReader2Factory()
    # imageReader = vtk.vtkImageReader2()
    imageReader = readerFactory.CreateImageReader2(argv[1])
    imageReader.SetFileName(argv[1])

    # Create texture
    texture = vtk.vtkTexture()
    texture.SetInputConnection(imageReader.GetOutputPort())

    transformTexture = vtk.vtkTransformTextureCoords()
    transformTexture.SetInputConnection(source.GetOutputPort())
    transformTexture.SetPosition(translate)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(transformTexture.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("Black"))

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName("TexturedSphere")

    renWinInteractor = vtk.vtkRenderWindowInteractor()
    renWinInteractor.SetRenderWindow(renderWindow)

    renderWindow.Render()
    renWinInteractor.Start()
Exemplo n.º 28
0
    def test_vtk_shananigans(self):
        sphere = vtk.vtkPointSource()
        sphere.SetNumberOfPoints(25)
        mesh = Mesh("data/wing_off_files/synth_wing_v3.off")
        # Triangulate the points with vtkDelaunay3D. This generates a convex hull
        # of tetrahedron.
        delny = vtk.vtkDelaunay3D()
        delny.SetInputConnection(sphere.GetOutputPort())
        delny.SetTolerance(0.01)
        print(dir(mesh.pv_mesh))
        # The triangulation has texture coordinates generated so we can map
        # a texture onto it.
        tmapper = vtk.vtkTextureMapToCylinder()
        tmapper.SetInputDataObject(mesh.pv_mesh.GetPointData().GetOutputPort())
        tmapper.PreventSeamOn()

        # We scale the texture coordinate to get some repeat patterns.
        xform = vtk.vtkTransformTextureCoords()
        xform.SetInputConnection(tmapper.GetOutputPort())
        xform.SetScale(4, 4, 1)

        # vtkDataSetMapper internally uses a vtkGeometryFilter to extract the
        # surface from the triangulation. The output (which is vtkPolyData) is
        # then passed to an internal vtkPolyDataMapper which does the
        # rendering.
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(xform.GetOutputPort())

        # A texture is loaded using an image reader. Textures are simply images.
        # The texture is eventually associated with an actor.
        bmpReader = vtk.vtkPNGReader()
        bmpReader.SetFileName("data/textures/checkers.png")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(bmpReader.GetOutputPort())
        atext.InterpolateOn()
        triangulation = vtk.vtkActor()
        triangulation.SetMapper(mapper)
        triangulation.SetTexture(atext)

        # Create the standard rendering stuff.
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # Add the actors to the renderer, set the background and size
        ren.AddActor(triangulation)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(300, 300)

        iren.Initialize()
        renWin.Render()
        iren.Start()
Exemplo n.º 29
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()

    # Load in the texture map. A texture is any unsigned char image. If it
    # is not of this type, you will have to map it through a lookup table
    # or by using vtkImageShiftScale.
    #
    readerFactory = vtk.vtkImageReader2Factory()
    textureFile = readerFactory.CreateImageReader2(fileName)
    textureFile.SetFileName(fileName)
    textureFile.Update()

    atext = vtk.vtkTexture()
    atext.SetInputConnection(textureFile.GetOutputPort())
    atext.InterpolateOn()

    # Create a plane source and actor. The vtkPlanesSource generates
    # texture coordinates.
    #
    plane = vtk.vtkPlaneSource()

    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputConnection(plane.GetOutputPort())

    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)
    planeActor.SetTexture(atext)

    # Create the RenderWindow, Renderer and Interactor.
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    renderer.AddActor(planeActor)
    renderer.SetBackground(colors.GetColor3d('DarkSlateGray'))
    renWin.SetSize(640, 480)
    renWin.SetWindowName('TexturePlane')

    # render the image
    renWin.Render()

    renderer.ResetCamera()
    renderer.GetActiveCamera().Elevation(-30)
    renderer.GetActiveCamera().Roll(-20)
    renderer.ResetCameraClippingRange()
    renWin.Render()
    iren.Start()
Exemplo n.º 30
0
def GetTexture(file_name):
    r = vtk.vtkImageReader2Factory.CreateImageReader2(file_name)
    # r = vtk.vtkPNGReader()
    r.SetFileName(file_name)
    r.Update()

    t = vtk.vtkTexture()
    t.SetInputConnection(r.GetOutputPort())
    # t.SetBlendingMode(vtk.vtkTexture.VTK_TEXTURE_BLENDING_MODE_NONE)

    # dims = r.GetOutput().GetDimensions()
    # print(dims)
    return t
Exemplo n.º 31
0
def TexturedQuad(numpy_array, image_path):
    if np.shape(numpy_array)[0] == 3:
        numpy_array = np.transpose(numpy_array)

    if image_path[-4:].lower() == '.jpg' or image_path[-4:].lower() == '.jpeg':
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(image_path)
        reader.Update()
    elif image_path[-4:].lower() == '.png':
        reader = vtk.vtkPNGReader()
        reader.SetFileName(image_path)
        reader.Update()
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    points = vtk.vtkPoints()
    points.SetNumberOfPoints(4)
    points.SetData(nps.numpy_to_vtk(numpy_array, deep=1))

    quad = vtk.vtkQuad()
    quad.GetPointIds().SetId(0, 0)
    quad.GetPointIds().SetId(1, 1)
    quad.GetPointIds().SetId(2, 2)
    quad.GetPointIds().SetId(3, 3)

    quads = vtk.vtkCellArray()
    quads.InsertNextCell(quad)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(quads)

    texCoords = vtk.vtkFloatArray()
    texCoords.SetNumberOfComponents(2)
    texCoords.SetName("TextureCoordinates")
    texCoords.InsertNextTuple((0.0, 0.0))
    texCoords.InsertNextTuple((1.0, 0.0))
    texCoords.InsertNextTuple((1.0, 1.0))
    texCoords.InsertNextTuple((0.0, 1.0))

    polydata.GetPointData().SetTCoords(texCoords)

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(polydata)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)

    return actor
Exemplo n.º 32
0
    def _setup(self):
        """Setup this UI Component.

        Return an image as a 2D actor with a specific position.

        Returns
        -------
        :class:`vtkTexturedActor2D`
        """
        self.texture_polydata = vtk.vtkPolyData()
        self.texture_points = vtk.vtkPoints()
        self.texture_points.SetNumberOfPoints(4)

        polys = vtk.vtkCellArray()
        polys.InsertNextCell(4)
        polys.InsertCellPoint(0)
        polys.InsertCellPoint(1)
        polys.InsertCellPoint(2)
        polys.InsertCellPoint(3)
        self.texture_polydata.SetPolys(polys)

        tc = vtk.vtkFloatArray()
        tc.SetNumberOfComponents(2)
        tc.SetNumberOfTuples(4)
        tc.InsertComponent(0, 0, 0.0)
        tc.InsertComponent(0, 1, 0.0)
        tc.InsertComponent(1, 0, 1.0)
        tc.InsertComponent(1, 1, 0.0)
        tc.InsertComponent(2, 0, 1.0)
        tc.InsertComponent(2, 1, 1.0)
        tc.InsertComponent(3, 0, 0.0)
        tc.InsertComponent(3, 1, 1.0)
        self.texture_polydata.GetPointData().SetTCoords(tc)

        texture_mapper = vtk.vtkPolyDataMapper2D()
        texture_mapper = set_input(texture_mapper, self.texture_polydata)

        image = vtk.vtkTexturedActor2D()
        image.SetMapper(texture_mapper)

        self.texture = vtk.vtkTexture()
        image.SetTexture(self.texture)

        image_property = vtk.vtkProperty2D()
        image_property.SetOpacity(1.0)
        image.SetProperty(image_property)
        self.actor = image

        # Add default events listener to the VTK actor.
        self.handle_events(self.actor)
Exemplo n.º 33
0
    def _setup(self):
        """Set up this UI component.

        Creating the button actor used internally.

        """
        # This is highly inspired by
        # https://github.com/Kitware/VTK/blob/c3ec2495b183e3327820e927af7f8f90d34c3474/Interaction/Widgets/vtkBalloonRepresentation.cxx#L47

        self.texture_polydata = vtk.vtkPolyData()
        self.texture_points = vtk.vtkPoints()
        self.texture_points.SetNumberOfPoints(4)

        polys = vtk.vtkCellArray()
        polys.InsertNextCell(4)
        polys.InsertCellPoint(0)
        polys.InsertCellPoint(1)
        polys.InsertCellPoint(2)
        polys.InsertCellPoint(3)
        self.texture_polydata.SetPolys(polys)

        tc = vtk.vtkFloatArray()
        tc.SetNumberOfComponents(2)
        tc.SetNumberOfTuples(4)
        tc.InsertComponent(0, 0, 0.0)
        tc.InsertComponent(0, 1, 0.0)
        tc.InsertComponent(1, 0, 1.0)
        tc.InsertComponent(1, 1, 0.0)
        tc.InsertComponent(2, 0, 1.0)
        tc.InsertComponent(2, 1, 1.0)
        tc.InsertComponent(3, 0, 0.0)
        tc.InsertComponent(3, 1, 1.0)
        self.texture_polydata.GetPointData().SetTCoords(tc)

        texture_mapper = vtk.vtkPolyDataMapper2D()
        texture_mapper = set_input(texture_mapper, self.texture_polydata)

        button = vtk.vtkTexturedActor2D()
        button.SetMapper(texture_mapper)

        self.texture = vtk.vtkTexture()
        button.SetTexture(self.texture)

        button_property = vtk.vtkProperty2D()
        button_property.SetOpacity(1.0)
        button.SetProperty(button_property)
        self.actor = button

        # Add default events listener to the VTK actor.
        self.handle_events(self.actor)
Exemplo n.º 34
0
def floor():
    plane = vtk.vtkPlaneSource()
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(pkg_resources.resource_filename("robopy", "media/imgs/floor.jpg"))
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())
    map_to_plane = vtk.vtkTextureMapToPlane()
    map_to_plane.SetInputConnection(plane.GetOutputPort())
    mapper = vtk.vtkPolyDataMapper()

    mapper.SetInputConnection(map_to_plane.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)
    return actor
Exemplo n.º 35
0
def main():
    colors = vtk.vtkNamedColors()

    jpegfile = get_program_parameters()

    # Create a render window
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(480, 480)
    renWin.SetWindowName('SphereTexture')

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Generate an sphere polydata
    sphere = vtk.vtkSphereSource()
    sphere.SetThetaResolution(12)
    sphere.SetPhiResolution(12)

    # Read the image data from a file
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(jpegfile)

    # Create texture object
    texture = vtk.vtkTexture()
    texture.SetInputConnection(reader.GetOutputPort())

    # Map texture coordinates
    map_to_sphere = vtk.vtkTextureMapToSphere()
    map_to_sphere.SetInputConnection(sphere.GetOutputPort())
    map_to_sphere.PreventSeamOn()

    # Create mapper and set the mapped texture as input
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(map_to_sphere.GetOutputPort())

    # Create actor and set the mapper and the texture
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetTexture(texture)

    ren.AddActor(actor)
    ren.SetBackground(colors.GetColor3d('RosyBrown'))

    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemplo n.º 36
0
 def create(self):
     self.road = ode.Body(self.world)
     mRoad = ode.Mass()
     mRoad.setBox(1, 3000, 0.01, self.size)
     self.road.setMass(mRoad)
     self.geomRoad = ode.GeomBox(self.space, (3000, 0.01, self.size))
     self.geomRoad.setBody(self.road)
     self.geomRoad.setPosition((0, 0, 0))
     self.viz.addGeom(self.geomRoad)
     self.reader = vtk.vtkJPGReader()
     self.reader.SetFileName(WHEEL_IMAGE)
     self.texture = vtk.vtkTexture()
     transform = vtk.vtkTransform()
     transform.Scale(1.0, 1.0, 1.0)
     self.texture.SetTransform(transform)
     self.viz.GetProperty(self.road).SetColor(ROADCOLOR)
    def set_texture(self, filename):
        """
        Sets an image from a file as a texture for the model.
        :param filename:
        :return:
        """
        # Read the texture image from a file.
        # Currently supports png and jpeg formats.
        if filename is not None:

            vf.validate_is_file(filename)

            if filename.endswith('.png'):
                self.texture_reader = vtk.vtkPNGReader()

            elif np.logical_or(filename.endswith('.jpeg'),
                               filename.endswith('.jpg')):
                self.texture_reader = vtk.vtkJPEGReader()

            else:
                raise ValueError(
                    'File type not supported for texture loading: {}'.format(
                        filename))

        else:
            # Unset texture when the function is called with None.
            self.texture_reader = None
            self.texture_file = None
            self.texture_name = None
            self.texture = None
            self.actor.SetTexture(None)
            return

        self.texture_reader.SetFileName(filename)
        self.texture_file = filename
        self.texture_name = os.path.basename(self.texture_file)

        # Create texture object.
        self.texture = vtk.vtkTexture()
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.texture.SetInput(self.texture_reader.GetOutput())
        else:
            self.texture.SetInputConnection(
                self.texture_reader.GetOutputPort())

        # Set the texture
        self.actor.SetTexture(self.texture)
Exemplo n.º 38
0
def StippledLine(actor, lineStipplePattern, lineStippleRepeat):
    tcoords = vtk.vtkDoubleArray()
    image = vtk.vtkImageData()
    texture = vtk.vtkTexture()

    # Create texture
    dimension = 16 * lineStippleRepeat

    image.SetDimensions(dimension, 1, 1)
    image.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 4)
    image.SetExtent(0, dimension - 1, 0, 0, 0, 0)
    on = 255
    off = 0
    i_dim = 0
    while i_dim < dimension:
        for i in range(0, 16):
            mask = (1 << i)
            bit = (lineStipplePattern & mask) >> i
            value = bit
            if value == 0:
                for j in range(0, lineStippleRepeat):
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 0, on)
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 1, on)
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 2, on)
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 3, off)
                    i_dim += 1
            else:
                for j in range(0, lineStippleRepeat):
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 0, on)
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 1, on)
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 2, on)
                    image.SetScalarComponentFromFloat(i_dim, 0, 0, 3, on)
                    i_dim += 1
    polyData = actor.GetMapper().GetInput()
    # Create texture coordinates
    tcoords.SetNumberOfComponents(1)
    tcoords.SetNumberOfTuples(polyData.GetNumberOfPoints())
    for i in range(0, polyData.GetNumberOfPoints()):
        value = i * 0.5
        tcoords.SetTypedTuple(i, [value])
    polyData.GetPointData().SetTCoords(tcoords)
    texture.SetInputData(image)
    texture.InterpolateOff()
    texture.RepeatOn()

    actor.SetTexture(texture)
Exemplo n.º 39
0
    def make_texture_overly_object(self):
        input_image = self.session.overlay_image_fname
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(input_image)
        texture = vtk.vtkTexture()
        texture.SetInput(reader.GetOutput())
        texture.SetInputConnection(reader.GetOutputPort())
        texture.InterpolateOn()

        plane = vtk.vtkPlaneSource()
        plane.SetOrigin((0, 0, 0))
        plane.SetPoint1(self.bounds.lat_max_distance)
        plane.SetPoint2(self.bounds.long_max_distance)

        planeMapper = vtk.vtkPolyDataMapper()
        planeMapper.SetInputConnection(plane.GetOutputPort())
        self.overlayActor = vtk.vtkActor()
        self.overlayActor.SetMapper(planeMapper)
        self.overlayActor.SetTexture(texture)
        self.actors.append(self.overlayActor)
Exemplo n.º 40
0
def create_textured_plane(**kwargs):
    """
    create a plane with correct size and texture it with a map
    """
    image_reader = vtk.vtkPNGReader()
    image_reader.SetFileName(kwargs['map'])

    plane = vtk.vtkPlaneSource()
    size = kwargs['size']
    z_level = 0.0
    plane.SetOrigin(-0.5*size[0], -0.5*size[1], z_level)
    plane.SetPoint1(+0.5*size[0], -0.5*size[1], z_level)
    plane.SetPoint2(-0.5*size[0], +0.5*size[1], z_level)

    texture = vtk.vtkTexture()
    texture.SetInputConnection(image_reader.GetOutputPort())

    texture_plane = vtk.vtkTextureMapToPlane()
    texture_plane.SetInputConnection(plane.GetOutputPort())
    return texture_plane, texture
Exemplo n.º 41
0
 def __init__(self, renderer, parent, screenDistance, width, height, isActiveCamera = False):
     '''
     Initialize the CameraScreen model.
     If you are going to stream data to it, set isActiveCamera to true in the constructor parameters and pass jpeg data to the update method.
     '''
     # Call the parent constructor
     super(CameraScreen,self).__init__(renderer, parent)
     
     # Create a plane for the camera 
     # Ref: http://www.vtk.org/doc/nightly/html/classvtkPlaneSource.html
     planeSource = vtk.vtkPlaneSource()
     # Defaults work for this, so just push it out a bit
     #planeSource.Push(screenDistance)
     
     # Transform scale it to the right size
     trans = vtk.vtkTransform()
     trans.Scale(width, height, 1)
     trans.Translate(0, 0, screenDistance)
     trans.RotateY(180) # Effectively flipping the UV (texture) mapping so that the video isn't left/right flipped
     transF = vtk.vtkTransformPolyDataFilter()
     transF.SetInputConnection(planeSource.GetOutputPort())
     transF.SetTransform(trans)
     
     # Create a test picture and assign it to the screen for now...
     # Ref: http://vtk.org/gitweb?p=VTK.git;a=blob;f=Examples/Rendering/Python/TPlane.py
     if not isActiveCamera:
         self.__textReader = vtk.vtkPNGReader()
         self.__textReader.SetFileName("../scene/media/semisortedcameralogo.png")
     else:
         self.__textReader = vtk.vtkJPEGReader()
     self.cameraVtkTexture = vtk.vtkTexture()
     self.cameraVtkTexture.SetInputConnection(self.__textReader.GetOutputPort())
     self.cameraVtkTexture.InterpolateOn()        
     
     # Finally assign the mapper and the actor
     planeMapper = vtk.vtkPolyDataMapper()
     planeMapper.SetInputConnection(transF.GetOutputPort())
      
     self.vtkActor.SetMapper(planeMapper)
     self.vtkActor.SetTexture(self.cameraVtkTexture)
Exemplo n.º 42
0
    def __init__( self, color, plane, reslice, range ):
        
        self._color = color
    
        self._source = plane
                
        self._mapper = vtk.vtkPolyDataMapper()
        self._mapper.SetInput( self._source.GetOutput() )
        self.SetMapper( self._mapper )

        self._lut = vtk.vtkWindowLevelLookupTable()
        self._lut.SetNumberOfColors( 256 )
        self._lut.SetTableRange( range[0], range[1] )
        self._lut.SetHueRange( 0.0, 0.0 )
        self._lut.SetSaturationRange( 0.0, 0.0 )
        self._lut.SetValueRange( 0.0, 1.0 )
        self._lut.SetAlphaRange( 0.0, 1.0 )
        self._lut.Build()

        self._colormap = vtk.vtkImageMapToColors()
        self._colormap.SetInputConnection( reslice.GetOutputPort() )
        self._colormap.SetLookupTable( self._lut )
        self._colormap.SetOutputFormatToRGBA()
        self._colormap.PassAlphaToOutputOn()

        self._texture = vtk.vtkTexture()
        self._texture.SetInterpolate( True )
        self._texture.SetQualityTo32Bit()
        self._texture.MapColorScalarsThroughLookupTableOff()
        self._texture.RepeatOff()
        self._texture.SetInput( self._colormap.GetOutput() )
        self._texture.SetLookupTable( self._lut )
        self.SetTexture( self._texture )

        self._property = vtk.vtkProperty()
        self._property.SetOpacity( 0.9 )
        self._property.EdgeVisibilityOn()
        self._property.SetEdgeColor( self._color[0], self._color[1], self._color[2] )
        self.SetProperty( self._property )
Exemplo n.º 43
0
    def _createOrthoPipelineForNewIPW(self, ipw):
        """This will create and append all the necessary constructs for a
        single new layer (ipw) to the self._orthoPipeline.

        Make sure you only call this method if the orthoView exists!
        After having done this, you still need to call _syncOrthoView() or
        _resetOrthoView() if you've added a new primary.
        """

        _ps = vtk.vtkPlaneSource()
        _pa = vtk.vtkActor()
        _tm2p = vtk.vtkTextureMapToPlane()
        self._orthoPipeline.append(
            {'planeSource' : _ps,
             'planeActor' : _pa,
             'textureMapToPlane': _tm2p})

        _tm2p.AutomaticPlaneGenerationOff()
        _tm2p.SetInput(_ps.GetOutput())
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(_tm2p.GetOutput())
        _pa.SetMapper(mapper)

        otherTexture = ipw.GetTexture()

        # we don't just use the texture, else VTK goes mad re-uploading
        # the same texture unnecessarily... let's just make use of the
        # same input, we get much more effective use of the
        # host->GPU bus
        texture = vtk.vtkTexture()
        texture.SetInterpolate(otherTexture.GetInterpolate())
        texture.SetQuality(otherTexture.GetQuality())
        texture.MapColorScalarsThroughLookupTableOff()
        texture.RepeatOff()
        texture.SetInput(otherTexture.GetInput())

        _pa.SetTexture(texture)

        self._renderer.AddActor(_pa)
Exemplo n.º 44
0
 def __init__(self, sim, pos, dims, density, fixed=False):
     # ODE initialization
     x, y, z = pos # initial pos
     lx, ly, lz = dims # dimensions
     self.sim = sim # link to the sim object
     self.body = ode.Body(self.sim.world) # ode body
     mass = ode.Mass() # mass object
     mass.setBox(density, lx, ly, lz) # calculate mass
     self.body.setMass(mass) # link mass to body
     self.body.setPosition(pos) # set the initial pos
     self.geom = ode.GeomBox(self.sim.space, lengths=dims) # geometry
     self.geom.setBody(self.body) # link geometry and body
     if fixed:
         self.fixedJoint = ode.FixedJoint(self.sim.world)
         self.fixedJoint.attach(self.body,self.sim.space.getBody())
         self.fixedJoint.setFixed()
     # VTK initialization
     self.math = vtk.vtkMath()
     self.cube = vtk.vtkCubeSource()
     self.cube.SetXLength(lx)
     self.cube.SetYLength(ly)
     self.cube.SetZLength(lz)
     self.cube.SetCenter((0.0,0.0,0.0))
     self.reader = vtk.vtkJPEGReader()
     self.reader.SetFileName(ROBOT_IMAGE)
     self.texture = vtk.vtkTexture()
     transform = vtk.vtkTransform()
     transform.Scale(1.0,1.0,1.0)
     self.texture.SetTransform(transform)
     self.texture.SetInput(self.reader.GetOutput())
     self.mapper = vtk.vtkPolyDataMapper()
     self.mapper.SetInput(self.cube.GetOutput())
     self.actor = vtk.vtkActor()
     self.actor.SetMapper(self.mapper)
     self.actor.SetTexture(self.texture)
     sim.renderer.AddActor(self.actor)
     # Self-include in the bodies for visualization
     sim.bodies.append(self)
Exemplo n.º 45
0
    def showRender(self):
        
        jpegfile = "/home/jose/Documentos/PFC/PFC/sphere.jpg"
        # Read the image data from a file
        reader = vtk.vtkJPEGReader()
        reader.SetFileName(jpegfile)
        reader.Update()
                # Create texture object
        texture = vtk.vtkTexture()
        
        if vtk.VTK_MAJOR_VERSION <= 5:
            texture.SetInput(reader.GetOutput())
        else:
            texture.SetInputConnection(reader.GetOutputPort())
        #self.render.SetTexturedBackground(True)
        
        #self.render.SetBackgroundTexture(texture)
        self.render.GradientBackgroundOn()
        self.render.SetBackground2(0.4,0.5,0.9)
        self.render.SetBackground(0.3,0.3,0.3)

        self.pantalla.Initialize()
        self.pantalla.Start()
Exemplo n.º 46
0
ballTC = vtk.vtkTextureMapToSphere()
ballTC.SetInputData(model)
lut = vtk.vtkLookupTable()
lut.SetNumberOfColors(3)
lut.Build()
lut.SetTableValue(0,0,0,0,1)
lut.SetTableValue(1,1,.3,.3,1)
lut.SetTableValue(2,.8,.8,.9,1)
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(ballTC.GetOutputPort())
mapper.SetScalarModeToUseCellData()
mapper.SetLookupTable(lut)
mapper.SetScalarRange(0,2)
earth = vtk.vtkPNMReader()
earth.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm")
texture = vtk.vtkTexture()
texture.SetInputConnection(earth.GetOutputPort())
soccerBall = vtk.vtkActor()
soccerBall.SetMapper(mapper)
soccerBall.SetTexture(texture)
# Add the actors to the renderer, set the background and size
#
ren1.AddActor(soccerBall)
ren1.SetBackground(0.1,0.2,0.4)
renWin.SetSize(300,300)
ren1.GetActiveCamera().SetPosition(4.19682,4.65178,6.23545)
ren1.GetActiveCamera().SetFocalPoint(0,0,0)
ren1.GetActiveCamera().SetViewAngle(21.4286)
ren1.GetActiveCamera().SetViewUp(0.451577,-0.833646,0.317981)
# render the image
#
Exemplo n.º 47
0
view.SetShrinkPercentage(SHRINK)
view.SetLayerThickness(ICEHEIGHT)
view.UseGradientColoringOff()
view.Update()

# print view.GetRepresentation(0)

# TESTING
pnmReader = vtk.vtkTIFFReader()
pnmReader.SetFileName("/Users/emonson/Programming/Python/VTK/VSItext2c.tif")
# pnmReader.SetFileName("/Users/emonson/Programming/VTK_cvs/VTKData/Data/beach.tif")
pnmReader.SetOrientationType(4)
# pnmReader.Update()
# END TESTING

tex = vtk.vtkTexture()
# tex.SetInput(WCimageData)
tex.SetInputConnection(pnmReader.GetOutputPort())
# tex.SetLookupTable(lut)

# Apply texture to polydata in vtkTexturedTreeAreaRepresentation through View
view.SetTexture(tex)

# Apply a theme to the views
theme = vtk.vtkViewTheme.CreateMellowTheme()
theme.SetPointHueRange(0,0)
theme.SetPointSaturationRange(0,0)
theme.SetPointValueRange(0.75,0.75)
theme.SetPointAlphaRange(1,1)
view.ApplyViewTheme(theme)
theme.FastDelete()
Exemplo n.º 48
0
    def testQuadricCut(self):

        solidTexture = (255, 255)
        clearTexture = (255, 0)
        edgeTexture = (0, 255)

        def makeBooleanTexture(caseNumber, resolution, thickness):
            #global solidTexture, clearTexture, edgeTexture
            booleanTexturecaseNumber = vtk.vtkBooleanTexture()

            booleanTexturecaseNumber.SetXSize(resolution)
            booleanTexturecaseNumber.SetYSize(resolution)
            booleanTexturecaseNumber.SetThickness(thickness)

            if caseNumber == 0:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(solidTexture)
                booleanTexturecaseNumber.SetOnIn(solidTexture)
                booleanTexturecaseNumber.SetOnOut(solidTexture)
                booleanTexturecaseNumber.SetInOn(solidTexture)
                booleanTexturecaseNumber.SetOutOn(solidTexture)
            elif caseNumber == 1:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(solidTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
            elif caseNumber == 2:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(solidTexture)
                booleanTexturecaseNumber.SetInOn(solidTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 3:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(clearTexture)
                booleanTexturecaseNumber.SetOnOut(solidTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 4:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(solidTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(solidTexture)
            elif caseNumber == 5:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(clearTexture)
                booleanTexturecaseNumber.SetOutOn(solidTexture)
            elif caseNumber == 6:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 7:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutOut(solidTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(clearTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(clearTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 8:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(solidTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(solidTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 9:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 10:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(solidTexture)
                booleanTexturecaseNumber.SetOutOn(clearTexture)
            elif caseNumber == 11:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(solidTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(clearTexture)
                booleanTexturecaseNumber.SetOnOut(edgeTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(clearTexture)
            elif caseNumber == 12:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(solidTexture)
                booleanTexturecaseNumber.SetOnOut(clearTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 13:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutIn(solidTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(clearTexture)
                booleanTexturecaseNumber.SetInOn(clearTexture)
                booleanTexturecaseNumber.SetOutOn(edgeTexture)
            elif caseNumber == 14:
                booleanTexturecaseNumber.SetInIn(solidTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(edgeTexture)
                booleanTexturecaseNumber.SetOnIn(edgeTexture)
                booleanTexturecaseNumber.SetOnOut(clearTexture)
                booleanTexturecaseNumber.SetInOn(edgeTexture)
                booleanTexturecaseNumber.SetOutOn(clearTexture)
            elif caseNumber == 15:
                booleanTexturecaseNumber.SetInIn(clearTexture)
                booleanTexturecaseNumber.SetInOut(clearTexture)
                booleanTexturecaseNumber.SetOutIn(clearTexture)
                booleanTexturecaseNumber.SetOutOut(clearTexture)
                booleanTexturecaseNumber.SetOnOn(clearTexture)
                booleanTexturecaseNumber.SetOnIn(clearTexture)
                booleanTexturecaseNumber.SetOnOut(clearTexture)
                booleanTexturecaseNumber.SetInOn(clearTexture)
                booleanTexturecaseNumber.SetOutOn(clearTexture)


            booleanTexturecaseNumber.Update()
            return booleanTexturecaseNumber

        # A list of positions
        positions = []
        positions.append((-4, 4, 0))
        positions.append((-2, 4, 0))
        positions.append((0, 4, 0))
        positions.append((2, 4, 0))
        positions.append((-4, 2, 0))
        positions.append((-2, 2, 0))
        positions.append((0, 2, 0))
        positions.append((2, 2, 0))
        positions.append((-4, 0, 0))
        positions.append((-2, 0, 0))
        positions.append((0, 0, 0))
        positions.append((2, 0, 0))
        positions.append((-4, -2, 0))
        positions.append((-2, -2, 0))
        positions.append((0, -2, 0))
        positions.append((2, -2, 0))

        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        # define two elliptical cylinders
        quadric1 = vtk.vtkQuadric()
        quadric1.SetCoefficients(1, 2, 0, 0, 0, 0, 0, 0, 0, -.07)

        quadric2 = vtk.vtkQuadric()
        quadric2.SetCoefficients(2, 1, 0, 0, 0, 0, 0, 0, 0, -.07)

        # create a sphere for all to use
        aSphere = vtk.vtkSphereSource()
        aSphere.SetPhiResolution(50)
        aSphere.SetThetaResolution(50)

        # create texture coordinates for all
        tcoords = vtk.vtkImplicitTextureCoords()
        tcoords.SetInputConnection(aSphere.GetOutputPort())
        tcoords.SetRFunction(quadric1)
        tcoords.SetSFunction(quadric2)

        aMapper = vtk.vtkDataSetMapper()
        aMapper.SetInputConnection(tcoords.GetOutputPort())

        # create a mapper, sphere and texture map for each case
        aTexture = []
        anActor = []
        for i in range(0, 16):
            aTexture.append(vtk.vtkTexture())
            aTexture[i].SetInputData(makeBooleanTexture(i, 256, 1).GetOutput())
            aTexture[i].InterpolateOff()
            aTexture[i].RepeatOff()
            anActor.append(vtk.vtkActor())
            anActor[i].SetMapper(aMapper)
            anActor[i].SetTexture(aTexture[i])
            anActor[i].SetPosition(positions[i])
            anActor[i].SetScale(2.0, 2.0, 2.0)
            ren.AddActor(anActor[i])


        ren.SetBackground(0.4392, 0.5020, 0.5647)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.4)
        renWin.SetSize(500, 500)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "quadricCut.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 49
0
    def testDeciFranFace(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren1 = vtk.vtkRenderer()
        ren2 = vtk.vtkRenderer()
        ren3 = vtk.vtkRenderer()
        ren4 = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren1)
        renWin.AddRenderer(ren2)
        renWin.AddRenderer(ren3)
        renWin.AddRenderer(ren4)

        pnm1 = vtk.vtkPNGReader()
        pnm1.SetFileName(VTK_DATA_ROOT + "/Data/fran_cut.png")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(pnm1.GetOutputPort())
        atext.InterpolateOn()

        # create a cyberware source
        #
        fran = vtk.vtkPolyDataReader()
        fran.SetFileName(VTK_DATA_ROOT + "/Data/fran_cut.vtk")

        # Create a table of decimation conditions
        #
        boundaryVertexDeletion = ["On", "Off"]
        accumulates = ["On", "Off"]

        deci = dict()
        mapper = dict()
        actor = dict()

        for topology in boundaryVertexDeletion:
            for accumulate in accumulates:
                idx = topology + accumulate
                deci.update({idx: vtk.vtkDecimatePro()})
                deci[idx].SetInputConnection(fran.GetOutputPort())
                deci[idx].SetTargetReduction(.95)
                if topology == "On":
                    deci[idx].PreserveTopologyOn()
                elif topology == "Off":
                    deci[idx].PreserveTopologyOff()
                if accumulate == "On":
                    deci[idx].AccumulateErrorOn()
                elif accumulate == "Off":
                    deci[idx].AccumulateErrorOff()
                mapper.update({idx: vtk.vtkPolyDataMapper()})
                mapper[idx].SetInputConnection(deci[idx].GetOutputPort())
                actor.update({idx: vtk.vtkActor()})
                actor[idx].SetMapper(mapper[idx])
                actor[idx].SetTexture(atext)

        # Add the actors to the renderer, set the background and size
        #
        ren1.SetViewport(0, .5, .5, 1)
        ren2.SetViewport(.5, .5, 1, 1)
        ren3.SetViewport(0, 0, .5, .5)
        ren4.SetViewport(.5, 0, 1, .5)

        ren1.AddActor(actor["OnOn"])
        ren2.AddActor(actor["OnOff"])
        ren3.AddActor(actor["OffOn"])
        ren4.AddActor(actor["OffOff"])

        camera = vtk.vtkCamera()
        ren1.SetActiveCamera(camera)
        ren2.SetActiveCamera(camera)
        ren3.SetActiveCamera(camera)
        ren4.SetActiveCamera(camera)

        ren1.GetActiveCamera().SetPosition(0.314753, -0.0699988, -0.264225)
        ren1.GetActiveCamera().SetFocalPoint(0.00188636, -0.136847, -5.84226e-09)
        ren1.GetActiveCamera().SetViewAngle(30)
        ren1.GetActiveCamera().SetViewUp(0, 1, 0)
        ren1.ResetCameraClippingRange()

        ren2.ResetCameraClippingRange()
        ren3.ResetCameraClippingRange()
        ren4.ResetCameraClippingRange()

        ren1.SetBackground(1, 1, 1)
        ren2.SetBackground(1, 1, 1)
        ren3.SetBackground(1, 1, 1)
        ren4.SetBackground(1, 1, 1)
        renWin.SetSize(500, 500)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "deciFranFace.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
    def SetUp(self):
        '''
        Set up squadViewer
        '''
        def OnClosing():
            self.root.quit()

        def SetPhi(squad, win, phi):
            squad.SetPhiRoundness(float(phi))
            win.Render()

        def SetTheta(squad, win, theta):
            squad.SetThetaRoundness(float(theta))
            win.Render()

        def SetThickness(squad, win, thickness):
            squad.SetThickness(float(thickness))
            win.Render()

        def SetTexture(actor, texture, win):
            if doTexture.get():
                actor.SetTexture(texture)
            else:
                actor.SetTexture(None)
            win.Render()

        def SetToroid(squad, scale, win):
            squad.SetToroidal(toroid.get())
            if toroid.get():
                scale.config(state=NORMAL, fg='black')
            else:
                scale.config(state=DISABLED, fg='gray')
            win.Render()

        self.root = tkinter.Tk()
        self.root.title("superquadric viewer")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Create render window
        self.tkrw = vtkTkRenderWidget(self.root, width=550, height=450)
        self.tkrw.BindTkRenderWidget()
        renWin = self.tkrw.GetRenderWindow()

        # Create parameter sliders
        #
        prs = tkinter.Scale(self.root, from_=0, to=3.5, res=0.1,
                             orient=HORIZONTAL, label="phi roundness")
        trs = tkinter.Scale(self.root, from_=0, to=3.5, res=0.1,
                             orient=HORIZONTAL, label="theta roundness")
        thicks = tkinter.Scale(self.root, from_=0.01, to=1.0, res=0.01,
                             orient=HORIZONTAL, label="thickness")

        # Create check buttons
        #
        toroid = tkinter.IntVar()
        toroid.set(0)
        doTexture = tkinter.IntVar()
        doTexture.set(0)

        rframe = tkinter.Frame(self.root)
        torbut = tkinter.Checkbutton(rframe, text="Toroid", variable=toroid)
        texbut = tkinter.Checkbutton(rframe, text="Texture", variable=doTexture)

        # Put it all together
        #
        torbut.pack(padx=10, pady=5, ipadx=20, ipady=5, side=RIGHT, anchor=S)
        texbut.pack(padx=10, pady=5, ipadx=20, ipady=5, side=RIGHT, anchor=S)

        self.tkrw.grid(sticky=N+E+W+S, columnspan=2)
        rframe.grid(sticky=N+E+W+S)
        thicks.grid(sticky=N+S+E+W, padx=10, ipady=5, row=1, column=1)
        prs.grid(sticky=N+E+W+S, padx=10, ipady=5, row = 2, column = 0)
        trs.grid(sticky=N+E+W+S, padx=10, ipady=5, row = 2, column = 1)
        tkinter.Pack.propagate(rframe,NO)

        prs.set(1.0)
        trs.set(0.7)
        thicks.set(0.3)
        toroid.set(1)
        doTexture.set(0)

        # Create pipeline
        #
        squad = vtk.vtkSuperquadricSource()
        squad.SetPhiResolution(20)
        squad.SetThetaResolution(25)

        pnmReader = vtk.vtkPNMReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/earth.ppm")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOn()

        appendSquads = vtk.vtkAppendPolyData()
        appendSquads.AddInputConnection(squad.GetOutputPort())

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(squad.GetOutputPort())
        mapper.ScalarVisibilityOff()
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.SetTexture(atext)
        actor.GetProperty().SetDiffuseColor(0.5, 0.8, 0.8)
        actor.GetProperty().SetAmbient(0.2)
        actor.GetProperty().SetAmbientColor(0.2, 0.2, 0.2)

        squad.SetPhiRoundness(prs.get())
        squad.SetThetaRoundness(trs.get())
        squad.SetToroidal(toroid.get())
        squad.SetThickness(thicks.get())
        squad.SetScale(1, 1, 1)
        SetTexture(actor, atext, renWin)

        # Create renderer stuff
        #
        ren = vtk.vtkRenderer()
        ren.SetAmbient(1.0, 1.0, 1.0)
        renWin.AddRenderer(ren)


        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(actor)
        ren.SetBackground(0.25, 0.2, 0.2)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.2)
        ren.GetActiveCamera().Elevation(40)
        ren.GetActiveCamera().Azimuth(-20)

        # Associate the functions with the sliders and check buttons.
        #
        prs.config(command=partial(SetPhi, squad, self.tkrw))
        trs.config(command=partial(SetTheta, squad, self.tkrw))
        thicks.config(command=partial(SetThickness,squad, self.tkrw))
        torbut.config(command=partial(SetToroid, squad, thicks, self.tkrw))
        texbut.config(command=partial(SetTexture, actor, atext, self.tkrw))
Exemplo n.º 51
0
# Do the surface rendering
sphereSource = vtk.vtkSphereSource()
sphereSource.SetRadius(100)

textureSphere = vtk.vtkTextureMapToSphere()
textureSphere.SetInputConnection(sphereSource.GetOutputPort())

sphereStripper = vtk.vtkStripper()
sphereStripper.SetInputConnection(textureSphere.GetOutputPort())
sphereStripper.SetMaximumLength(5)

sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphereStripper.GetOutputPort())
sphereMapper.ScalarVisibilityOff()

sphereTexture = vtk.vtkTexture()
sphereTexture.SetInputConnection(reader.GetOutputPort())

sphereProperty = vtk.vtkProperty()
sphereProperty.BackfaceCullingOn()

sphere = vtk.vtkActor()
sphere.SetMapper(sphereMapper)
sphere.SetTexture(sphereTexture)
sphere.SetProperty(sphereProperty)

#---------------------------------------------------------
ren.AddViewProp(sphere)

camera = ren.GetActiveCamera()
camera.SetFocalPoint(0, 0, 0)
Exemplo n.º 52
0
def rhombicuboctahedron():
    import vtk
    # First, you need to store the vertex locations.

    import numpy as np
    fu = 1  # full unit
    hu = .5  # half unit
    d = np.sqrt((fu ** 2) / 2)  # diag
    hh = hu + d  # half height

    # left view faces us

    import utool as ut
    import six
    import itertools
    counter = ut.partial(six.next, itertools.count(0))

    vertex_locations = vtk.vtkPoints()
    vertex_locations.SetNumberOfPoints(24)

    p1, p2, p3 = np.array([
        (-hu, -hu, hh),
        ( hu, -hu, hh),
        ( hu,  hu, hh),
        (-hu,  hu, hh),
    ]).T
    plist = [p1, p2, p3]

    # three of the six main faces
    #perms = list(itertools.permutations((0, 1, 2), 3))
    perms = [(0, 1, 2), (0, 2, 1), (2, 0, 1)]

    vertex_array = []

    # VERTEXES
    # left, up, back
    vplist = ['L', 'U', 'B', 'R', 'D', 'F']
    vpdict = {}
    print('perms = %r' % (perms,))
    for x in range(3):
        vp = vplist[x]
        p = np.vstack(ut.take(plist, perms[x])).T
        counts = [counter() for z in range(4)]
        vpdict[vp] = counts
        vertex_array.extend(p.tolist())
        vertex_locations.SetPoint(counts[0], p[0])
        vertex_locations.SetPoint(counts[1], p[1])
        vertex_locations.SetPoint(counts[2], p[2])
        vertex_locations.SetPoint(counts[3], p[3])

    # three more of the six main faces
    perms = [(0, 1, 2), (0, 2, 1), (2, 0, 1)]
    plist[-1] = -plist[-1]
    # right, down, front
    print('perms = %r' % (perms,))
    for x in range(3):
        p = np.vstack(ut.take(plist, perms[x])).T
        counts = [counter() for z in range(4)]
        vp = vplist[x + 3]
        vpdict[vp] = counts
        vertex_array.extend(p.tolist())
        vertex_locations.SetPoint(counts[0], p[0])
        vertex_locations.SetPoint(counts[1], p[1])
        vertex_locations.SetPoint(counts[2], p[2])
        vertex_locations.SetPoint(counts[3], p[3])

    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)

    polygon_faces = vtk.vtkCellArray()

    face_dict = {
        'L': [vpdict['L'][0], vpdict['L'][1], vpdict['L'][2], vpdict['L'][3]],
        'D': [vpdict['D'][0], vpdict['D'][1], vpdict['D'][2], vpdict['D'][3]],
        'U': [vpdict['U'][0], vpdict['U'][1], vpdict['U'][2], vpdict['U'][3]],
        'F': [vpdict['F'][0], vpdict['F'][1], vpdict['F'][2], vpdict['F'][3]],
        'R': [vpdict['R'][0], vpdict['R'][1], vpdict['R'][2], vpdict['R'][3]],
        'B': [vpdict['B'][0], vpdict['B'][1], vpdict['B'][2], vpdict['B'][3]],
        'FL': [ vpdict['L'][0], vpdict['L'][3], vpdict['F'][2], vpdict['F'][3], ],
        'BL': [ vpdict['L'][1], vpdict['L'][2], vpdict['B'][2], vpdict['B'][3], ],
        'UL': [ vpdict['L'][2], vpdict['L'][3], vpdict['U'][3], vpdict['U'][2], ],
        'DL': [ vpdict['L'][0], vpdict['L'][1], vpdict['D'][2], vpdict['D'][3], ],
        'UFL': [ vpdict['L'][3], vpdict['F'][2], vpdict['U'][3], ],
        'DFL': [ vpdict['L'][0], vpdict['F'][3], vpdict['D'][3], ],
        'UBL': [ vpdict['L'][2], vpdict['B'][2], vpdict['U'][2], ],
        'DBL': [ vpdict['L'][1], vpdict['B'][3], vpdict['D'][2], ],
        'UFR': [ vpdict['R'][3], vpdict['F'][1], vpdict['U'][0], ],
        'DFR': [ vpdict['R'][0], vpdict['F'][0], vpdict['D'][0], ],
        'UBR': [ vpdict['R'][2], vpdict['B'][1], vpdict['U'][1], ],
        'DBR': [ vpdict['R'][1], vpdict['B'][0], vpdict['D'][1], ],
        'FR': [ vpdict['R'][3], vpdict['R'][0], vpdict['F'][0], vpdict['F'][1], ],
        'BR': [ vpdict['R'][2], vpdict['R'][1], vpdict['B'][0], vpdict['B'][1], ],
        'UR': [ vpdict['R'][3], vpdict['R'][2], vpdict['U'][1], vpdict['U'][0], ],
        'DR': [ vpdict['R'][1], vpdict['R'][0], vpdict['D'][0], vpdict['D'][1], ],
        'DF': [ vpdict['F'][0], vpdict['F'][3], vpdict['D'][3], vpdict['D'][0], ],
        'DB': [ vpdict['B'][3], vpdict['B'][0], vpdict['D'][1], vpdict['D'][2], ],
        'UF': [ vpdict['F'][1], vpdict['F'][2], vpdict['U'][3], vpdict['U'][0], ],
        'UB': [ vpdict['B'][2], vpdict['B'][1], vpdict['U'][1], vpdict['U'][2], ],
    }

    for key, vert_ids in face_dict.items():
        #if key != 'L':
        #    continue
        if len(vert_ids) == 4:
            q = vtk.vtkQuad()
        else:
            q = vtk.vtkTriangle()
        for count, idx in enumerate(vert_ids):
            q.GetPointIds().SetId(count, idx)
        polygon_faces.InsertNextCell(q)

    # Next you create a vtkPolyData to store your face and vertex information
    #that
    # represents your polyhedron.
    pd = vtk.vtkPolyData()
    pd.SetPoints(vertex_locations)
    pd.SetPolys(polygon_faces)

    face_stream = vtk.vtkIdList()
    face_stream.InsertNextId(polygon_faces.GetNumberOfCells())
    vertex_list = vtk.vtkIdList()

    polygon_faces.InitTraversal()
    while polygon_faces.GetNextCell(vertex_list) == 1:
        face_stream.InsertNextId(vertex_list.GetNumberOfIds())

        for j in range(vertex_list.GetNumberOfIds()):
            face_stream.InsertNextId(vertex_list.GetId(j))

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(vertex_locations)
    ug.InsertNextCell(vtk.VTK_POLYHEDRON, face_stream)

    #writer = vtk.vtkUnstructuredGridWriter()
    #writer.SetFileName("rhombicuboctahedron.vtk")
    ##writer.SetInputData(ug)
    #writer.SetInput(ug)
    #writer.Write()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(ug)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    if 1:
        # Read the image data from a file
        import utool as ut

        textureCoords = vtk.vtkFloatArray()
        textureCoords.SetNumberOfComponents(3)
        #coords = ut.take(vertex_array, face_dict['L'])
        #for coord in coords:
        #    textureCoords.InsertNextTuple(tuple(coord))
        textureCoords.InsertNextTuple((0, 0, 0))
        textureCoords.InsertNextTuple((1, 0, 0))
        textureCoords.InsertNextTuple((1, 1, 0))
        textureCoords.InsertNextTuple((0, 1, 0))

        # Create texture object
        fpath = ut.grab_test_imgpath('zebra.png')
        reader = vtk.vtkPNGReader()
        reader.SetFileName(fpath)

        texture = vtk.vtkTexture()
        texture.SetInput(reader.GetOutput())
        texture.RepeatOff()
        texture.InterpolateOff()

        ptdat = pd.GetPointData()
        ptdat.SetTCoords(textureCoords)

        actor.SetTexture(texture)

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)

    renw = vtk.vtkRenderWindow()
    renw.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renw)

    ren.ResetCamera()
    renw.Render()
    iren.Start()
Exemplo n.º 53
0
Arquivo: TPlane.py Projeto: 0004c/VTK
#!/usr/bin/env python

# This simple example shows how to do basic texture mapping.

import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Load in the texture map. A texture is any unsigned char image. If it
# is not of this type, you will have to map it through a lookup table
# or by using vtkImageShiftScale.
bmpReader = vtk.vtkBMPReader()
bmpReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
atext = vtk.vtkTexture()
atext.SetInputConnection(bmpReader.GetOutputPort())
atext.InterpolateOn()

# Create a plane source and actor. The vtkPlanesSource generates
# texture coordinates.
plane = vtk.vtkPlaneSource()
planeMapper = vtk.vtkPolyDataMapper()
planeMapper.SetInputConnection(plane.GetOutputPort())
planeActor = vtk.vtkActor()
planeActor.SetMapper(planeMapper)
planeActor.SetTexture(atext)

# Create the RenderWindow, Renderer and both Actors
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
Exemplo n.º 54
0
    def testParametricFunctions(self):
        # ------------------------------------------------------------
        # Get a texture
        # ------------------------------------------------------------
        textureReader = vtk.vtkJPEGReader()
        textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")
        texture = vtk.vtkTexture()
        texture.SetInputConnection(textureReader.GetOutputPort())

        # ------------------------------------------------------------
        # For each parametric surface:
        # 1) Create it
        # 2) Assign mappers and actors
        # 3) Position the object
        # 5) Add a label
        # ------------------------------------------------------------

        # ------------------------------------------------------------
        # Create a torus
        # ------------------------------------------------------------
        torus = vtk.vtkParametricTorus()
        torusSource = vtk.vtkParametricFunctionSource()
        torusSource.SetParametricFunction(torus)
        torusSource.SetScalarModeToPhase()

        torusMapper = vtk.vtkPolyDataMapper()
        torusMapper.SetInputConnection(torusSource.GetOutputPort())
        torusMapper.SetScalarRange(0, 360)

        torusActor = vtk.vtkActor()
        torusActor.SetMapper(torusMapper)
        torusActor.SetPosition(0, 12, 0)

        torusTextMapper = vtk.vtkTextMapper()
        torusTextMapper.SetInput("Torus")
        torusTextMapper.GetTextProperty().SetJustificationToCentered()
        torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        torusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        torusTextMapper.GetTextProperty().SetFontSize(14)
        torusTextActor = vtk.vtkActor2D()
        torusTextActor.SetMapper(torusTextMapper)
        torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Klein bottle
        # ------------------------------------------------------------
        klein = vtk.vtkParametricKlein()
        kleinSource = vtk.vtkParametricFunctionSource()
        kleinSource.SetParametricFunction(klein)
        kleinSource.SetScalarModeToU0V0()

        kleinMapper = vtk.vtkPolyDataMapper()
        kleinMapper.SetInputConnection(kleinSource.GetOutputPort())
        kleinMapper.SetScalarRange(0, 3)

        kleinActor = vtk.vtkActor()
        kleinActor.SetMapper(kleinMapper)
        kleinActor.SetPosition(8, 10.5, 0)

        kleinTextMapper = vtk.vtkTextMapper()
        kleinTextMapper.SetInput("Klein")
        kleinTextMapper.GetTextProperty().SetJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        kleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        kleinTextMapper.GetTextProperty().SetFontSize(14)
        kleinTextActor = vtk.vtkActor2D()
        kleinTextActor.SetMapper(kleinTextMapper)
        kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Figure-8 Klein
        # ------------------------------------------------------------
        klein2 = vtk.vtkParametricFigure8Klein()
        klein2Source = vtk.vtkParametricFunctionSource()
        klein2Source.SetParametricFunction(klein2)
        klein2Source.GenerateTextureCoordinatesOn()

        klein2Mapper = vtk.vtkPolyDataMapper()
        klein2Mapper.SetInputConnection(klein2Source.GetOutputPort())
        klein2Mapper.SetScalarRange(0, 3)

        klein2Actor = vtk.vtkActor()
        klein2Actor.SetMapper(klein2Mapper)
        klein2Actor.SetPosition(16, 12, 0)
        klein2Actor.SetTexture(texture)


        fig8KleinTextMapper = vtk.vtkTextMapper()
        fig8KleinTextMapper.SetInput("Fig-8.Klein")
        fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0)
        fig8KleinTextMapper.GetTextProperty().SetFontSize(14)
        fig8KleinTextActor = vtk.vtkActor2D()
        fig8KleinTextActor.SetMapper(fig8KleinTextMapper)
        fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0)

        # ------------------------------------------------------------
        # Create a Mobius strip
        # ------------------------------------------------------------
        mobius = vtk.vtkParametricMobius()
        mobiusSource = vtk.vtkParametricFunctionSource()
        mobiusSource.SetParametricFunction(mobius)
        mobiusSource.GenerateTextureCoordinatesOn()

        mobiusMapper = vtk.vtkPolyDataMapper()
        mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort())

        mobiusActor = vtk.vtkActor()
        mobiusActor.SetMapper(mobiusMapper)
        mobiusActor.RotateX(45)
        mobiusActor.SetPosition(24, 12, 0)
        mobiusActor.SetTexture(texture)

        mobiusTextMapper = vtk.vtkTextMapper()
        mobiusTextMapper.SetInput("Mobius")
        mobiusTextMapper.GetTextProperty().SetJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0)
        mobiusTextMapper.GetTextProperty().SetFontSize(14)
        mobiusTextActor = vtk.vtkActor2D()
        mobiusTextActor.SetMapper(mobiusTextMapper)
        mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0)

        # ------------------------------------------------------------
        # Create a super toroid
        # ------------------------------------------------------------
        toroid = vtk.vtkParametricSuperToroid()
        toroid.SetN1(2)
        toroid.SetN2(3)
        toroidSource = vtk.vtkParametricFunctionSource()
        toroidSource.SetParametricFunction(toroid)
        toroidSource.SetScalarModeToU()

        toroidMapper = vtk.vtkPolyDataMapper()
        toroidMapper.SetInputConnection(toroidSource.GetOutputPort())
        toroidMapper.SetScalarRange(0, 6.28)

        toroidActor = vtk.vtkActor()
        toroidActor.SetMapper(toroidMapper)
        toroidActor.SetPosition(0, 4, 0)

        superToroidTextMapper = vtk.vtkTextMapper()
        superToroidTextMapper.SetInput("Super.Toroid")
        superToroidTextMapper.GetTextProperty().SetJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superToroidTextMapper.GetTextProperty().SetFontSize(14)
        superToroidTextActor = vtk.vtkActor2D()
        superToroidTextActor.SetMapper(superToroidTextMapper)
        superToroidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0)

        # ------------------------------------------------------------
        # Create a super ellipsoid
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        splinePoints = [
          [0.50380158308139134, -0.60679315105396936, -0.37248976406291578],
          [-0.4354646054261665, -0.85362339758017258, -0.84844312996065385],
          [0.2163147512899315, -0.39797507012168643, -0.76700353518454523],
          [0.97158415334838644, -0.58513467367046257, -0.35846037946569753],
          [-0.64359767997804918, -0.94620739107309249, -0.90762176546623086],
          [-0.39901219094126117, -0.1978931497772658, 0.0098316934936828471],
          [-0.75872745167404765, 0.067719714281950116, 0.165237936733867],
          [-0.84599731389712418, -0.67685466896596114, 0.10357868909071133],
          [0.84702754758625654, -0.0080077177882230677, -0.58571286666473044],
          [-0.076150034124101484, 0.14637647622561856, 0.1494359239700418] ]
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            inputPoints.InsertPoint(i, splinePoints[i])

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)

        # ------------------------------------------------------------
        # Create a closed 1D spline
        # ------------------------------------------------------------
        spline2 = vtk.vtkParametricSpline()
        spline2.SetPoints(inputPoints)
        spline2.ClosedOn()
        spline2Source = vtk.vtkParametricFunctionSource()
        spline2Source.SetParametricFunction(spline2)

        spline2Mapper = vtk.vtkPolyDataMapper()
        spline2Mapper.SetInputConnection(spline2Source.GetOutputPort())

        spline2Actor = vtk.vtkActor()
        spline2Actor.SetMapper(spline2Mapper)
        spline2Actor.SetPosition(24, 4, 0)
        spline2Actor.GetProperty().SetColor(0, 0, 0)

        spline2TextMapper = vtk.vtkTextMapper()
        spline2TextMapper.SetInput("Closed.Spline")
        spline2TextMapper.GetTextProperty().SetJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        spline2TextMapper.GetTextProperty().SetColor(1, 0, 0)
        spline2TextMapper.GetTextProperty().SetFontSize(14)
        spline2TextActor = vtk.vtkActor2D()
        spline2TextActor.SetMapper(spline2TextMapper)
        spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0)

        # ------------------------------------------------------------
        # Create a spiral conic
        # ------------------------------------------------------------
        sconic = vtk.vtkParametricConicSpiral()
        sconic.SetA(0.8)
        sconic.SetB(2.5)
        sconic.SetC(0.4)
        sconicSource = vtk.vtkParametricFunctionSource()
        sconicSource.SetParametricFunction(sconic)
        sconicSource.SetScalarModeToDistance()

        sconicMapper = vtk.vtkPolyDataMapper()
        sconicMapper.SetInputConnection(sconicSource.GetOutputPort())
        sconicActor = vtk.vtkActor()
        sconicActor.SetMapper(sconicMapper)
        sconicMapper.SetScalarRange(0, 9)
        sconicActor.SetPosition(0, -4, 0)
        sconicActor.SetScale(1.2, 1.2, 1.2)

        sconicTextMapper = vtk.vtkTextMapper()
        sconicTextMapper.SetInput("Spiral.Conic")
        sconicTextMapper.GetTextProperty().SetJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        sconicTextMapper.GetTextProperty().SetColor(1, 0, 0)
        sconicTextMapper.GetTextProperty().SetFontSize(14)
        sconicTextActor = vtk.vtkActor2D()
        sconicTextActor.SetMapper(sconicTextMapper)
        sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0)

        # ------------------------------------------------------------
        # Create Boy's surface
        # ------------------------------------------------------------
        boy = vtk.vtkParametricBoy()
        boySource = vtk.vtkParametricFunctionSource()
        boySource.SetParametricFunction(boy)
        boySource.SetScalarModeToModulus()

        boyMapper = vtk.vtkPolyDataMapper()
        boyMapper.SetInputConnection(boySource.GetOutputPort())
        boyMapper.SetScalarRange(0, 2)
        boyActor = vtk.vtkActor()
        boyActor.SetMapper(boyMapper)
        boyActor.SetPosition(8, -4, 0)
        boyActor.SetScale(1.5, 1.5, 1.5)

        boyTextMapper = vtk.vtkTextMapper()
        boyTextMapper.SetInput("Boy")
        boyTextMapper.GetTextProperty().SetJustificationToCentered()
        boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        boyTextMapper.GetTextProperty().SetColor(1, 0, 0)
        boyTextMapper.GetTextProperty().SetFontSize(14)
        boyTextActor = vtk.vtkActor2D()
        boyTextActor.SetMapper(boyTextMapper)
        boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0)

        # ------------------------------------------------------------
        # Create a cross cap
        # ------------------------------------------------------------
        crossCap = vtk.vtkParametricCrossCap()
        crossCapSource = vtk.vtkParametricFunctionSource()
        crossCapSource.SetParametricFunction(crossCap)
        crossCapSource.SetScalarModeToY()

        crossCapMapper = vtk.vtkPolyDataMapper()
        crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort())
        crossCapActor = vtk.vtkActor()
        crossCapActor.SetMapper(crossCapMapper)
        crossCapActor.RotateX(65)
        crossCapActor.SetPosition(16, -4, 0)
        crossCapActor.SetScale(1.5, 1.5, 1.5)

        crossCapTextMapper = vtk.vtkTextMapper()
        crossCapTextMapper.SetInput("Cross.Cap")
        crossCapTextMapper.GetTextProperty().SetJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0)
        crossCapTextMapper.GetTextProperty().SetFontSize(14)
        crossCapTextActor = vtk.vtkActor2D()
        crossCapTextActor.SetMapper(crossCapTextMapper)
        crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0)

        # ------------------------------------------------------------
        # Create Dini's surface
        # ------------------------------------------------------------
        dini = vtk.vtkParametricDini()
        diniSource = vtk.vtkParametricFunctionSource()
        diniSource.SetScalarModeToDistance()
        diniSource.SetParametricFunction(dini)

        diniMapper = vtk.vtkPolyDataMapper()
        diniMapper.SetInputConnection(diniSource.GetOutputPort())

        diniActor = vtk.vtkActor()
        diniActor.SetMapper(diniMapper)
        diniActor.RotateX(-90)
        diniActor.SetPosition(24, -3, 0)
        diniActor.SetScale(1.5, 1.5, 0.5)

        diniTextMapper = vtk.vtkTextMapper()
        diniTextMapper.SetInput("Dini")
        diniTextMapper.GetTextProperty().SetJustificationToCentered()
        diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        diniTextMapper.GetTextProperty().SetColor(1, 0, 0)
        diniTextMapper.GetTextProperty().SetFontSize(14)
        diniTextActor = vtk.vtkActor2D()
        diniTextActor.SetMapper(diniTextMapper)
        diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0)

        # ------------------------------------------------------------
        # Create Enneper's surface
        # ------------------------------------------------------------
        enneper = vtk.vtkParametricEnneper()
        enneperSource = vtk.vtkParametricFunctionSource()
        enneperSource.SetParametricFunction(enneper)
        enneperSource.SetScalarModeToQuadrant()

        enneperMapper = vtk.vtkPolyDataMapper()
        enneperMapper.SetInputConnection(enneperSource.GetOutputPort())
        enneperMapper.SetScalarRange(1, 4)

        enneperActor = vtk.vtkActor()
        enneperActor.SetMapper(enneperMapper)
        enneperActor.SetPosition(0, -12, 0)
        enneperActor.SetScale(0.25, 0.25, 0.25)

        enneperTextMapper = vtk.vtkTextMapper()
        enneperTextMapper.SetInput("Enneper")
        enneperTextMapper.GetTextProperty().SetJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        enneperTextMapper.GetTextProperty().SetColor(1, 0, 0)
        enneperTextMapper.GetTextProperty().SetFontSize(14)
        enneperTextActor = vtk.vtkActor2D()
        enneperTextActor.SetMapper(enneperTextMapper)
        enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0)

        # ------------------------------------------------------------
        # Create an ellipsoidal surface
        # ------------------------------------------------------------
        ellipsoid = vtk.vtkParametricEllipsoid()
        ellipsoid.SetXRadius(1)
        ellipsoid.SetYRadius(0.75)
        ellipsoid.SetZRadius(0.5)
        ellipsoidSource = vtk.vtkParametricFunctionSource()
        ellipsoidSource.SetParametricFunction(ellipsoid)
        ellipsoidSource.SetScalarModeToZ()

        ellipsoidMapper = vtk.vtkPolyDataMapper()
        ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort())
        ellipsoidMapper.SetScalarRange(-0.5, 0.5)

        ellipsoidActor = vtk.vtkActor()
        ellipsoidActor.SetMapper(ellipsoidMapper)
        ellipsoidActor.SetPosition(8, -12, 0)
        ellipsoidActor.SetScale(1.5, 1.5, 1.5)

        ellipsoidTextMapper = vtk.vtkTextMapper()
        ellipsoidTextMapper.SetInput("Ellipsoid")
        ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        ellipsoidTextMapper.GetTextProperty().SetFontSize(14)
        ellipsoidTextActor = vtk.vtkActor2D()
        ellipsoidTextActor.SetMapper(ellipsoidTextMapper)
        ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0)

        # ------------------------------------------------------------
        # Create a surface with random hills on it.
        # ------------------------------------------------------------
        randomHills = vtk.vtkParametricRandomHills()
        randomHills.AllowRandomGenerationOn()
        randomHillsSource = vtk.vtkParametricFunctionSource()
        randomHillsSource.SetParametricFunction(randomHills)
        randomHillsSource.GenerateTextureCoordinatesOn()

        randomHillsMapper = vtk.vtkPolyDataMapper()
        randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort())

        randomHillsActor = vtk.vtkActor()
        randomHillsActor.SetMapper(randomHillsMapper)
        randomHillsActor.SetPosition(16, -14, 0)
        randomHillsActor.SetScale(0.2, 0.2, 0.2)
        randomHillsActor.SetTexture(texture)

        randomHillsTextMapper = vtk.vtkTextMapper()
        randomHillsTextMapper.SetInput("Random.Hills")
        randomHillsTextMapper.GetTextProperty().SetJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0)
        randomHillsTextMapper.GetTextProperty().SetFontSize(14)
        randomHillsTextActor = vtk.vtkActor2D()
        randomHillsTextActor.SetMapper(randomHillsTextMapper)
        randomHillsTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0)

        # ------------------------------------------------------------
        # Create Steiner's Roman Surface.
        # ------------------------------------------------------------
        roman = vtk.vtkParametricRoman()
        roman.SetRadius(1.5)
        romanSource = vtk.vtkParametricFunctionSource()
        romanSource.SetParametricFunction(roman)
        romanSource.SetScalarModeToX()

        romanMapper = vtk.vtkPolyDataMapper()
        romanMapper.SetInputConnection(romanSource.GetOutputPort())

        romanActor = vtk.vtkActor()
        romanActor.SetMapper(romanMapper)
        romanActor.SetPosition(24, -12, 0)

        romanTextMapper = vtk.vtkTextMapper()
        romanTextMapper.SetInput("Roman")
        romanTextMapper.GetTextProperty().SetJustificationToCentered()
        romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        romanTextMapper.GetTextProperty().SetColor(1, 0, 0)
        romanTextMapper.GetTextProperty().SetFontSize(14)
        romanTextActor = vtk.vtkActor2D()
        romanTextActor.SetMapper(romanTextMapper)
        romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0)

        # ------------------------------------------------------------
        # Create the RenderWindow, Renderer and both Actors
        # ------------------------------------------------------------
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # add actors
        ren.AddViewProp(torusActor)
        ren.AddViewProp(kleinActor)
        ren.AddViewProp(klein2Actor)
        ren.AddViewProp(toroidActor)
        ren.AddViewProp(superEllipsoidActor)
        ren.AddViewProp(mobiusActor)
        ren.AddViewProp(splineActor)
        ren.AddViewProp(spline2Actor)
        ren.AddViewProp(sconicActor)
        ren.AddViewProp(boyActor)
        ren.AddViewProp(crossCapActor)
        ren.AddViewProp(diniActor)
        ren.AddViewProp(enneperActor)
        ren.AddViewProp(ellipsoidActor)
        ren.AddViewProp(randomHillsActor)
        ren.AddViewProp(romanActor)
        #add text actors
        ren.AddViewProp(torusTextActor)
        ren.AddViewProp(kleinTextActor)
        ren.AddViewProp(fig8KleinTextActor)
        ren.AddViewProp(mobiusTextActor)
        ren.AddViewProp(superToroidTextActor)
        ren.AddViewProp(superEllipsoidTextActor)
        ren.AddViewProp(splineTextActor)
        ren.AddViewProp(spline2TextActor)
        ren.AddViewProp(sconicTextActor)
        ren.AddViewProp(boyTextActor)
        ren.AddViewProp(crossCapTextActor)
        ren.AddViewProp(diniTextActor)
        ren.AddViewProp(enneperTextActor)
        ren.AddViewProp(ellipsoidTextActor)
        ren.AddViewProp(randomHillsTextActor)
        ren.AddViewProp(romanTextActor)

        ren.SetBackground(0.7, 0.8, 1)
        renWin.SetSize(500, 500)
        ren.ResetCamera()
        ren.GetActiveCamera().Zoom(1.3)

        iren.Initialize()
        renWin.Render()

        img_file = "TestParametricFunctions.png"
        # NOTE: this test has a companion .tcl test. The threshold set
        #  here should be the same as the threshold in the .tcl
        #  test. Both tests should produce exactly the same results.
        vtk.test.Testing.compareImage(iren.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=10)
        vtk.test.Testing.interact()
Exemplo n.º 55
0
def main():
    session = Set_Render_Variables("quake(13).csv")

    data = Data_Extractor(session)
    bounds = Model_Bounds_Points_Maker(data, session)
    events = Timed_Event_List_Maker(data.event_list, session)

    # sets up the VTK session
    ren = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    #renderWindow.AddRenderer(ren)
    i_ren = vtk.vtkRenderWindowInteractor()
    i_ren.SetRenderWindow(renderWindow)

    # text / legend object
    legend = vtk.vtkCornerAnnotation()
    legend.SetText(0, "          Quake Cloud 3d Visualiser\n          Depth Markers are 25Km Apart\n"
                      "          All other distances are relative \n\n\n          Copyright 2013 Jay Gattuso\n\n")
    legend.SetMaximumFontSize(15)


    # handles the overlay map image
    input_image = session.overlay_image_fname
    reader = vtk.vtkJPEGReader()
    reader.SetFileName(input_image)
    texture = vtk.vtkTexture()
    texture.SetInput(reader.GetOutput())
    texture.SetInputConnection(reader.GetOutputPort())
    texture.InterpolateOn()

    ren = vtk.vtkRenderer()
    renderWindow.AddRenderer(ren)
    plane = vtk.vtkPlaneSource()
    plane.SetOrigin((0, 0, 0))
    plane.SetPoint1(bounds.lat_max_distance)
    plane.SetPoint2(bounds.long_max_distance)

    # Create texture object
    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputConnection(plane.GetOutputPort())
    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)
    planeActor.SetTexture(texture)

    pointCloud_bounds = VtkPointCloud(data.event_max_depth)

    if session.plot_boundary_markers:
        for bound in bounds.bounds:
            pointCloud_bounds.addPoint(bound, 10)  # the number is what makes the bound markers larger

    if session.plot_depth_scale:
        for bound in bounds.bounds_scale:
            pointCloud_bounds.addPoint(bound, 10)  # the number is what makes the bound markers larger

    # add basic objects (bounds, overlay, background)
    ren.AddActor(pointCloud_bounds.vtkActor)
    ren.AddViewProp(legend)
    ren.AddActor(planeActor)
    ren.SetBackground(.2, .2, .2)
    ren.ResetCamera()

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Begin Interaction
    renderWindow.Render()

    # Initialize must be called prior to creating timer events.
    renderWindowInteractor.Initialize()

    # Sign up to receive TimerEvent
    cb = vtkTimerCallback(events.timed_event_dict, data.event_max_depth, ren, renderWindow, session)
    cb.actor = vtk.vtkActor()
    renderWindowInteractor.AddObserver('TimerEvent', cb.execute)
    timerId = renderWindowInteractor.CreateRepeatingTimer(session.replay_frame_speed)

    renderWindowInteractor.Start()
Exemplo n.º 56
0
decimate.SetDegree(25)
decimate.PreserveTopologyOn()
extrude = vtk.vtkLinearExtrusionFilter()
extrude.SetInputConnection(decimate.GetOutputPort())
extrude.SetExtrusionType(2)
extrude.SetScaleFactor(-20)
normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(extrude.GetOutputPort())
normals.SetFeatureAngle(80)
strip = vtk.vtkStripper()
strip.SetInputConnection(extrude.GetOutputPort())
map = vtk.vtkPolyDataMapper()
map.SetInputConnection(strip.GetOutputPort())
map.SetInputConnection(normals.GetOutputPort())
map.ScalarVisibilityOff()
imageTexture = vtk.vtkTexture()
imageTexture.InterpolateOn()
imageTexture.SetInputConnection(imagePowerOf2.GetOutputPort())
clipart = vtk.vtkActor()
clipart.SetMapper(map)
clipart.SetTexture(imageTexture)
ren1.AddActor(clipart)
clipart.GetProperty().SetDiffuseColor(1,1,1)
clipart.GetProperty().SetSpecular(.5)
clipart.GetProperty().SetSpecularPower(30)
clipart.GetProperty().SetDiffuse(.9)
ren1.ResetCamera()
camera = ren1.GetActiveCamera()
camera.Azimuth(30)
camera.Elevation(-30)
camera.Dolly(1.5)
    def testGlyphs(self):
        """Test if texturing of the glyphs works correctly."""
        # The Glyph
        cs = vtk.vtkCubeSource()
        cs.SetXLength(2.0); cs.SetYLength(1.0); cs.SetZLength(0.5)

        # Create input point data.
        pts = vtk.vtkPoints()
        pts.InsertPoint(0, (1,1,1))
        pts.InsertPoint(1, (0,0,0))
        pts.InsertPoint(2, (-1,-1,-1))
        polys = vtk.vtkCellArray()
        polys.InsertNextCell(1)
        polys.InsertCellPoint(0)
        polys.InsertNextCell(1)
        polys.InsertCellPoint(1)
        polys.InsertNextCell(1)
        polys.InsertCellPoint(2)
        pd = vtk.vtkPolyData()
        pd.SetPoints(pts)
        pd.SetPolys(polys)

        # Orient the glyphs as per vectors.
        vec = vtk.vtkFloatArray()
        vec.SetNumberOfComponents(3)
        vec.InsertTuple3(0, 1, 0, 0)
        vec.InsertTuple3(1, 0, 1, 0)
        vec.InsertTuple3(2, 0, 0, 1)
        pd.GetPointData().SetVectors(vec)

        # The glyph filter.
        g = vtk.vtkGlyph3D()
        g.SetScaleModeToDataScalingOff()
        g.SetVectorModeToUseVector()
        g.SetInputData(pd)
        g.SetSourceConnection(cs.GetOutputPort())

        m = vtk.vtkPolyDataMapper()
        m.SetInputConnection(g.GetOutputPort())
        a = vtk.vtkActor()
        a.SetMapper(m)

        # The texture.
        img_file = os.path.join(VTK_DATA_ROOT, "Data", "masonry.bmp")
        img_r = vtk.vtkBMPReader()
        img_r.SetFileName(img_file)
        t = vtk.vtkTexture()
        t.SetInputConnection(img_r.GetOutputPort())
        t.InterpolateOn()
        a.SetTexture(t)

        # Renderer, RenderWindow etc.
        ren = vtk.vtkRenderer()
        ren.SetBackground(0.5, 0.5, 0.5)
        ren.AddActor(a)

        ren.ResetCamera();
        cam = ren.GetActiveCamera()
        cam.Azimuth(-90)
        cam.Zoom(1.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        rwi = vtk.vtkRenderWindowInteractor()
        rwi.SetRenderWindow(renWin)
        rwi.Initialize()
        rwi.Render()
Exemplo n.º 58
0
    def prepareActorWithShadersAndMapper(self, points, poly, tdir):

        # Set point normals
        self.pointNormalsArray = vtk.vtkDoubleArray()
        pointNormalsArray = self.pointNormalsArray
        pointNormalsArray.SetNumberOfComponents(3)  # 3d normals (ie x,y,z)
        pointNormalsArray.SetNumberOfTuples(points.GetNumberOfPoints())

        # Add the data to the normals array (use for tangent vector...)
        self.pointNormalsArray.SetTuple3(0, tdir[0], tdir[1], tdir[2])
        pointNormalsArray.SetTuple3(1, tdir[0], tdir[1], tdir[2])
        pointNormalsArray.SetTuple3(2, tdir[0], tdir[1], tdir[2])
        pointNormalsArray.SetTuple3(3, tdir[0], tdir[1], tdir[2])

        # Set point tcoords
        self.pointTCoordsArray = vtk.vtkDoubleArray()
        pointTCoordsArray = self.pointTCoordsArray
        pointTCoordsArray.SetNumberOfComponents(3)  # 4d TCoords (ie s, t, p)
        pointTCoordsArray.SetNumberOfTuples(points.GetNumberOfPoints())
        pointTCoordsArray.SetName("thickness_falloff")

        # Add the data to the TCoords array (use for expansion direction...)
        # Hmm, okay, now i see. if we do all of our calcs in VC
        # and the offset scale is constant there (which is how it is done now),
        # then the width of the polygon will never change
        # when zooming in and out, since the width is constant...
        th = self.linethickness / 2.0
        fall = self.falloff
        pointTCoordsArray.SetTuple3(0, -1.0, th, fall)  # (expansion dir, offset scale, falloff)
        pointTCoordsArray.SetTuple3(1, 1.0, th, fall)
        pointTCoordsArray.SetTuple3(2, 1.0, th, fall)
        pointTCoordsArray.SetTuple3(3, -1.0, th, fall)

        """
        # Set gl_Color for each vertex, and have alpha = (1 - abs(expansion direction))^falloff
        pointColorArray = vtk.vtkDoubleArray()
        pointColorArray.SetNumberOfComponents(3) #4d TCoords (ie s, t, p)
        pointColorArray.SetNumberOfTuples( points.GetNumberOfPoints() )
        
        pointColorArray.SetTuple3(0, 1., 0., 0.) 
        pointColorArray.SetTuple3(1, 1., 0., 0.) 
        pointColorArray.SetTuple3(2, 1., 0., 0.) 
        pointColorArray.SetTuple3(3, 1., 0., 0.) 
        """

        polys = vtk.vtkCellArray()
        polys.InsertNextCell(poly)

        # appears that we need a texture for tcoords glsl attribute variable to be set
        # Apply the texture
        reader = vtk.vtkJPEGReader()
        reader.SetFileName("../examplesAndSandboxCode/test.jpeg")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(reader.GetOutputPort())
        atext.InterpolateOn()

        actor = self.actor
        actor.SetTexture(atext)

        quadPolyData = self.polydata
        quadPolyData.SetPoints(points)
        quadPolyData.SetPolys(polys)
        # Add the normals to the points in the polydata, on a vtkDataSetAttributes object
        quadPolyData.GetPointData().SetNormals(pointNormalsArray)
        quadPolyData.GetPointData().SetTCoords(pointTCoordsArray)
        quadPolyData.GetPointData().SetActiveTCoords("thickness_falloff")
        # actor.GetProperty().SetDiffuseColor(1, 0, 0) # Red
        # actor.GetProperty().SetSpecularColor(1, 0, 0) # Red
        # actor.GetProperty().SetEdgeVisibility(False)

        gl_mapper = self.gl_mapper
        gl_mapper.SetInputData(quadPolyData)

        actor.SetMapper(gl_mapper)

        gl_mapper.SetVertexShaderCode(vertshader)
        gl_mapper.SetFragmentShaderCode(fragshader)

        # gl_mapper.SetBlendModeToAdditive()

        val = actor.HasTranslucentPolygonalGeometry()
        # actor.ForceTranslucentOn()

        actor.VisibilityOff()

        return actor
Exemplo n.º 59
0
    def testCells(self):

        # Demonstrates all cell types
        #
        # NOTE: the use of NewInstance/DeepCopy is included to increase
        # regression coverage.  It is not required in most applications.

        ren = vtk.vtkRenderer()
        # turn off all cullers
        ren.GetCullers().RemoveAllItems()

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(300, 150)
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)

        # create a scene with one of each cell type

        # Voxel

        voxelPoints = vtk.vtkPoints()
        voxelPoints.SetNumberOfPoints(8)
        voxelPoints.InsertPoint(0, 0, 0, 0)
        voxelPoints.InsertPoint(1, 1, 0, 0)
        voxelPoints.InsertPoint(2, 0, 1, 0)
        voxelPoints.InsertPoint(3, 1, 1, 0)
        voxelPoints.InsertPoint(4, 0, 0, 1)
        voxelPoints.InsertPoint(5, 1, 0, 1)
        voxelPoints.InsertPoint(6, 0, 1, 1)
        voxelPoints.InsertPoint(7, 1, 1, 1)

        aVoxel = vtk.vtkVoxel()
        aVoxel.GetPointIds().SetId(0, 0)
        aVoxel.GetPointIds().SetId(1, 1)
        aVoxel.GetPointIds().SetId(2, 2)
        aVoxel.GetPointIds().SetId(3, 3)
        aVoxel.GetPointIds().SetId(4, 4)
        aVoxel.GetPointIds().SetId(5, 5)
        aVoxel.GetPointIds().SetId(6, 6)
        aVoxel.GetPointIds().SetId(7, 7)

        bVoxel = aVoxel.NewInstance()
        bVoxel.DeepCopy(aVoxel)

        aVoxelGrid = vtk.vtkUnstructuredGrid()
        aVoxelGrid.Allocate(1, 1)
        aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds())
        aVoxelGrid.SetPoints(voxelPoints)

        aVoxelMapper = vtk.vtkDataSetMapper()
        aVoxelMapper.SetInputData(aVoxelGrid)

        aVoxelActor = vtk.vtkActor()
        aVoxelActor.SetMapper(aVoxelMapper)
        aVoxelActor.GetProperty().BackfaceCullingOn()

        # Hexahedron

        hexahedronPoints = vtk.vtkPoints()
        hexahedronPoints.SetNumberOfPoints(8)
        hexahedronPoints.InsertPoint(0, 0, 0, 0)
        hexahedronPoints.InsertPoint(1, 1, 0, 0)
        hexahedronPoints.InsertPoint(2, 1, 1, 0)
        hexahedronPoints.InsertPoint(3, 0, 1, 0)
        hexahedronPoints.InsertPoint(4, 0, 0, 1)
        hexahedronPoints.InsertPoint(5, 1, 0, 1)
        hexahedronPoints.InsertPoint(6, 1, 1, 1)
        hexahedronPoints.InsertPoint(7, 0, 1, 1)

        aHexahedron = vtk.vtkHexahedron()
        aHexahedron.GetPointIds().SetId(0, 0)
        aHexahedron.GetPointIds().SetId(1, 1)
        aHexahedron.GetPointIds().SetId(2, 2)
        aHexahedron.GetPointIds().SetId(3, 3)
        aHexahedron.GetPointIds().SetId(4, 4)
        aHexahedron.GetPointIds().SetId(5, 5)
        aHexahedron.GetPointIds().SetId(6, 6)
        aHexahedron.GetPointIds().SetId(7, 7)

        bHexahedron = aHexahedron.NewInstance()
        bHexahedron.DeepCopy(aHexahedron)

        aHexahedronGrid = vtk.vtkUnstructuredGrid()
        aHexahedronGrid.Allocate(1, 1)
        aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds())
        aHexahedronGrid.SetPoints(hexahedronPoints)

        aHexahedronMapper = vtk.vtkDataSetMapper()
        aHexahedronMapper.SetInputData(aHexahedronGrid)

        aHexahedronActor = vtk.vtkActor()
        aHexahedronActor.SetMapper(aHexahedronMapper)
        aHexahedronActor.AddPosition(2, 0, 0)
        aHexahedronActor.GetProperty().BackfaceCullingOn()

        # Tetra

        tetraPoints = vtk.vtkPoints()
        tetraPoints.SetNumberOfPoints(4)
        tetraPoints.InsertPoint(0, 0, 0, 0)
        tetraPoints.InsertPoint(1, 1, 0, 0)
        tetraPoints.InsertPoint(2, 0.5, 1, 0)
        tetraPoints.InsertPoint(3, 0.5, 0.5, 1)

        aTetra = vtk.vtkTetra()
        aTetra.GetPointIds().SetId(0, 0)
        aTetra.GetPointIds().SetId(1, 1)
        aTetra.GetPointIds().SetId(2, 2)
        aTetra.GetPointIds().SetId(3, 3)

        bTetra = aTetra.NewInstance()
        bTetra.DeepCopy(aTetra)

        aTetraGrid = vtk.vtkUnstructuredGrid()
        aTetraGrid.Allocate(1, 1)
        aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds())
        aTetraGrid.SetPoints(tetraPoints)

        aTetraCopy = vtk.vtkUnstructuredGrid()
        aTetraCopy.ShallowCopy(aTetraGrid)

        aTetraMapper = vtk.vtkDataSetMapper()
        aTetraMapper.SetInputData(aTetraCopy)

        aTetraActor = vtk.vtkActor()
        aTetraActor.SetMapper(aTetraMapper)
        aTetraActor.AddPosition(4, 0, 0)
        aTetraActor.GetProperty().BackfaceCullingOn()

        # Wedge

        wedgePoints = vtk.vtkPoints()
        wedgePoints.SetNumberOfPoints(6)
        wedgePoints.InsertPoint(0, 0, 1, 0)
        wedgePoints.InsertPoint(1, 0, 0, 0)
        wedgePoints.InsertPoint(2, 0, 0.5, 0.5)
        wedgePoints.InsertPoint(3, 1, 1, 0)
        wedgePoints.InsertPoint(4, 1, 0, 0)
        wedgePoints.InsertPoint(5, 1, 0.5, 0.5)

        aWedge = vtk.vtkWedge()
        aWedge.GetPointIds().SetId(0, 0)
        aWedge.GetPointIds().SetId(1, 1)
        aWedge.GetPointIds().SetId(2, 2)
        aWedge.GetPointIds().SetId(3, 3)
        aWedge.GetPointIds().SetId(4, 4)
        aWedge.GetPointIds().SetId(5, 5)

        bWedge = aWedge.NewInstance()
        bWedge.DeepCopy(aWedge)

        aWedgeGrid = vtk.vtkUnstructuredGrid()
        aWedgeGrid.Allocate(1, 1)
        aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds())
        aWedgeGrid.SetPoints(wedgePoints)

        aWedgeCopy = vtk.vtkUnstructuredGrid()
        aWedgeCopy.DeepCopy(aWedgeGrid)

        aWedgeMapper = vtk.vtkDataSetMapper()
        aWedgeMapper.SetInputData(aWedgeCopy)

        aWedgeActor = vtk.vtkActor()
        aWedgeActor.SetMapper(aWedgeMapper)
        aWedgeActor.AddPosition(6, 0, 0)
        aWedgeActor.GetProperty().BackfaceCullingOn()

        # Pyramid

        pyramidPoints = vtk.vtkPoints()
        pyramidPoints.SetNumberOfPoints(5)
        pyramidPoints.InsertPoint(0, 0, 0, 0)
        pyramidPoints.InsertPoint(1, 1, 0, 0)
        pyramidPoints.InsertPoint(2, 1, 1, 0)
        pyramidPoints.InsertPoint(3, 0, 1, 0)
        pyramidPoints.InsertPoint(4, 0.5, 0.5, 1)

        aPyramid = vtk.vtkPyramid()
        aPyramid.GetPointIds().SetId(0, 0)
        aPyramid.GetPointIds().SetId(1, 1)
        aPyramid.GetPointIds().SetId(2, 2)
        aPyramid.GetPointIds().SetId(3, 3)
        aPyramid.GetPointIds().SetId(4, 4)

        bPyramid = aPyramid.NewInstance()
        bPyramid.DeepCopy(aPyramid)

        aPyramidGrid = vtk.vtkUnstructuredGrid()
        aPyramidGrid.Allocate(1, 1)
        aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds())
        aPyramidGrid.SetPoints(pyramidPoints)

        aPyramidMapper = vtk.vtkDataSetMapper()
        aPyramidMapper.SetInputData(aPyramidGrid)

        aPyramidActor = vtk.vtkActor()
        aPyramidActor.SetMapper(aPyramidMapper)
        aPyramidActor.AddPosition(8, 0, 0)
        aPyramidActor.GetProperty().BackfaceCullingOn()

        # Pixel

        pixelPoints = vtk.vtkPoints()
        pixelPoints.SetNumberOfPoints(4)
        pixelPoints.InsertPoint(0, 0, 0, 0)
        pixelPoints.InsertPoint(1, 1, 0, 0)
        pixelPoints.InsertPoint(2, 0, 1, 0)
        pixelPoints.InsertPoint(3, 1, 1, 0)

        aPixel = vtk.vtkPixel()
        aPixel.GetPointIds().SetId(0, 0)
        aPixel.GetPointIds().SetId(1, 1)
        aPixel.GetPointIds().SetId(2, 2)
        aPixel.GetPointIds().SetId(3, 3)

        bPixel = aPixel.NewInstance()
        bPixel.DeepCopy(aPixel)

        aPixelGrid = vtk.vtkUnstructuredGrid()
        aPixelGrid.Allocate(1, 1)
        aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds())
        aPixelGrid.SetPoints(pixelPoints)

        aPixelMapper = vtk.vtkDataSetMapper()
        aPixelMapper.SetInputData(aPixelGrid)

        aPixelActor = vtk.vtkActor()
        aPixelActor.SetMapper(aPixelMapper)
        aPixelActor.AddPosition(0, 0, 2)
        aPixelActor.GetProperty().BackfaceCullingOn()

        # Quad

        quadPoints = vtk.vtkPoints()
        quadPoints.SetNumberOfPoints(4)
        quadPoints.InsertPoint(0, 0, 0, 0)
        quadPoints.InsertPoint(1, 1, 0, 0)
        quadPoints.InsertPoint(2, 1, 1, 0)
        quadPoints.InsertPoint(3, 0, 1, 0)

        aQuad = vtk.vtkQuad()
        aQuad.GetPointIds().SetId(0, 0)
        aQuad.GetPointIds().SetId(1, 1)
        aQuad.GetPointIds().SetId(2, 2)
        aQuad.GetPointIds().SetId(3, 3)

        bQuad = aQuad.NewInstance()
        bQuad.DeepCopy(aQuad)

        aQuadGrid = vtk.vtkUnstructuredGrid()
        aQuadGrid.Allocate(1, 1)
        aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds())
        aQuadGrid.SetPoints(quadPoints)

        aQuadMapper = vtk.vtkDataSetMapper()
        aQuadMapper.SetInputData(aQuadGrid)

        aQuadActor = vtk.vtkActor()
        aQuadActor.SetMapper(aQuadMapper)
        aQuadActor.AddPosition(2, 0, 2)
        aQuadActor.GetProperty().BackfaceCullingOn()

        # Triangle

        trianglePoints = vtk.vtkPoints()
        trianglePoints.SetNumberOfPoints(3)
        trianglePoints.InsertPoint(0, 0, 0, 0)
        trianglePoints.InsertPoint(1, 1, 0, 0)
        trianglePoints.InsertPoint(2, 0.5, 0.5, 0)

        triangleTCoords = vtk.vtkFloatArray()
        triangleTCoords.SetNumberOfComponents(2)
        triangleTCoords.SetNumberOfTuples(3)
        triangleTCoords.InsertTuple2(0, 1, 1)
        triangleTCoords.InsertTuple2(1, 2, 2)
        triangleTCoords.InsertTuple2(2, 3, 3)

        aTriangle = vtk.vtkTriangle()
        aTriangle.GetPointIds().SetId(0, 0)
        aTriangle.GetPointIds().SetId(1, 1)
        aTriangle.GetPointIds().SetId(2, 2)

        bTriangle = aTriangle.NewInstance()
        bTriangle.DeepCopy(aTriangle)

        aTriangleGrid = vtk.vtkUnstructuredGrid()
        aTriangleGrid.Allocate(1, 1)
        aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds())
        aTriangleGrid.SetPoints(trianglePoints)
        aTriangleGrid.GetPointData().SetTCoords(triangleTCoords)

        aTriangleMapper = vtk.vtkDataSetMapper()
        aTriangleMapper.SetInputData(aTriangleGrid)

        aTriangleActor = vtk.vtkActor()
        aTriangleActor.SetMapper(aTriangleMapper)
        aTriangleActor.AddPosition(4, 0, 2)
        aTriangleActor.GetProperty().BackfaceCullingOn()

        # Polygon

        polygonPoints = vtk.vtkPoints()
        polygonPoints.SetNumberOfPoints(4)
        polygonPoints.InsertPoint(0, 0, 0, 0)
        polygonPoints.InsertPoint(1, 1, 0, 0)
        polygonPoints.InsertPoint(2, 1, 1, 0)
        polygonPoints.InsertPoint(3, 0, 1, 0)

        aPolygon = vtk.vtkPolygon()
        aPolygon.GetPointIds().SetNumberOfIds(4)
        aPolygon.GetPointIds().SetId(0, 0)
        aPolygon.GetPointIds().SetId(1, 1)
        aPolygon.GetPointIds().SetId(2, 2)
        aPolygon.GetPointIds().SetId(3, 3)

        bPolygon = aPolygon.NewInstance()
        bPolygon.DeepCopy(aPolygon)

        aPolygonGrid = vtk.vtkUnstructuredGrid()
        aPolygonGrid.Allocate(1, 1)
        aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds())
        aPolygonGrid.SetPoints(polygonPoints)

        aPolygonMapper = vtk.vtkDataSetMapper()
        aPolygonMapper.SetInputData(aPolygonGrid)

        aPolygonActor = vtk.vtkActor()
        aPolygonActor.SetMapper(aPolygonMapper)
        aPolygonActor.AddPosition(6, 0, 2)
        aPolygonActor.GetProperty().BackfaceCullingOn()

        # Triangle Strip

        triangleStripPoints = vtk.vtkPoints()
        triangleStripPoints.SetNumberOfPoints(5)
        triangleStripPoints.InsertPoint(0, 0, 1, 0)
        triangleStripPoints.InsertPoint(1, 0, 0, 0)
        triangleStripPoints.InsertPoint(2, 1, 1, 0)
        triangleStripPoints.InsertPoint(3, 1, 0, 0)
        triangleStripPoints.InsertPoint(4, 2, 1, 0)

        triangleStripTCoords = vtk.vtkFloatArray()
        triangleStripTCoords.SetNumberOfComponents(2)
        triangleStripTCoords.SetNumberOfTuples(3)
        triangleStripTCoords.InsertTuple2(0, 1, 1)
        triangleStripTCoords.InsertTuple2(1, 2, 2)
        triangleStripTCoords.InsertTuple2(2, 3, 3)
        triangleStripTCoords.InsertTuple2(3, 4, 4)
        triangleStripTCoords.InsertTuple2(4, 5, 5)

        aTriangleStrip = vtk.vtkTriangleStrip()
        aTriangleStrip.GetPointIds().SetNumberOfIds(5)
        aTriangleStrip.GetPointIds().SetId(0, 0)
        aTriangleStrip.GetPointIds().SetId(1, 1)
        aTriangleStrip.GetPointIds().SetId(2, 2)
        aTriangleStrip.GetPointIds().SetId(3, 3)
        aTriangleStrip.GetPointIds().SetId(4, 4)

        bTriangleStrip = aTriangleStrip.NewInstance()
        bTriangleStrip.DeepCopy(aTriangleStrip)

        aTriangleStripGrid = vtk.vtkUnstructuredGrid()
        aTriangleStripGrid.Allocate(1, 1)
        aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds())
        aTriangleStripGrid.SetPoints(triangleStripPoints)
        aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords)

        aTriangleStripMapper = vtk.vtkDataSetMapper()
        aTriangleStripMapper.SetInputData(aTriangleStripGrid)

        aTriangleStripActor = vtk.vtkActor()
        aTriangleStripActor.SetMapper(aTriangleStripMapper)
        aTriangleStripActor.AddPosition(8, 0, 2)
        aTriangleStripActor.GetProperty().BackfaceCullingOn()

        # Line

        linePoints = vtk.vtkPoints()
        linePoints.SetNumberOfPoints(2)
        linePoints.InsertPoint(0, 0, 0, 0)
        linePoints.InsertPoint(1, 1, 1, 0)

        aLine = vtk.vtkLine()
        aLine.GetPointIds().SetId(0, 0)
        aLine.GetPointIds().SetId(1, 1)

        bLine = aLine.NewInstance()
        bLine.DeepCopy(aLine)

        aLineGrid = vtk.vtkUnstructuredGrid()
        aLineGrid.Allocate(1, 1)
        aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds())
        aLineGrid.SetPoints(linePoints)

        aLineMapper = vtk.vtkDataSetMapper()
        aLineMapper.SetInputData(aLineGrid)

        aLineActor = vtk.vtkActor()
        aLineActor.SetMapper(aLineMapper)
        aLineActor.AddPosition(0, 0, 4)
        aLineActor.GetProperty().BackfaceCullingOn()

        # Poly line

        polyLinePoints = vtk.vtkPoints()
        polyLinePoints.SetNumberOfPoints(3)
        polyLinePoints.InsertPoint(0, 0, 0, 0)
        polyLinePoints.InsertPoint(1, 1, 1, 0)
        polyLinePoints.InsertPoint(2, 1, 0, 0)

        aPolyLine = vtk.vtkPolyLine()
        aPolyLine.GetPointIds().SetNumberOfIds(3)
        aPolyLine.GetPointIds().SetId(0, 0)
        aPolyLine.GetPointIds().SetId(1, 1)
        aPolyLine.GetPointIds().SetId(2, 2)

        bPolyLine = aPolyLine.NewInstance()
        bPolyLine.DeepCopy(aPolyLine)

        aPolyLineGrid = vtk.vtkUnstructuredGrid()
        aPolyLineGrid.Allocate(1, 1)
        aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds())
        aPolyLineGrid.SetPoints(polyLinePoints)

        aPolyLineMapper = vtk.vtkDataSetMapper()
        aPolyLineMapper.SetInputData(aPolyLineGrid)

        aPolyLineActor = vtk.vtkActor()
        aPolyLineActor.SetMapper(aPolyLineMapper)
        aPolyLineActor.AddPosition(2, 0, 4)
        aPolyLineActor.GetProperty().BackfaceCullingOn()

        # Vertex

        vertexPoints = vtk.vtkPoints()
        vertexPoints.SetNumberOfPoints(1)
        vertexPoints.InsertPoint(0, 0, 0, 0)

        aVertex = vtk.vtkVertex()
        aVertex.GetPointIds().SetId(0, 0)

        bVertex = aVertex.NewInstance()
        bVertex.DeepCopy(aVertex)

        aVertexGrid = vtk.vtkUnstructuredGrid()
        aVertexGrid.Allocate(1, 1)
        aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds())
        aVertexGrid.SetPoints(vertexPoints)

        aVertexMapper = vtk.vtkDataSetMapper()
        aVertexMapper.SetInputData(aVertexGrid)

        aVertexActor = vtk.vtkActor()
        aVertexActor.SetMapper(aVertexMapper)
        aVertexActor.AddPosition(0, 0, 6)
        aVertexActor.GetProperty().BackfaceCullingOn()

        # Poly Vertex

        polyVertexPoints = vtk.vtkPoints()
        polyVertexPoints.SetNumberOfPoints(3)
        polyVertexPoints.InsertPoint(0, 0, 0, 0)
        polyVertexPoints.InsertPoint(1, 1, 0, 0)
        polyVertexPoints.InsertPoint(2, 1, 1, 0)

        aPolyVertex = vtk.vtkPolyVertex()
        aPolyVertex.GetPointIds().SetNumberOfIds(3)
        aPolyVertex.GetPointIds().SetId(0, 0)
        aPolyVertex.GetPointIds().SetId(1, 1)
        aPolyVertex.GetPointIds().SetId(2, 2)

        bPolyVertex = aPolyVertex.NewInstance()
        bPolyVertex.DeepCopy(aPolyVertex)

        aPolyVertexGrid = vtk.vtkUnstructuredGrid()
        aPolyVertexGrid.Allocate(1, 1)
        aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds())
        aPolyVertexGrid.SetPoints(polyVertexPoints)

        aPolyVertexMapper = vtk.vtkDataSetMapper()
        aPolyVertexMapper.SetInputData(aPolyVertexGrid)

        aPolyVertexActor = vtk.vtkActor()
        aPolyVertexActor.SetMapper(aPolyVertexMapper)
        aPolyVertexActor.AddPosition(2, 0, 6)
        aPolyVertexActor.GetProperty().BackfaceCullingOn()

        # Pentagonal prism

        pentaPoints = vtk.vtkPoints()
        pentaPoints.SetNumberOfPoints(10)
        pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0)
        pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0)
        pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0)
        pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0)
        pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0)
        pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0)
        pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0)
        pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0)
        pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0)

        aPenta = vtk.vtkPentagonalPrism()
        aPenta.GetPointIds().SetId(0, 0)
        aPenta.GetPointIds().SetId(1, 1)
        aPenta.GetPointIds().SetId(2, 2)
        aPenta.GetPointIds().SetId(3, 3)
        aPenta.GetPointIds().SetId(4, 4)
        aPenta.GetPointIds().SetId(5, 5)
        aPenta.GetPointIds().SetId(6, 6)
        aPenta.GetPointIds().SetId(7, 7)
        aPenta.GetPointIds().SetId(8, 8)
        aPenta.GetPointIds().SetId(9, 9)

        bPenta = aPenta.NewInstance()
        bPenta.DeepCopy(aPenta)

        aPentaGrid = vtk.vtkUnstructuredGrid()
        aPentaGrid.Allocate(1, 1)
        aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds())
        aPentaGrid.SetPoints(pentaPoints)

        aPentaCopy = vtk.vtkUnstructuredGrid()
        aPentaCopy.DeepCopy(aPentaGrid)

        aPentaMapper = vtk.vtkDataSetMapper()
        aPentaMapper.SetInputData(aPentaCopy)

        aPentaActor = vtk.vtkActor()
        aPentaActor.SetMapper(aPentaMapper)
        aPentaActor.AddPosition(10, 0, 0)
        aPentaActor.GetProperty().BackfaceCullingOn()

        # Hexagonal prism

        hexaPoints = vtk.vtkPoints()
        hexaPoints.SetNumberOfPoints(12)
        hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0)
        hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0)
        hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0)
        hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0)
        hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0)
        hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0)
        hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0)
        hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0)
        hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0)
        hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0)
        hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0)
        hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0)

        aHexa = vtk.vtkHexagonalPrism()
        aHexa.GetPointIds().SetId(0, 0)
        aHexa.GetPointIds().SetId(1, 1)
        aHexa.GetPointIds().SetId(2, 2)
        aHexa.GetPointIds().SetId(3, 3)
        aHexa.GetPointIds().SetId(4, 4)
        aHexa.GetPointIds().SetId(5, 5)
        aHexa.GetPointIds().SetId(6, 6)
        aHexa.GetPointIds().SetId(7, 7)
        aHexa.GetPointIds().SetId(8, 8)
        aHexa.GetPointIds().SetId(9, 9)
        aHexa.GetPointIds().SetId(10, 10)
        aHexa.GetPointIds().SetId(11, 11)

        bHexa = aHexa.NewInstance()
        bHexa.DeepCopy(aHexa)

        aHexaGrid = vtk.vtkUnstructuredGrid()
        aHexaGrid.Allocate(1, 1)
        aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds())
        aHexaGrid.SetPoints(hexaPoints)

        aHexaCopy = vtk.vtkUnstructuredGrid()
        aHexaCopy.DeepCopy(aHexaGrid)

        aHexaMapper = vtk.vtkDataSetMapper()
        aHexaMapper.SetInputData(aHexaCopy)

        aHexaActor = vtk.vtkActor()
        aHexaActor.SetMapper(aHexaMapper)
        aHexaActor.AddPosition(12, 0, 0)
        aHexaActor.GetProperty().BackfaceCullingOn()

        # RIB property
        aRIBProperty = vtk.vtkRIBProperty()
        aRIBProperty.SetVariable("Km", "float")
        aRIBProperty.SetSurfaceShader("LGVeinedmarble")
        aRIBProperty.SetVariable("veinfreq", "float")
        aRIBProperty.AddVariable("warpfreq", "float")
        aRIBProperty.AddVariable("veincolor", "color")
        aRIBProperty.AddParameter("veinfreq", " 2")
        aRIBProperty.AddParameter("veincolor", "1.0000 1.0000 0.9412")
        bRIBProperty = vtk.vtkRIBProperty()
        bRIBProperty.SetVariable("Km", "float")
        bRIBProperty.SetParameter("Km", "1.0")
        bRIBProperty.SetDisplacementShader("dented")
        bRIBProperty.SetSurfaceShader("plastic")
        aProperty = vtk.vtkProperty()
        bProperty = vtk.vtkProperty()

        aTriangleActor.SetProperty(aProperty)
        aTriangleStripActor.SetProperty(bProperty)

        ren.SetBackground(0.1, 0.2, 0.4)

        ren.AddActor(aVoxelActor)
        aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0)
        ren.AddActor(aHexahedronActor)
        aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0)
        ren.AddActor(aTetraActor)
        aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0)
        ren.AddActor(aWedgeActor)
        aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aPyramidActor)
        aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aPixelActor)
        aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1)
        ren.AddActor(aQuadActor)
        aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1)
        ren.AddActor(aTriangleActor)
        aTriangleActor.GetProperty().SetDiffuseColor(0.3, 1, 0.5)
        ren.AddActor(aPolygonActor)
        aPolygonActor.GetProperty().SetDiffuseColor(1, 0.4, 0.5)
        ren.AddActor(aTriangleStripActor)
        aTriangleStripActor.GetProperty().SetDiffuseColor(0.3, 0.7, 1)
        ren.AddActor(aLineActor)
        aLineActor.GetProperty().SetDiffuseColor(0.2, 1, 1)
        ren.AddActor(aPolyLineActor)
        aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aVertexActor)
        aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPolyVertexActor)
        aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1)
        ren.AddActor(aPentaActor)
        aPentaActor.GetProperty().SetDiffuseColor(0.2, 0.4, 0.7)
        ren.AddActor(aHexaActor)
        aHexaActor.GetProperty().SetDiffuseColor(0.7, 0.5, 1)

        aRIBLight = vtk.vtkRIBLight()
        aRIBLight.ShadowsOn()
        aLight = vtk.vtkLight()

        aLight.PositionalOn()
        aLight.SetConeAngle(25)

        ren.AddLight(aLight)

        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(30)
        ren.GetActiveCamera().Elevation(20)
        ren.GetActiveCamera().Dolly(2.8)
        ren.ResetCameraClippingRange()

        aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint())
        aLight.SetPosition(ren.GetActiveCamera().GetPosition())

        # write to the temp directory if possible, otherwise use .
        dir = tempfile.gettempdir()

        atext = vtk.vtkTexture()
        pnmReader = vtk.vtkBMPReader()
        pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
        atext.SetInputConnection(pnmReader.GetOutputPort())
        atext.InterpolateOff()
        aTriangleActor.SetTexture(atext)
        rib = vtk.vtkRIBExporter()
        rib.SetInput(renWin)
        rib.SetFilePrefix(dir + "/cells")
        rib.SetTexturePrefix(dir + "/cells")
        rib.Write()
        os.remove(dir + "/cells.rib")

        iv = vtk.vtkIVExporter()
        iv.SetInput(renWin)
        iv.SetFileName(dir + "/cells.iv")
        iv.Write()
        os.remove(dir + "/cells.iv")

        obj = vtk.vtkOBJExporter()
        obj.SetInput(renWin)
        obj.SetFilePrefix(dir + "/cells")
        obj.Write()
        os.remove(dir + "/cells.obj")
        os.remove(dir + "/cells.mtl")

        vrml = vtk.vtkVRMLExporter()
        vrml.SetInput(renWin)
        # vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl"))
        # vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl"))
        vrml.SetFileName(dir + "/cells.wrl")
        vrml.SetSpeed(5.5)
        vrml.Write()
        os.remove(dir + "/cells.wrl")

        oogl = vtk.vtkOOGLExporter()
        oogl.SetInput(renWin)
        oogl.SetFileName(dir + "/cells.oogl")
        oogl.Write()
        os.remove(dir + "/cells.oogl")

        # the UnRegister calls are because make object is the same as New,
        # and causes memory leaks. (Python does not treat NewInstance the same as New).
        def DeleteCopies():
            bVoxel.UnRegister(None)
            bHexahedron.UnRegister(None)
            bTetra.UnRegister(None)
            bWedge.UnRegister(None)
            bPyramid.UnRegister(None)
            bPixel.UnRegister(None)
            bQuad.UnRegister(None)
            bTriangle.UnRegister(None)
            bPolygon.UnRegister(None)
            bTriangleStrip.UnRegister(None)
            bLine.UnRegister(None)
            bPolyLine.UnRegister(None)
            bVertex.UnRegister(None)
            bPolyVertex.UnRegister(None)
            bPenta.UnRegister(None)
            bHexa.UnRegister(None)

        DeleteCopies()

        # render and interact with data

        renWin.Render()

        img_file = "cells.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 60
0
def vis_imgInit(ren):
    rdr = [None]*2
    txt = [None]*2
    plane = [None]*2
    tmap = [None]*2
    cast = [None]*2
    vmap = [None]*2
    actor = [None]*2
    lookupGrayscale = [None]*2
    lookupColor = [None]*2
    
    rdr[0] = 'vis_img_reader_' + ren[0]
    txt[0] = 'vis_img_texture_' + ren[0]
    plane[0] = 'vis_img_plane_' + ren[0]
    tmap[0] = 'vis_img_tmap_' + ren[0]
    vmap[0] = 'vis_img_map_' + ren[0]
    actor[0] = 'vis_img_actor_' + ren[0]
    lookupGrayscale[0] = 'vis_img_g8bitGrayscaleLUT_' + ren[0]
    lookupColor[0] = 'vis_img_gBlueToRedLUT_'+ ren[0]
    
    rdr[1] = vtk.vtkImageReader()
    rdr[1].SetDataScalarTypeToShort()
    rdr[1].SetFileDimensionality(2)
    rdr[1].SetDataByteOrderToBigEndian()
    
    txt[1] = vtk.vtkTexture()
    plane[1] = vtk.vtkPlaneSource()
    plane[1].SetResolution(1,1)
    plane[1].SetOrigin(0.,0.,0.)
    
    tmap[1] = vtk.vtkTextureMapToPlane()
    tmap[1].SetInputConnection(plane[1].GetOutputPort())
    
    cast[1] = vtk.vtkCastToConcrete()
    cast[1].SetInputConnection(tmap[1].GetOutputPort())
    
    vmap[1] = vtk.vtkPolyDataMapper()
    vmap[1].SetInputConnection(cast[1].GetOutputPort())
    
    actor[1] = vtk.vtkActor()
    actor[1].SetMapper(vmap[1])
    actor[1].SetTexture(txt[1])
    
    lookupGrayscale[1] = vtk.vtkLookupTable()
    lookupGrayscale[1].SetHueRange(0.,0.)
    lookupGrayscale[1].SetSaturationRange(0.,0.)
    lookupGrayscale[1].SetValueRange(0.,1.)
    lookupGrayscale[1].SetNumberOfColors(16384)
    lookupGrayscale[1].Build()
    
    lookupColor[1] = vtk.vtkLookupTable()
    lookupColor[1].SetHueRange(0.6667,0.)
    lookupColor[1].SetSaturationRange(1.,1.)
    lookupColor[1].SetValueRange(1.,1.)
    lookupColor[1].SetAlphaRange(1.,1.)
    lookupColor[1].SetNumberOfColors(16384)
    lookupColor[1].Build()
    
    setattr(vis,rdr[0], rdr)
    setattr(vis,txt[0], txt)
    setattr(vis,plane[0], plane)
    setattr(vis,tmap[0], tmap)
    setattr(vis,vmap[0], vmap)
    setattr(vis,actor[0], actor)
    setattr(vis,lookupGrayscale[0], lookupGrayscale)
    setattr(vis,lookupColor[0], lookupColor)
    return