Esempio n. 1
0
    def __init__(self, renderer):
        Visualizer.__init__(self)

        assert isinstance(renderer, vtk.vtkRenderer)
        self.ren = renderer

        # -------- add the beam ----
        # geometry
        self.beam = vtk.vtkCubeSource()
        self.beam.SetXLength(st.visBeamLength)
        self.beam.SetYLength(st.visBeamWidth)
        self.beam.SetZLength(st.visBeamDepth)

        # mapper
        self.beamMapper = vtk.vtkPolyDataMapper()
        self.beamMapper.SetInputConnection(self.beam.GetOutputPort())

        # actor
        self.beamActor = vtk.vtkLODActor()
        self.beamActor.SetMapper(self.beamMapper)

        # make it look nice
        self.beamProp = self.beamActor.GetProperty()
        self.beamProp.SetColor(101 / 255, 123 / 255, 131 / 255)

        self.ren.AddActor(self.beamActor)

        # -------- add the ball ----
        # geometry
        self.ball = vtk.vtkSphereSource()
        self.ball.SetRadius(st.visR)
        self.ball.SetThetaResolution(20)
        self.ball.SetPhiResolution(20)

        # mapper
        self.ballMapper = vtk.vtkPolyDataMapper()
        self.ballMapper.SetInputConnection(self.ball.GetOutputPort())

        # actor
        self.ballActor = vtk.vtkLODActor()
        self.ballActor.SetMapper(self.ballMapper)

        # make it look nice
        self.ballProp = self.ballActor.GetProperty()
        self.ballProp.SetColor(255 / 255, 255 / 255, 0)
        self.ballProp.SetAmbient(0.2)
        self.ballProp.SetDiffuse(0.8)
        self.ballProp.SetSpecular(0.5)
        self.ballProp.SetSpecularPower(0.5)

        self.ren.AddActor(self.ballActor)

        # add background
        self.ren.GradientBackgroundOn()
        self.ren.SetBackground(228 / 255, 232 / 255, 213 / 255)
        self.ren.SetBackground2(38 / 255, 139 / 255, 210 / 255)

        # get everybody into the frame
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().Zoom(1.7)
Esempio n. 2
0
    def __init__(self, renderer):
        Visualizer.__init__(self)

        assert isinstance(renderer, vtk.vtkRenderer)
        self.ren = renderer
    
        # -------- add the beam ----
        # geometry
        self.beam = vtk.vtkCubeSource()
        self.beam.SetXLength(st.visBeamLength)
        self.beam.SetYLength(st.visBeamWidth)
        self.beam.SetZLength(st.visBeamDepth)

        # mapper
        self.beamMapper = vtk.vtkPolyDataMapper()
        self.beamMapper.SetInputConnection(self.beam.GetOutputPort())

        # actor
        self.beamActor = vtk.vtkLODActor()
        self.beamActor.SetMapper(self.beamMapper)

        # make it look nice
        self.beamProp = self.beamActor.GetProperty()
        self.beamProp.SetColor(101 / 255, 123 / 255, 131 / 255)

        self.ren.AddActor(self.beamActor)

        # -------- add the ball ----
        # geometry
        self.ball = vtk.vtkSphereSource()
        self.ball.SetRadius(st.visR)
        self.ball.SetThetaResolution(20)
        self.ball.SetPhiResolution(20)

        # mapper
        self.ballMapper = vtk.vtkPolyDataMapper()
        self.ballMapper.SetInputConnection(self.ball.GetOutputPort())

        # actor
        self.ballActor = vtk.vtkLODActor()
        self.ballActor.SetMapper(self.ballMapper)

        # make it look nice
        self.ballProp = self.ballActor.GetProperty()
        self.ballProp.SetColor(255 / 255, 255 / 255, 0)
        self.ballProp.SetAmbient(0.2)
        self.ballProp.SetDiffuse(0.8)
        self.ballProp.SetSpecular(0.5)
        self.ballProp.SetSpecularPower(0.5)

        self.ren.AddActor(self.ballActor)

        # add background
        self.ren.GradientBackgroundOn()
        self.ren.SetBackground(228 / 255, 232 / 255, 213 / 255)
        self.ren.SetBackground2(38 / 255, 139 / 255, 210 / 255)

        # get everybody into the frame
        self.ren.ResetCamera()
        self.ren.GetActiveCamera().Zoom(1.7)
Esempio n. 3
0
    def __init__(self, inputs=None):
        if inputs is None:
            inputs = {
                'magnify' : 1,
                'debug' : False,
                'console' : True,
                'is_groups' : False,
            }
        #GuiCommon.__init__(self, inputs=inputs)

        res_widget = MockResWidget()
        kwds = {
            'inputs' : inputs,
            'res_widget' : res_widget
        }
        #GuiAttributes.__init__(self, **kwds)
        GuiCommon.__init__(self, **kwds)
        self.res_widget = res_widget
        self.vtk_interactor = VTKInteractor()
        self.debug = False
        self._form = []
        self.result_cases = OrderedDict()
        #self.geometry_actors = {
            #'main' : vtkActor(),
        #}
        self.main_grid_mappers = {'main' : GridMapper()}
        self.grid = vtk.vtkUnstructuredGrid()
        #self.scalarBar = ScalarBar()
        self.scalar_bar = ScalarBar()
        self.alt_geometry_actor = ScalarBar()
        self.alt_grids = {
            'main' : self.grid,
        }
        self.main_geometry_actors = {
            'main' :  vtkActor(),
        }

        self.glyph_source = ArrowSource()
        self.glyphs = Glyph3D()
        self.glyph_mapper = PolyDataMapper()
        self.arrow_actor = vtkLODActor()
        self.arrow_actor_centroid = vtkLODActor()

        #self.geometry_properties = {
            #'main' : None,
            #'caero' : None,
            #'caero_sub' : None,
        #}
        #self._add_alt_actors = _add_alt_actors

        level = 'debug' if self.debug else 'info'
        self.log = get_logger(log=None, level=level)
        self.rend = vtkRenderer()

        self.text_actors[0] = vtkTextActor()
        self.text_actors[1] = vtkTextActor()
        self.text_actors[2] = vtkTextActor()
        self.text_actors[3] = vtkTextActor()
        self.format_class_map = CLASS_MAP
Esempio n. 4
0
def create_highlighted_actor(gui,
                             ugrid,
                             representation='wire',
                             add_actor=True):
    """creates a highlighted actor given a vtkUnstructuredGrid"""
    actor = vtk.vtkLODActor()
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputData(ugrid)
    # don't use a single color; makes setting prop values work
    mapper.ScalarVisibilityOff()
    actor.SetMapper(mapper)

    settings = gui.settings
    prop = actor.GetProperty()
    prop.SetColor(settings.highlight_color)
    prop.SetOpacity(settings.highlight_opacity)
    if representation == 'surface':
        pass
    elif representation == 'points':
        prop.SetRepresentationToPoints()
        prop.SetPointSize(settings.highlight_point_size)
    elif representation == 'wire':
        prop.SetRepresentationToWireframe()
        prop.SetLineWidth(settings.highlight_line_thickness)
    else:
        raise NotImplementedError(
            'representation=%r and must be [surface, points, wire]' %
            (representation))

    if add_actor:
        gui.rend.AddActor(actor)
    return actor
Esempio n. 5
0
    def LerSTL(self, path):
        mesh = vtk.vtkSTLReader()
        mesh.SetFileName(path)
        mesh.Update()

        #self.pd  = mesh.GetOutput()
        self.polydata = mesh.GetOutput()

        normals = vtk.vtkPolyDataNormals()
        #normals.SetInput(polydata)
        normals.SetInputData(mesh.GetOutput())
        normals.ComputeCellNormalsOn()
        normals.Update()

        #mudanças para aumentar a normal

        self.vertices = pontos(normals.GetOutput())
        self.normalsp = get_normals(normals.GetOutput())

        stlMapper = vtk.vtkPolyDataMapper()
        stlMapper.SetInputConnection(normals.GetOutputPort())

        stlActor = vtk.vtkLODActor()
        stlActor.SetMapper(stlMapper)

        self.renderer.AddActor(stlActor)
        self.Interactor.Render()
Esempio n. 6
0
    def surface_renderer(img):
        # get iso surface as polydata
        marcher = vtk.vtkMarchingCubes()
        marcher.SetInputData(img)
        marcher.SetValue(0, 255)
        marcher.ComputeNormalsOn()
        marcher.Update()

        # mapper-actor-render-renderwindow sequence
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(marcher.GetOutput())
        mapper.ScalarVisibilityOff()

        actor = vtk.vtkLODActor()
        actor.SetMapper(mapper)
        actor.SetNumberOfCloudPoints(1000000)
        actor.GetProperty().SetColor(1.6, 0.0, 2)
        actor.GetProperty().SetOpacity(0.5)

        render = vtk.vtkRenderer()
        render.AddActor(actor)
        render.SetBackground(0.0, 0.0, 0.0)

        window = vtk.vtkRenderWindow()
        window.AddRenderer(render)
        window.PolygonSmoothingOn()
        window.SetSize(500, 500)

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

        iren.Initialize()
        window.Render()
        iren.Start()
Esempio n. 7
0
def LoadModel(filename):

    v, f = loadObj(filename)
    mapper = GetFaceMapper(v, f)
    actor = vtk.vtkLODActor()
    actor.SetMapper(mapper)
    return actor  # represents an entity in a rendered scene
Esempio n. 8
0
def getParticleActor(ptcldata, colour, opacity):

    # Set particle size and angular resolution
    particles = vtk.vtkSphereSource()
    particles.SetThetaResolution(options.particleresolution)
    particles.SetPhiResolution(options.particleresolution)
    if (ellipsoids):
        particles.SetRadius(1.0)
    else:
        particles.SetRadius(options.particleradius)

    # Different glyphs for spheres and ellipsoids
    if (ellipsoids):
        ptclGlyph = vtk.vtkTensorGlyph()
        ptclGlyph.ExtractEigenvaluesOff()
        if (not particlecolourbydata): ptclGlyph.ColorGlyphsOff()
    else:
        ptclGlyph = vtk.vtkGlyph3D()
    ptclGlyph.SetInput(ptcldata)
    ptclGlyph.SetSource(particles.GetOutput())

    # Mapper
    ptclMapper = vtk.vtkPolyDataMapper()
    ptclMapper.SetInput(ptclGlyph.GetOutput())
    ptclMapper.GlobalImmediateModeRenderingOn()

    # Actor
    ptclActor = vtk.vtkLODActor()
    ptclActor.SetMapper(ptclMapper)
    ptclActor.GetProperty().SetColor(colour)
    ptclActor.GetProperty().SetOpacity(opacity)

    # Add to global renderer
    return ptclActor
Esempio n. 9
0
    def init_spheres(self):
        spheres = vtk.vtkSphereSource()
        spheres.SetRadius(self.params.r)
        spheres.SetThetaResolution(32)
        spheres.SetPhiResolution(32)

        spheredata = self.readpoints()

        self.sphereGlyph = vtk.vtkGlyph3D()
        self.sphereGlyph.SetSource(spheres.GetOutput())
        self.sphereGlyph.SetInput(spheredata)

        # Mapping of sphere data and also adding actors for rendering the spheres.Here you can also chnage the color of shere changing the parameters into SetColor. You can put any values and observe changes but (0,0,0) is used for black and (1,1,1) is for white.

        sphereMapper = vtk.vtkPolyDataMapper()
        sphereMapper.SetInput(self.sphereGlyph.GetOutput())
        sphereMapper.GlobalImmediateModeRenderingOn()
        self.sphereActor = vtk.vtkLODActor()
        self.sphereActor.SetMapper(sphereMapper)
        self.sphereActor.GetProperty().SetColor(self.params.spherecolour[0],
                                                self.params.spherecolour[1],
                                                self.params.spherecolour[2])
        self.sphereActor.GetProperty().SetOpacity(1)

        self.ren.AddActor(self.sphereActor)
Esempio n. 10
0
def run_vtk(hdf5_filename: str, scale: float):
    #alg = HDF5Source()
    alg = H5NastranReader()
    alg.SetFileName(hdf5_filename)

    #cf = vtk.vtkContourFilter()
    #cf.SetInputConnection(alg.GetOutputPort())
    #cf.SetValue(0, 200)
    model, ugrid, root, alt_grids = get_nastran_ugrid(hdf5_filename)
    ugrid = alt_grids['main']

    warp = vtk.vtkWarpVector()
    warp.SetScaleFactor(scale)
    warp.SetInputData(ugrid)
    warp.Update()

    #warp = ugrid
    grid_mapper = vtk.vtkDataSetMapper()
    if 0:
        grid_mapper.SetInputData(ugrid)
    else:
        grid_mapper.SetInputData(warp.GetOutput())

    #grid_mapper = vtk.vtkPolyDataMapper()
    #grid_mapper.SetInputConnection(ugrid.GetOutputPort())

    actor = vtk.vtkLODActor()
    actor.SetMapper(grid_mapper)

    add_actor_to_renderer(actor)
    print('go')
Esempio n. 11
0
	def InitVTKMethods(self):
		"""Initializes the VTK methods to be used."""
		self.colortable=ColorTableSource()
		self._plane=vtkPlane()
		self._cutter=vtkCutter()
		self._mapper=vtkDataSetMapper()
		self.actor=vtkLODActor()
Esempio n. 12
0
File: app.py Progetto: jcdinis/POMES
    def LerSTL(self, path):
        mesh= vtk.vtkSTLReader()
        mesh.SetFileName(path)
        mesh.Update()

        #self.pd  = mesh.GetOutput()
        self.polydata  = mesh.GetOutput()

        normals = vtk.vtkPolyDataNormals()
        #normals.SetInput(polydata)
        normals.SetInputData(mesh.GetOutput())
        normals.ComputeCellNormalsOn()
        normals.Update()

        #mudanças para aumentar a normal
        

        self.vertices =pontos(normals.GetOutput())
        self.normalsp = get_normals(normals.GetOutput())

        

        stlMapper = vtk.vtkPolyDataMapper()
        stlMapper.SetInputConnection(normals.GetOutputPort())
        
        stlActor = vtk.vtkLODActor()
        stlActor.SetMapper(stlMapper)


        self.renderer.AddActor(stlActor)
        self.Interactor.Render()
Esempio n. 13
0
 def InitVTKMethods(self):
     """Initializes the VTK methods to be used."""
     self.colortable = ColorTableSource()
     self._plane = vtkPlane()
     self._cutter = vtkCutter()
     self._mapper = vtkDataSetMapper()
     self.actor = vtkLODActor()
Esempio n. 14
0
    def build_glyph(self):
        """builds the glyph actor"""
        glyph_source, glyphs, glyph_mapper, arrow_actor = build_glyph(
            self.grid)
        self.rend.AddActor(arrow_actor)

        self.glyph_source = glyph_source
        self.glyphs = glyphs
        self.glyph_mapper = glyph_mapper
        self.arrow_actor = arrow_actor
        #-----------------------------------------
        glyphs_centroid = vtk.vtkGlyph3D()
        glyphs_centroid.SetVectorModeToUseVector()
        glyphs_centroid.SetScaleModeToScaleByVector()
        glyphs_centroid.SetColorModeToColorByScale()
        glyphs_centroid.ScalingOn()
        glyphs_centroid.ClampingOn()
        glyphs_centroid.SetSourceConnection(glyph_source.GetOutputPort())

        glyph_mapper_centroid = vtk.vtkPolyDataMapper()
        glyph_mapper_centroid.SetInputConnection(
            glyphs_centroid.GetOutputPort())
        glyph_mapper_centroid.ScalarVisibilityOff()

        arrow_actor_centroid = vtk.vtkLODActor()
        arrow_actor_centroid.SetMapper(glyph_mapper_centroid)

        self.glyphs_centroid = glyphs_centroid
        self.glyph_mapper_centroid = glyph_mapper_centroid
        self.arrow_actor_centroid = arrow_actor_centroid
Esempio n. 15
0
 def __LoadSTL(self, filename):
     reader = vtk.vtkSTLReader()
     reader.SetFileName(filename)
     mapper = vtk.vtkPolyDataMapper(
     )  # maps polygonal data to graphics primitives
     mapper.SetInputConnection(reader.GetOutputPort())
     actor = vtk.vtkLODActor()
     actor.SetMapper(mapper)
     return actor  # represents an entity in a rendered scene
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        self.init = False
        VisualizationModule.__init__(self, parent, visualizer, numberOfInputs=(2, 2), **kws)
        # self.name = "Surface Rendering"
        self.normals = vtk.vtkPolyDataNormals()
        self.smooth = None
        self.volumeModule = None
        self.scalarRange = (0, 255)
        for i in range(1, 3):
            self.setInputChannel(i, i)

        self.eventDesc = "Rendering iso-surface"
        self.decimate = vtk.vtkDecimatePro()
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper2 = vtk.vtkPolyDataMapper()

        self.contour = vtk.vtkMarchingCubes()
        self.contour2 = vtk.vtkDiscreteMarchingCubes()

        self.descs = {
            "Normals": "Smooth surface with normals",
            "FeatureAngle": "Feature angle of normals\n",
            "Simplify": "Simplify surface",
            "PreserveTopology": "Preserve topology",
            "Transparency": "Surface transparency",
            "Distance": "Distance to consider inside",
            "MarkColor": "Mark in/outside objects with colors",
        }

        self.actor = self.lodActor = vtk.vtkLODActor()
        self.lodActor.SetMapper(self.mapper)
        self.lodActor.SetNumberOfCloudPoints(10000)

        self.actor2 = vtk.vtkLODActor()
        self.actor2.SetMapper(self.mapper2)
        self.actor2.SetNumberOfCloudPoints(10000)
        self.renderer = self.parent.getRenderer()
        self.renderer.AddActor(self.lodActor)
        self.renderer.AddActor(self.actor2)

        lib.messenger.connect(None, "highlight_object", self.onHighlightObject)
Esempio n. 17
0
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""
		self.init = False
		VisualizationModule.__init__(self, parent, visualizer, numberOfInputs = (2,2), **kws)   
		#self.name = "Surface Rendering"
		self.normals = vtk.vtkPolyDataNormals()
		self.smooth = None
		self.volumeModule = None
		self.scalarRange = (0, 255)
		for i in range(1, 3):
			self.setInputChannel(i, i)
			
		self.eventDesc = "Rendering iso-surface"
		self.decimate = vtk.vtkDecimatePro()
		self.mapper = vtk.vtkPolyDataMapper()
		self.mapper2 = vtk.vtkPolyDataMapper()
		
		self.contour = vtk.vtkMarchingCubes()
		self.contour2 = vtk.vtkDiscreteMarchingCubes()
		
		self.descs = {
			"Normals": "Smooth surface with normals", "FeatureAngle": "Feature angle of normals\n",
			"Simplify": "Simplify surface", "PreserveTopology": "Preserve topology",
			"Transparency": "Surface transparency","Distance":"Distance to consider inside",
			"MarkColor":"Mark in/outside objects with colors"
			}
		
		self.actor = self.lodActor = vtk.vtkLODActor()
		self.lodActor.SetMapper(self.mapper)
		self.lodActor.SetNumberOfCloudPoints(10000)
		
		self.actor2 = vtk.vtkLODActor()
		self.actor2.SetMapper(self.mapper2)
		self.actor2.SetNumberOfCloudPoints(10000)
		self.renderer = self.parent.getRenderer()
		self.renderer.AddActor(self.lodActor)
		self.renderer.AddActor(self.actor2)
		
		lib.messenger.connect(None, "highlight_object", self.onHighlightObject)
Esempio n. 18
0
File: Main.py Progetto: cliburn/flow
    def __init__(self, parent=None, id=-1,
                 pos=wx.DefaultPosition,
                 title="3D Density"):
        VizFrame.__init__(self, parent, id, pos, title)
        self.widget = wxVTKRenderWindowInteractor(self,-1)
        style = vtk.vtkInteractorStyleTrackballCamera()
        self.widget.SetInteractorStyle(style)

        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.1, 0.7)
        self.widget.GetRenderWindow().AddRenderer(self.ren)


        self.data = None
        self.colors = None
        
        # layout the frame
        self.box = wx.BoxSizer(wx.HORIZONTAL)
        self.leftPanel = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.box)
        self.box.Add(self.leftPanel,0, wx.EXPAND)
        self.box.Add(self.widget,1,wx.EXPAND)
        self.Layout()

        self.MenuBar = wx.MenuBar()
        self.FileMenu = wx.Menu()
        self.GateMenu = wx.Menu()
        self.MenuBar.Append(self.FileMenu, "File")
        self.MenuBar.Append(self.GateMenu, "Gating")
        self.SetMenuBar(self.MenuBar)
        export = self.FileMenu.Append(-1, "Export graphics")
        self.Bind(wx.EVT_MENU, self.OnExport, export)
        self.colorGate = self.GateMenu.Append(-1, "Gate on visible colors only")
        self.Bind(wx.EVT_MENU, self.GateByColor, self.colorGate)
        self.colorGate.Enable(False)
        gate = self.GateMenu.Append(-1, "Capture gated events")
        self.boxAddMenuItem = self.GateMenu.Append(-1, "Add box gate")
        self.GateMenu.AppendSeparator()
        self.boxes = []
        self.Bind(wx.EVT_MENU, self.OnBox, self.boxAddMenuItem)
        
        self.Bind(wx.EVT_MENU, self.Gate, gate)

        self.selectActor = vtk.vtkLODActor()
        self.planes = {} #vtk.vtkPlanes()
        self.clipper = vtk.vtkClipPolyData()
        
        self.boxCount = 1
        self.boxIds = {}

        self.Show()
        self.SendSizeEvent()
Esempio n. 19
0
def isoFile(filename):

    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(filename)
    reader.Update()

    iso = vtk.vtkMarchingCubes()
    iso.SetInput(reader.GetOutput())
    iso.SetValue(0, 0.4)
    poly_map = vtk.vtkPolyDataMapper()
    poly_map.SetInput(iso.GetOutput())

    isoActor = vtk.vtkActor()
    isoActor.SetMapper(poly_map)

    ren.SetBackground(1, 1, 1)

    elevation = vtk.vtkElevationFilter()
    elevation.SetInputConnection(iso.GetOutputPort())
    elevation.ReleaseDataFlagOn()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInput(elevation.GetPolyDataOutput())
    normals.SetFeatureAngle(60)
    normals.ConsistencyOff()
    normals.SplittingOff()
    normals.ReleaseDataFlagOn()

    demMapper = vtk.vtkPolyDataMapper()
    demMapper.SetInputConnection(normals.GetOutputPort())
    demMapper.ImmediateModeRenderingOn()

    demActor = vtk.vtkLODActor()
    demActor.SetMapper(demMapper)
    #ren.AddActor(demActor)

    ren.AddActor(isoActor)

    cam1 = ren.GetActiveCamera()
    cam1.SetViewUp(0, 0, 1)
    cam1.SetFocalPoint(reader.GetOutput().GetCenter())
    cam1.SetPosition(0, 0, 0)

    ren.ResetCamera()
    #Changing Elevation, Azimuth,and Zoom
    elevation = input("Please Enter the Value of Elevation:")
    azimuth = input("Please Enter the Value of Azimuth:")
    zoom = input("Please Enter the Value of Zoom:")

    cam1.Elevation(elevation)
    cam1.Azimuth(azimuth)
    cam1.Zoom(zoom)
Esempio n. 20
0
    def _reset_model(self, name):
        """resets the grids; sets up alt_grids"""
        if hasattr(self, 'main_grids') and name not in self.main_grids:
            grid = vtk.vtkUnstructuredGrid()
            grid_mapper = vtk.vtkDataSetMapper()
            grid_mapper.SetInputData(grid)

            geom_actor = vtk.vtkLODActor()
            geom_actor.DragableOff()
            geom_actor.SetMapper(grid_mapper)
            self.rend.AddActor(geom_actor)

            self.grid = grid
            self.grid_mapper = grid_mapper
            self.geom_actor = geom_actor
            self.grid.Modified()

            # link the current "main" to the scalar bar
            scalar_range = self.grid_selected.GetScalarRange()
            self.grid_mapper.ScalarVisibilityOn()
            self.grid_mapper.SetScalarRange(scalar_range)
            self.grid_mapper.SetLookupTable(self.color_function)

            self.edge_actor = vtk.vtkLODActor()
            self.edge_actor.DragableOff()
            self.edge_mapper = vtk.vtkPolyDataMapper()

            # create the edges
            self.get_edges()
        else:
            self.grid.Reset()
            self.grid.Modified()

        # reset alt grids
        alt_names = self.alt_grids.keys()
        for alt_name in alt_names:
            self.alt_grids[alt_name].Reset()
            self.alt_grids[alt_name].Modified()
Esempio n. 21
0
 def __init__(self, actorlist, volumelist):
     self.render = vtk.vtkRenderer()
     self.renWindow = vtk.vtkRenderWindow()
     self.renWindow.AddRenderer(self.render)
     self.interactor = vtk.vtkRenderWindowInteractor()
     self.interactor.SetRenderWindow(self.renWindow)
     self.actorstoadd = actorlist
     self.volumestoadd = volumelist
     self.t = vtk.vtkTransform()
     self.box = vtk.vtkBoxWidget()
     self.planes = vtk.vtkPlanes()
     self.clipper = vtk.vtkClipPolyData()
     self.selectMapper = vtk.vtkPolyDataMapper()
     self.selectActor = vtk.vtkLODActor()
Esempio n. 22
0
    def addGrid(self, grid):
        nx, ny, nz = grid.shape[1:]

        self.display.append(True)

        self.grids.append(vtk.vtkStructuredGrid())

        self.grids[-1].SetExtent(0, nz-1, 0, ny-1, 0, nx-1)
        p = vtk.vtkPoints()

        shp = grid.shape
        grid.shape = (3, nx*ny*nz)
        p.SetData(vtknp.numpy_to_vtk(np.ascontiguousarray(grid.T), deep=True, array_type=vtknp.get_vtk_array_type(grid.dtype)))
        grid.shape = shp
        self.grids[-1].SetPoints(p)

        #Couleur
        color = np.random.rand(3)
        #Create a vtkOutlineFilter to draw the bounding box of the data set.
        ol = vtk.vtkOutlineFilter()
        if (vtk.vtkVersion().GetVTKMajorVersion()>=6):
          ol.SetInputData(self.grids[-1])
        else:
          ol.SetInput(self.grids[-1])      
        olm = vtk.vtkPolyDataMapper()
        olm.SetInputConnection(ol.GetOutputPort())
        ola = vtk.vtkActor()
        ola.SetMapper(olm)
        ola.GetProperty().SetColor(color)

        s=vtk.vtkShrinkFilter()
        if (vtk.vtkVersion().GetVTKMajorVersion()>=6):
          s.SetInputData(self.grids[-1])
        else:
          s.SetInput(self.grids[-1])      
        s.SetShrinkFactor(0.8)
        #
        mapper = vtk.vtkDataSetMapper()
        #map.SetInputData(data)
        mapper.SetInputConnection(s.GetOutputPort())
        act = vtk.vtkLODActor()
        act.SetMapper(mapper)
        #act.GetProperty().SetRepresentationToWireframe()
        #act.GetProperty().SetRepresentationToPoints()	
        act.GetProperty().SetColor(color)
        act.GetProperty().SetEdgeColor(color)
        act.GetProperty().EdgeVisibilityOff()	
        self.actors.append(act)
        self.setBounds()
        self.ren.SetActiveCamera(self.cam)
Esempio n. 23
0
    def appendContextActor(self, name, filename, color, customProps = dict()):
        """
        Add a context actor (actor with a name) loaded from a file to the
        scene.

        @param name: the name of the actor
        @type name: str

        @param filename: path to a file containing the actor
        @type filename: str

        @param color: the requested colour of the actor
        @type color: (float, float, float)

        @param customProps: C{dict}
        @type  customProps: dictionary storing additional properties to be applied to
                       the actor (opacity, diffuse color, etc.)

        @note: the method DOES NOT trigger the scene to render
        """

        # If if actor with given name already exists,
        # remove it
        if self.hasContextActor(name):
            self.removeContextActor(name)

        # Read the vtkPolyData file from the disk
        # and load it into render window trough the mapper
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(filename)

        mapMesh = vtk.vtkPolyDataMapper()
        mapMesh.SetInputConnection(reader.GetOutputPort())

        meshActor = vtk.vtkLODActor()
        meshActor.SetMapper(mapMesh)
        meshActor.GetProperty().SetColor(color)

        print customProps
        # Apply additional setting as given by customProps
        for (k,v) in customProps.items():
            # Apply the property depending on its type:
            if v:
                getattr(meshActor.GetProperty(), k)(v)
            else:
                getattr(meshActor.GetProperty(), k)()

        # Create reference for the appended actor
        self.__contextActors[name] = meshActor
        self.renderer.AddActor(meshActor)
Esempio n. 24
0
    def appendContextActor(self, name, filename, color, customProps=dict()):
        """
        Add a context actor (actor with a name) loaded from a file to the
        scene.

        @param name: the name of the actor
        @type name: str

        @param filename: path to a file containing the actor
        @type filename: str

        @param color: the requested colour of the actor
        @type color: (float, float, float)

        @param customProps: C{dict}
        @type  customProps: dictionary storing additional properties to be applied to
                       the actor (opacity, diffuse color, etc.)

        @note: the method DOES NOT trigger the scene to render
        """

        # If if actor with given name already exists,
        # remove it
        if self.hasContextActor(name):
            self.removeContextActor(name)

        # Read the vtkPolyData file from the disk
        # and load it into render window trough the mapper
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(filename)

        mapMesh = vtk.vtkPolyDataMapper()
        mapMesh.SetInputConnection(reader.GetOutputPort())

        meshActor = vtk.vtkLODActor()
        meshActor.SetMapper(mapMesh)
        meshActor.GetProperty().SetColor(color)

        print customProps
        # Apply additional setting as given by customProps
        for (k, v) in customProps.items():
            # Apply the property depending on its type:
            if v:
                getattr(meshActor.GetProperty(), k)(v)
            else:
                getattr(meshActor.GetProperty(), k)()

        # Create reference for the appended actor
        self.__contextActors[name] = meshActor
        self.renderer.AddActor(meshActor)
Esempio n. 25
0
    def lineActor(self,obj):
        """
        Returns an object of type vtkLODActor for rendering within a VTK 
        pipeline
        """
        me  = vtk.vtkPolyData()
        pts = vtk.vtkPoints()
        cts = vtk.vtkCellArray()
            
        for n in range(len(obj.points)):
            pts.InsertPoint(n,obj.points[n][0],
                              obj.points[n][1],
                              obj.points[n][2])
            
        for n in range(1,len(obj.points)):
            cts.InsertNextCell(2)
            cts.InsertCellPoint(n-1)
            cts.InsertCellPoint(n)
              
        me.SetPoints(pts)
        me.SetLines(cts)
                          
        dataMapper = vtk.vtkPolyDataMapper()
        dataMapper.SetInputData(me)

        dataActor =vtk.vtkLODActor()
        dataActor.SetMapper(dataMapper)
        
        if obj.color is not None:
            if np.size(obj.color) == 3:
                dataActor.GetProperty().SetColor(obj.color[0],
                                                 obj.color[1],
                                                 obj.color[2])
            else:
                carray = vtk.vtkUnsignedCharArray()
                carray.SetNumberOfComponents(3)
                carray.SetName("Colors")
                color = (obj.color*255).astype(int)
                for c in color:
                    carray.InsertNextTupleValue(c)
                me.GetCellData().SetScalars(carray)

        if obj.opacity is not None:
            dataActor.GetProperty().SetOpacity(obj.opacity)
            
        if obj.width is not None:
            dataActor.GetProperty().SetLineWidth(obj.width)
            
        return dataActor
Esempio n. 26
0
    def __createMainActor(self):
        """
        If no main actor (C{self.L{__mainActor} == None}) create it from the
        volume C{self.L{__sourceVolume}} (if exists). The colour of main actor
        is given by C{self.L{__mainActorCol}}
        """
        if self.__mainActor == None and self.__sourceVolume != None:
            ct = self.__mainActorCol
            vtksource = self.__finalPipeline.execute(self.vtkMesh)

            self.__mainActor = vtk.vtkLODActor()
            self.__mainActor.SetMapper(vtksource)
            self.__mainActor.GetProperty().SetColor(ct[0], ct[1], ct[2])

            self.renderer.AddActor(self.__mainActor)
Esempio n. 27
0
    def __createMainActor(self):
        """
        If no main actor (C{self.L{__mainActor} == None}) create it from the
        volume C{self.L{__sourceVolume}} (if exists). The colour of main actor
        is given by C{self.L{__mainActorCol}}
        """
        if self.__mainActor == None and self.__sourceVolume != None:
            ct = self.__mainActorCol
            vtksource = self.__finalPipeline.execute(self.vtkMesh)

            self.__mainActor = vtk.vtkLODActor()
            self.__mainActor.SetMapper(vtksource)
            self.__mainActor.GetProperty().SetColor(ct[0],ct[1],ct[2])

            self.renderer.AddActor(self.__mainActor)
Esempio n. 28
0
	def makeVTKLODActor(vtkObj,clipper):
		"""Make LOD vtk Actor"""
		selectMapper = vtk.vtkDataSetMapper()
		selectMapper.SetInputConnection(clipper.GetOutputPort())
		selectMapper.SetScalarVisibility(1)
		selectMapper.SetColorModeToMapScalars()
		selectMapper.SetScalarModeToUseCellData()
		selectMapper.SetScalarRange(clipper.GetInputDataObject(0,0).GetCellData().GetArray(0).GetRange())

		selectActor = vtk.vtkLODActor()
		selectActor.SetMapper(selectMapper)
		selectActor.GetProperty().SetEdgeColor(1,0.5,0)
		selectActor.GetProperty().SetEdgeVisibility(0)
		selectActor.VisibilityOn()
		selectActor.SetScale(1.01, 1.01, 1.01)
		return selectActor
Esempio n. 29
0
 def polyActor(self,obj): 
     """
     Returns an object of type vtkLODActor for rendering within a VTK 
     pipeline
     """
     actor   = vtk.vtkPolyData()
     pts     = vtk.vtkPoints()
     cts     = vtk.vtkCellArray()
         
     for n in range(len(obj.points)):
         pts.InsertPoint(n,obj.points[n,0], 
                           obj.points[n,1],
                           obj.points[n,2])
        
     for n in range(len(obj.connectivity)):
         cts.InsertNextCell(3)
         for node in obj.connectivity[n]:
             cts.InsertCellPoint(node) 
             
     actor.SetPoints(pts)
     actor.SetPolys(cts)
     
     # If the normals of the object are specified (smooth object), this is
     # rendered as such
     if obj.normals is not None:
         nrm = vtk.vtkDoubleArray()
         nrm.SetNumberOfComponents(3)
         nrm.SetNumberOfTuples(len(obj.points))
         for n in range(len(obj.points)):
             nrm.SetTuple(n,obj.normals[n].tolist())
         actor.GetPointData().SetNormals(nrm)
         
     dataMapper = vtk.vtkPolyDataMapper()
     dataMapper.SetInputData(actor)
     
     dataActor =vtk.vtkLODActor()
     dataActor.SetMapper(dataMapper)
     
     if obj.color is not None:
         dataActor.GetProperty().SetColor(obj.color[0],
                                          obj.color[1],
                                          obj.color[2])
     if obj.opacity is not None:
         dataActor.GetProperty().SetOpacity(obj.opacity)
         
     return dataActor
def main():

    # Read in data set.
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName("quadMeshFullc4080.vtp")
    reader.Update()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(reader.GetOutputPort())
    cleaner.Update()

    # Apply tessellation filter.
    tessellation = vtk.vtkProgrammableFilter()
    tessellation.AddInputConnection(cleaner.GetOutputPort())
    tessellation.SetExecuteMethod(
        tessellation_callback(tessellation, 250, 0.008))

    # Set up mapper.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(tessellation.GetOutput())
    mapper.ScalarVisibilityOff()

    # Set up actor.
    actor = vtk.vtkLODActor()
    actor.SetMapper(mapper)

    # Render.
    ren = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(actor)
    ren.SetBackground(0.1, 0.2, 0.4)
    ren_win.SetSize(800, 800)

    # Start event.
    iren.Initialize()
    ren_win.Render()
    iren.Start()
Esempio n. 31
0
def load_isosurface(image):
    iso = vtk.vtkContourFilter()
    # iso = vtk.vtkMarchingCubes()
    iso.SetInputConnection(image)
    iso.ComputeNormalsOn()
    for i in range(8):
        iso.SetValue(i, i * 33.33 + 266.67)
    iso.Update()

    isoMapper = vtk.vtkPolyDataMapper()
    isoMapper.SetInputData(iso.GetOutput())
    isoMapper.ScalarVisibilityOff()

    # Take the isosurface data and create geometry
    actor = vtk.vtkLODActor()
    actor.SetNumberOfCloudPoints(1000000)
    actor.SetMapper(isoMapper)
    actor.SetVisibility(False)
    actor.GetProperty().SetColor(1, 0, 0)
    return actor
Esempio n. 32
0
    def create_vtk_actors(self, create_rend=True):
        """creates the vtk actors used by the GUI"""
        if create_rend:
            self.rend = vtk.vtkRenderer()

        xyz = [0., 0., 0.]
        self.min_max_actors.append(create_annotation(self, 'Min', *xyz))
        self.min_max_actors.append(create_annotation(self, 'Max', *xyz))
        for actor in self.min_max_actors:
            actor.SetVisibility(False)

        # vtk actors
        self.grid = vtk.vtkUnstructuredGrid()

        # edges
        self.edge_actor = vtk.vtkLODActor()
        self.edge_actor.DragableOff()
        self.edge_mapper = vtk.vtkPolyDataMapper()

        self.create_cell_picker()
Esempio n. 33
0
    def initPlaneWidget(self):
        """Sets up vtkImplicitPlaneWidget for plane selection.
		
		Sets also up necessary actor and mapper.
		
		Returns:
			vtk.vtkImplicitPlaneWidget: Widget.
		
		"""

        # Initialize a plane widget
        self.planeWidget = vtk.vtkImplicitPlaneWidget()
        self.planeWidget.SetInteractor(self.iren)
        self.planeWidget.SetPlaceFactor(1.25)
        self.planeWidget.SetInput(self.grid)
        self.planeWidget.PlaceWidget()

        # Callback connection of interaction event
        self.planeWidget.AddObserver("InteractionEvent",
                                     self.StartPlaneCallback)
        self.planeWidget.AddObserver("EndInteractionEvent",
                                     self.EndPlaneCallback)

        # Mapper
        self.selectMapper = vtk.vtkDataSetMapper()
        self.selectMapper.SetInput(self.grid)

        # Actor
        self.selectActor = vtk.vtkLODActor()
        self.selectActor.SetMapper(self.selectMapper)
        self.selectActor.GetProperty().SetColor(0, 1, 0)
        self.selectActor.VisibilityOff()
        self.selectActor.SetScale(1.01, 1.01, 1.01)

        self.ren.AddActor(self.selectActor)

        # Place widget at right position
        self.planeWidget.SetNormal(0, 0, 1)
        self.planeWidget.SetOrigin(self.grid.GetCenter())

        return self.planeWidget
Esempio n. 34
0
	def initPlaneWidget(self):
		
		"""Sets up vtkImplicitPlaneWidget for plane selection.
		
		Sets also up necessary actor and mapper.
		
		Returns:
			vtk.vtkImplicitPlaneWidget: Widget.
		
		"""
		
		# Initialize a plane widget
		self.planeWidget = vtk.vtkImplicitPlaneWidget()
		self.planeWidget.SetInteractor(self.iren)
		self.planeWidget.SetPlaceFactor(1.25)
		self.planeWidget.SetInput(self.grid)
		self.planeWidget.PlaceWidget()
		
		# Callback connection of interaction event
		self.planeWidget.AddObserver("InteractionEvent", self.StartPlaneCallback)
		self.planeWidget.AddObserver("EndInteractionEvent",self.EndPlaneCallback)
		
		# Mapper
		self.selectMapper = vtk.vtkDataSetMapper()
		self.selectMapper.SetInput(self.grid)
		
		# Actor
		self.selectActor = vtk.vtkLODActor()
		self.selectActor.SetMapper(self.selectMapper)
		self.selectActor.GetProperty().SetColor(0, 1, 0)
		self.selectActor.VisibilityOff()
		self.selectActor.SetScale(1.01, 1.01, 1.01)
		
		self.ren.AddActor(self.selectActor)
		
		# Place widget at right position
		self.planeWidget.SetNormal(0,0,1)
		self.planeWidget.SetOrigin(self.grid.GetCenter())
		
		
		return self.planeWidget
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        VisualizationModule.__init__(self, parent, visualizer, **kws)
        # self.name = "Surface Rendering"
        # for i in range(1, 3):
        # 	self.setInputChannel(i, i)
        self.normals = vtk.vtkPolyDataNormals()
        self.smooth = None
        self.volumeModule = None
        self.scalarRange = (0, 255)

        self.eventDesc = "Rendering iso-surface"
        self.decimate = vtk.vtkDecimatePro()
        self.setMethod(1)
        self.init = 0
        self.mapper = vtk.vtkPolyDataMapper()

        self.descs = {
            "Method": "Surface rendering method",
            "Gaussian": "Smooth surface with gaussian smoothing",
            "Normals": "Smooth surface with normals",
            "FeatureAngle": "Feature angle of normals\n",
            "Simplify": "Simplify surface",
            "PreserveTopology": "Preserve topology",
            "IsoValue": "Iso value",
            "SurfaceRangeBegin": "Generate surfaces in range:\n",
            "SurfaceAmnt": "Number of surfaces",
            "Transparency": "Surface transparency",
            "MultipleSurfaces": "Visualize multiple surfaces",
            "SolidColor": "Color surface with max. intensity",
        }

        self.actor = self.lodActor = vtk.vtkLODActor()
        self.lodActor.SetMapper(self.mapper)
        self.lodActor.SetNumberOfCloudPoints(10000)
        self.renderer = self.parent.getRenderer()
        self.renderer.AddActor(self.lodActor)
        # self.updateRendering()
        self.filterDesc = "Create and visualize iso-surface"
Esempio n. 36
0
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        VisualizationModule.__init__(self, parent, visualizer, **kws)
        #self.name = "Surface Rendering"
        #for i in range(1, 3):
        #	self.setInputChannel(i, i)
        self.normals = vtk.vtkPolyDataNormals()
        self.smooth = None
        self.volumeModule = None
        self.scalarRange = (0, 255)

        self.eventDesc = "Rendering iso-surface"
        self.decimate = vtk.vtkDecimatePro()
        self.setMethod(1)
        self.init = 0
        self.mapper = vtk.vtkPolyDataMapper()

        self.descs = {
            "Method": "Surface rendering method",
            "Gaussian": "Smooth surface with gaussian smoothing",
            "Normals": "Smooth surface with normals",
            "FeatureAngle": "Feature angle of normals\n",
            "Simplify": "Simplify surface",
            "PreserveTopology": "Preserve topology",
            "IsoValue": "Iso value",
            "SurfaceRangeBegin": "Generate surfaces in range:\n",
            "SurfaceAmnt": "Number of surfaces",
            "Transparency": "Surface transparency",
            "MultipleSurfaces": "Visualize multiple surfaces",
            "SolidColor": "Color surface with max. intensity"
        }

        self.actor = self.lodActor = vtk.vtkLODActor()
        self.lodActor.SetMapper(self.mapper)
        self.lodActor.SetNumberOfCloudPoints(10000)
        self.renderer = self.parent.getRenderer()
        self.renderer.AddActor(self.lodActor)
        #self.updateRendering()
        self.filterDesc = "Create and visualize iso-surface"
Esempio n. 37
0
    def LerSTLProtese(self, path):
        mesh = vtk.vtkSTLReader()
        mesh.SetFileName(path)
        mesh.Update()

        stlMapper = vtk.vtkPolyDataMapper()
        stlMapper.SetInputConnection(mesh.GetOutputPort())

        stlActor = vtk.vtkLODActor()
        stlActor.SetMapper(stlMapper)

        self.simp.Enable(True)
        if self.simpo.IsEnabled():
            self.simpP.Enable(True)

        self.RightPanel.visaofrontal.AdicionaAtor(stlActor)
        self.RightPanel.visaolateral.AdicionaAtor(stlActor)
        self.RightPanel.visaotop.AdicionaAtor(stlActor)
        self.RightPanel.visaoControl.AdicionaAtor(stlActor)
        self.ListaActores.append(stlActor)
        self.ListaProteses.append(stlActor)
Esempio n. 38
0
def show(vtkObject, w=512, h=512):
    """
    Show result of pipeline.

    :param vtkObject: anything VTK
    :param w: window width
    :param h: window height

    :type vtkObject: None
    :type w: int
    :type h: int

    >>> image_data = create_image_data_from_array(surf)
    >>> cubes = filter_marching_cubes(image_data)
    >>> show(cubes)
    """
    mapper = vtk.vtkPolyDataMapper()

    try:
        mapper.SetInputConnection(vtkObject.GetOutputPort())
    except AttributeError:
        mapper.SetInput(vtkObject)

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

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

    window = vtk.vtkRenderWindow()
    window.AddRenderer(renderer)
    window.SetSize(w, h)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(window)

    interactor.Initialize()
    window.Render()
    interactor.Start()
Esempio n. 39
0
def build_glyph(grid):
    """builds the glyph actor"""
    glyphs = vtk.vtkGlyph3D()
    #if filter_small_forces:
    #glyphs.SetRange(0.5, 1.)

    glyphs.SetVectorModeToUseVector()
    #apply_color_to_glyph = False
    #if apply_color_to_glyph:
    #glyphs.SetScaleModeToScaleByScalar()
    glyphs.SetScaleModeToScaleByVector()
    glyphs.SetColorModeToColorByScale()
    #glyphs.SetColorModeToColorByScalar()  # super tiny
    #glyphs.SetColorModeToColorByVector()  # super tiny

    glyphs.ScalingOn()
    glyphs.ClampingOn()
    #glyphs.Update()

    glyph_source = vtk.vtkArrowSource()
    #glyph_source.InvertOn()  # flip this arrow direction
    glyphs.SetInputData(grid)

    glyphs.SetSourceConnection(glyph_source.GetOutputPort())
    #glyphs.SetScaleModeToDataScalingOff()
    #glyphs.SetScaleFactor(10.0)  # bwb
    #glyphs.SetScaleFactor(1.0)  # solid-bending
    glyph_mapper = vtk.vtkPolyDataMapper()
    glyph_mapper.SetInputConnection(glyphs.GetOutputPort())
    glyph_mapper.ScalarVisibilityOff()

    arrow_actor = vtk.vtkLODActor()
    arrow_actor.SetMapper(glyph_mapper)

    prop = arrow_actor.GetProperty()
    prop.SetColor(1., 0., 0.)
    #self.grid.GetPointData().SetActiveVectors(None)
    arrow_actor.SetVisibility(False)
    return glyph_source, glyphs, glyph_mapper, arrow_actor
Esempio n. 40
0
def show(vtkObject, w=512, h=512):
    """
    Show result of pipeline.

    :param vtkObject: anything VTK
    :param w: window width
    :param h: window height

    :type vtkObject: None
    :type w: int
    :type h: int

    >>> image_data = create_image_data_from_array(surf)
    >>> cubes = filter_marching_cubes(image_data)
    >>> show(cubes)
    """
    mapper = vtk.vtkPolyDataMapper()

    try:
        mapper.SetInputConnection(vtkObject.GetOutputPort())
    except AttributeError:
        mapper.SetInput(vtkObject)

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

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

    window = vtk.vtkRenderWindow()
    window.AddRenderer(renderer)
    window.SetSize(w, h)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(window)

    interactor.Initialize()
    window.Render()
    interactor.Start()
Esempio n. 41
0
 def __init__(self, dataset=None, name=None, image=None, gui_image=None):
     ####################
     # Public interface #
     ####################
     self.name = name
     
     #####################
     # Private interface #
     #####################
     self._dataset = None
     self._actor = vtkLODActor()
     self._image = None
     self._gui_image = None
     
     self._point_locator = vtkPointLocator()
     self._cell_locator = vtkCellLocator()
     self._point_locator_dirty = True
     self._cell_locator_dirty = True
     
     self._mapper = vtkPolyDataMapper()
     self._clipping_mapper = vtkPolyDataMapper()
     self._inside_out = True
     self._clipping_functions = None
     self._clippers = []
     self._mask_filter = vtkMaskPoints()
     
     ##################
     # Initialization #
     ##################
     self._mask_filter.SetOnRatio(1)
     self._mask_filter.SetOffset(0)
     self._mask_filter.GenerateVerticesOn()
     
     self._actor.SetMapper(self._mapper)
     self._set_dataset(dataset)
     self.color_by_material()
     self._set_image(image)
     self._set_gui_image(image)
Esempio n. 42
0
 def pointsActor(self, obj):
     npts = np.size(obj.points, 0)
      
     vertices = vtk.vtkCellArray()
     ptsource = vtk.vtkPoints()
     
     ptsource.SetNumberOfPoints(npts)
     
     for n,p in enumerate(obj.points):
         ptsource.SetPoint(n,p)
         vertices.InsertNextCell(1)
         vertices.InsertCellPoint(n)
         
     point = vtk.vtkPolyData()
     point.SetPoints(ptsource)
     point.SetVerts(vertices)   
     
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputData(point) 
     
     actor = vtk.vtkLODActor()
     actor.SetMapper(mapper)
     actor.GetProperty().SetPointSize(1)
     return actor
Esempio n. 43
0
# its graphical representation of the data to maintain interactive
# performance.

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

# Create the reader and read a data file.  Connect the mapper and
# actor.
sr = vtk.vtkSTLReader()
sr.SetFileName(VTK_DATA_ROOT + "/Data/42400-IDGH.stl")

stlMapper = vtk.vtkPolyDataMapper()
stlMapper.SetInputConnection(sr.GetOutputPort())

stlActor = vtk.vtkLODActor()
stlActor.SetMapper(stlMapper)

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

# Add the actors to the render; set the background and size
ren.AddActor(stlActor)
ren.SetBackground(0.1, 0.2, 0.4)
renWin.SetSize(500, 500)

# Zoom in closer
Esempio n. 44
0
warp.SetInputConnection(surface.GetOutputPort())
warp.SetScaleFactor(1)
warp.UseNormalOn()
warp.SetNormal(0, 0, 1)

normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(warp.GetOutputPort())
normals.SetFeatureAngle(60)
normals.SplittingOff()

demMapper = vtk.vtkPolyDataMapper()
demMapper.SetInputConnection(normals.GetOutputPort())
demMapper.SetScalarRange(lo, hi)
demMapper.SetLookupTable(lut)

demActor = vtk.vtkLODActor()
demActor.SetMapper(demMapper)

# Create some paths
pts = vtk.vtkPoints()
pts.InsertNextPoint(562669, 5.1198e+006, 1992.77)
pts.InsertNextPoint(562801, 5.11618e+006, 2534.97)
pts.InsertNextPoint(562913, 5.11157e+006, 1911.1)
pts.InsertNextPoint(559849, 5.11083e+006, 1681.34)
pts.InsertNextPoint(562471, 5.11633e+006, 2593.57)
pts.InsertNextPoint(563223, 5.11616e+006, 2598.31)
pts.InsertNextPoint(566579, 5.11127e+006, 1697.83)
pts.InsertNextPoint(569000, 5.11127e+006, 1697.83)

lines = vtk.vtkCellArray()
lines.InsertNextCell(3)
Sphere0.SetStartPhi(0)
Sphere0.SetEndPhi(180)
Glyph0 = vtk.vtkGlyph3D()
Glyph0.SetInputConnection(pdb0.GetOutputPort())
Glyph0.SetOrient(1)
Glyph0.SetColorMode(1)
#Glyph0 ScalingOn
Glyph0.SetScaleMode(2)
Glyph0.SetScaleFactor(.25)
Glyph0.SetSourceConnection(Sphere0.GetOutputPort())
Mapper5 = vtk.vtkPolyDataMapper()
Mapper5.SetInputConnection(Glyph0.GetOutputPort())
Mapper5.UseLookupTableScalarRangeOff()
Mapper5.SetScalarVisibility(1)
Mapper5.SetScalarModeToDefault()
Actor5 = vtk.vtkLODActor()
Actor5.SetMapper(Mapper5)
Actor5.GetProperty().SetRepresentationToSurface()
Actor5.GetProperty().SetInterpolationToGouraud()
Actor5.GetProperty().SetAmbient(0.15)
Actor5.GetProperty().SetDiffuse(0.85)
Actor5.GetProperty().SetSpecular(0.1)
Actor5.GetProperty().SetSpecularPower(100)
Actor5.GetProperty().SetSpecularColor(1,1,1)
Actor5.GetProperty().SetColor(1,1,1)
Actor5.SetNumberOfCloudPoints(30000)
ren1.AddActor(Actor5)
Tuber0 = vtk.vtkTubeFilter()
Tuber0.SetInputConnection(pdb0.GetOutputPort())
Tuber0.SetNumberOfSides(8)
Tuber0.SetCapping(0)
Esempio n. 46
0
glyph.SetInputConnection(sphere.GetOutputPort())
glyph.SetSourceConnection(cone.GetOutputPort())
glyph.SetVectorModeToUseNormal()
glyph.SetScaleModeToScaleByVector()
glyph.SetScaleFactor(0.25)

# The sphere and spikes are appended into a single polydata.
# This just makes things simpler to manage.
apd = vtk.vtkAppendPolyData()
apd.AddInputConnection(glyph.GetOutputPort())
apd.AddInputConnection(sphere.GetOutputPort())

maceMapper = vtk.vtkPolyDataMapper()
maceMapper.SetInputConnection(apd.GetOutputPort())

maceActor = vtk.vtkLODActor()
maceActor.SetMapper(maceMapper)
maceActor.VisibilityOn()

# This portion of the code clips the mace with the vtkPlanes
# implicit function. The clipped region is colored green.
plane = vtk.vtkPlane()
clipper = vtk.vtkClipPolyData()
clipper.SetInputConnection(apd.GetOutputPort())
clipper.SetClipFunction(plane)
clipper.InsideOutOn()

selectMapper = vtk.vtkPolyDataMapper()
selectMapper.SetInputConnection(clipper.GetOutputPort())

selectActor = vtk.vtkLODActor()
Esempio n. 47
0
File: cutLoop.py Progetto: 0004c/VTK
loop = vtk.vtkSelectPolyData()
loop.SetInputConnection(sphere.GetOutputPort())
loop.SetLoop(selectionPoints)
loop.GenerateSelectionScalarsOn()
# negative scalars inside
loop.SetSelectionModeToSmallestRegion()

# clips out positive region
clip = vtk.vtkClipPolyData()
clip.SetInputConnection(loop.GetOutputPort())

clipMapper = vtk.vtkPolyDataMapper()
clipMapper.SetInputConnection(clip.GetOutputPort())

clipActor = vtk.vtkLODActor()
clipActor.SetMapper(clipMapper)

loop2 = vtk.vtkSelectPolyData()
loop2.SetInputConnection(sphere.GetOutputPort())
loop2.SetLoop(selectionPoints)
loop2.SetSelectionModeToSmallestRegion()

selectMapper = vtk.vtkPolyDataMapper()
selectMapper.SetInputConnection(loop2.GetOutputPort())

selectActor = vtk.vtkLODActor()
selectActor.SetMapper(selectMapper)
selectActor.AddPosition(1, 0, 0)
selectActor.GetProperty().SetColor(GetRGBColor('peacock'))
Esempio n. 48
0
bcf.GenerateContourEdgesOn()

# Compute normals to give a better look.
normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(bcf.GetOutputPort())
normals.SetFeatureAngle(60)
normals.ConsistencyOff()
normals.SplittingOff()

demMapper = vtk.vtkPolyDataMapper()
demMapper.SetInputConnection(normals.GetOutputPort())
demMapper.SetScalarRange(0, 10)
demMapper.SetLookupTable(lutLand)
demMapper.SetScalarModeToUseCellData()

demActor = vtk.vtkLODActor()
demActor.SetMapper(demMapper)

## Create contour edges
edgeMapper = vtk.vtkPolyDataMapper()
edgeMapper.SetInput(bcf.GetContourEdgesOutput())
edgeMapper.SetResolveCoincidentTopologyToPolygonOffset()
edgeActor = vtk.vtkActor()
edgeActor.SetMapper(edgeMapper)
edgeActor.GetProperty().SetColor(0, 0, 0)

## Test clipping
# Create the contour bands.
bcf2 = vtk.vtkBandedPolyDataContourFilter()
bcf2.SetInput(warp.GetPolyDataOutput())
bcf2.ClippingOn()
# Here we add a filter that computes surface normals from the geometry.
shrink = vtk.vtkShrinkPolyData()
shrink.SetInputConnection(part.GetOutputPort())
shrink.SetShrinkFactor(0.85)

# The mapper is responsible for pushing the geometry into the graphics
# library. It may also do color mapping, if scalars or other
# attributes are defined.
partMapper = vtk.vtkPolyDataMapper()
partMapper.SetInputConnection(shrink.GetOutputPort())

# The LOD actor is a special type of actor. It will change appearance
# in order to render faster. At the highest resolution, it renders
# ewverything just like an actor. The middle level is a point cloud,
# and the lowest level is a simple bounding box.
partActor = vtk.vtkLODActor()
partActor.SetMapper(partMapper)
partActor.GetProperty().SetColor(light_grey)
partActor.RotateX(30.0)
partActor.RotateY(-45.0)

# Create the graphics structure. The renderer renders into the
# render window. The render window interactor captures mouse events
# and will perform appropriate camera or actor manipulation
# depending on the nature of the events.
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
Esempio n. 50
0
#!/usr/bin/env python

# This example demonstrates the use of 2D text.

import vtk

# Create a sphere source, mapper, and actor
sphere = vtk.vtkSphereSource()

sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereMapper.GlobalImmediateModeRenderingOn()
sphereActor = vtk.vtkLODActor()
sphereActor.SetMapper(sphereMapper)

# Create a scaled text actor. 
# Set the text, font, justification, and properties (bold, italics,
# etc.).
textActor = vtk.vtkTextActor()
textActor.ScaledTextOn()
textActor.SetDisplayPosition(90, 50)
textActor.SetInput("This is a sphere")

# Set coordinates to match the old vtkScaledTextActor default value
textActor.GetPosition2Coordinate().SetCoordinateSystemToNormalizedViewport()
textActor.GetPosition2Coordinate().SetValue(0.6, 0.1)

tprop = textActor.GetTextProperty()
tprop.SetFontSize(18)
tprop.SetFontFamilyToArial()
tprop.SetJustificationToCentered()
ren1 = vtk.vtkRenderer()
ren1.SetBackground(0,0,0)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(300,300)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
facet0 = vtk.vtkFacetReader()
facet0.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/clown.facet")
Mapper5 = vtk.vtkPolyDataMapper()
Mapper5.SetInputConnection(facet0.GetOutputPort())
Mapper5.UseLookupTableScalarRangeOff()
Mapper5.SetScalarVisibility(1)
Mapper5.SetScalarModeToDefault()
Actor5 = vtk.vtkLODActor()
Actor5.SetMapper(Mapper5)
Actor5.GetProperty().SetRepresentationToSurface()
Actor5.GetProperty().SetInterpolationToGouraud()
Actor5.GetProperty().SetAmbient(0.15)
Actor5.GetProperty().SetDiffuse(0.85)
Actor5.GetProperty().SetSpecular(0.1)
Actor5.GetProperty().SetSpecularPower(100)
Actor5.GetProperty().SetSpecularColor(1,1,1)
Actor5.GetProperty().SetColor(1,1,1)
Actor5.SetNumberOfCloudPoints(30000)
ren1.AddActor(Actor5)
camera = vtk.vtkCamera()
camera.SetClippingRange(3,6)
camera.SetFocalPoint(.1,.03,-.5)
camera.SetPosition(4.4,-0.5,-.5)
Esempio n. 52
0
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create a vtkBYUReader and read in a data set.
fohe = vtk.vtkBYUReader()
fohe.SetGeometryFileName(VTK_DATA_ROOT + "/Data/teapot.g")

# Create a vtkPolyDataNormals filter to calculate the normals of the
# data set.
normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(fohe.GetOutputPort())
# Set up the associated mapper and actor.
foheMapper = vtk.vtkPolyDataMapper()
foheMapper.SetInputConnection(normals.GetOutputPort())
foheActor = vtk.vtkLODActor()
foheActor.SetMapper(foheMapper)

# Create a vtkOutlineFilter to draw the bounding box of the data set.
# Also create the associated mapper and actor.
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(normals.GetOutputPort())
mapOutline = vtk.vtkPolyDataMapper()
mapOutline.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(mapOutline)
outlineActor.GetProperty().SetColor(0, 0, 0)

# Create a vtkCamera, and set the camera parameters.
camera = vtk.vtkCamera()
camera.SetClippingRange(1.60187, 20.0842)
	def InitVTKMethods(self):
		"""Initializes the VTK methods to be used"""
		self._outline=vtkStructuredGridOutlineFilter()
		self._tube=vtkTubeFilter()
		self._mapper_=vtkPolyDataMapper()
		self.actor=vtkLODActor()
Esempio n. 54
0
    return rgb

ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# create a sphere source and actor
#
sphere = vtk.vtkSphereSource()

sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())

sphereActor = vtk.vtkLODActor()
sphereActor.SetMapper(sphereMapper)
sphereActor.GetProperty().SetDiffuseColor(GetRGBColor('banana'))
sphereActor.GetProperty().SetSpecular(.4)
sphereActor.GetProperty().SetSpecularPower(20)

# create the spikes using a cone source and the sphere source
#
cone = vtk.vtkConeSource()
cone.SetResolution(20)

glyph = vtk.vtkGlyph3D()
glyph.SetInputConnection(sphere.GetOutputPort())
glyph.SetSourceConnection(cone.GetOutputPort())
glyph.SetVectorModeToUseNormal()
glyph.SetScaleModeToScaleByVector()
Esempio n. 55
0
cone = vtk.vtkConeSource()
glyph = vtk.vtkGlyph3D()
glyph.SetInputConnection(sphere.GetOutputPort())
glyph.SetSourceConnection(cone.GetOutputPort())
glyph.SetVectorModeToUseNormal()
glyph.SetScaleModeToScaleByVector()
glyph.SetScaleFactor(0.25)

# The sphere and spikes are appended into a single polydata. This just
# makes things simpler to manage.
apd = vtk.vtkAppendPolyData()
apd.AddInputConnection(glyph.GetOutputPort())
apd.AddInputConnection(sphere.GetOutputPort())
maceMapper = vtk.vtkPolyDataMapper()
maceMapper.SetInputConnection(apd.GetOutputPort())
maceActor = vtk.vtkLODActor()
maceActor.SetMapper(maceMapper)
maceActor.VisibilityOn()

# This portion of the code clips the mace with the vtkPlanes implicit
# function.  The clipped region is colored green.
planes = vtk.vtkPlanes()
clipper = vtk.vtkClipPolyData()
clipper.SetInputConnection(apd.GetOutputPort())
clipper.SetClipFunction(planes)
clipper.InsideOutOn()
selectMapper = vtk.vtkPolyDataMapper()
selectMapper.SetInputConnection(clipper.GetOutputPort())
selectActor = vtk.vtkLODActor()
selectActor.SetMapper(selectMapper)
selectActor.GetProperty().SetColor(0, 1, 0)
Esempio n. 56
0
    def testBoxWidget(self):

        # Demonstrate how to use the vtkBoxWidget.
        # This script uses a 3D box widget to define a "clipping box" to clip some
        # simple geometry (a mace). Make sure that you hit the "W" key to activate the widget.

        # create a sphere source
        #
        sphere = vtk.vtkSphereSource()
        cone = vtk.vtkConeSource()
        glyph = vtk.vtkGlyph3D()
        glyph.SetInputConnection(sphere.GetOutputPort())
        glyph.SetSourceConnection(cone.GetOutputPort())
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleModeToScaleByVector()
        glyph.SetScaleFactor(0.25)
        apd = vtk.vtkAppendPolyData()
        apd.AddInputConnection(glyph.GetOutputPort())
        apd.AddInputConnection(sphere.GetOutputPort())
        maceMapper = vtk.vtkPolyDataMapper()
        maceMapper.SetInputConnection(apd.GetOutputPort())
        maceActor = vtk.vtkLODActor()
        maceActor.SetMapper(maceMapper)
        maceActor.VisibilityOn()

        planes = vtk.vtkPlanes()
        clipper = vtk.vtkClipPolyData()
        clipper.SetInputConnection(apd.GetOutputPort())
        clipper.SetClipFunction(planes)
        clipper.InsideOutOn()
        selectMapper = vtk.vtkPolyDataMapper()
        selectMapper.SetInputConnection(clipper.GetOutputPort())
        selectActor = vtk.vtkLODActor()
        selectActor.SetMapper(selectMapper)
        selectActor.GetProperty().SetColor(0, 1, 0)
        selectActor.VisibilityOff()
        selectActor.SetScale(1.01, 1.01, 1.01)

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

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        boxWidget = vtk.vtkBoxWidget()
        boxWidget.SetInteractor(iRen)

        ren.AddActor(maceActor)
        ren.AddActor(selectActor)

        # Add the actors to the renderer, set the background and size
        #
        ren.SetBackground(0.1, 0.2, 0.4)
        renWin.SetSize(300, 300)

        def SelectPolygons(widget, event_string):
            '''
            The callback takes two parameters.
            Parameters:
              widget - the object that generates the event.
              event_string - the event name (which is a string).
            '''
            boxWidget, selectActor
            boxWidget.GetPlanes(planes)
            selectActor.VisibilityOn()

        # place the interactor initially
        boxWidget.SetInputConnection(glyph.GetOutputPort())
        boxWidget.PlaceWidget()
        boxWidget.AddObserver("EndInteractionEvent", SelectPolygons)

        # render and interact with data

        renWin.Render()

        img_file = "TestBoxWidget.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Esempio n. 57
0
def tubes(lines, colors, opacity=1, linewidth=0.15, tube_sides=8,
          lod=True, lod_points=10 ** 4, lod_points_size=5):
    """ Uses streamtubes to visualize polylines.


    Parameters
    ----------
    lines : list
        a list of array representing a line as 3d points (N, 3)
    colors : array (N, 3)
        rgb colors.
    opacity : float (default = 1)
        the transparency of the bloc of lines: 0 <= transparency <= 1.
    linewidth : float (default = 1)
        the line thickness.
    tube_sides: int
        the tube resolution.
    lod: bool
        use vtkLODActor rather than vtkActor.
    lod_points: int
        number of points to be used when LOD is in effect.
    lod_points_size: int
        size of points when lod is in effect.

    Returns
    ----------
    actor: vtkActor or vtkLODActor
        the bloc of tubes actor.
    """
    points = vtk.vtkPoints()

    colors = numpy.asarray(colors)
    if colors.ndim == 1:
        colors = numpy.tile(colors, (len(lines), 1))

    # Create the polyline.
    streamlines = vtk.vtkCellArray()

    cols = vtk.vtkUnsignedCharArray()
    cols.SetName("Cols")
    cols.SetNumberOfComponents(3)

    len_lines = len(lines)
    prior_line_shape = 0
    for i in range(len_lines):
        line = lines[i]
        streamlines.InsertNextCell(line.shape[0])
        for j in range(line.shape[0]):
            points.InsertNextPoint(*line[j])
            streamlines.InsertCellPoint(j + prior_line_shape)
            color = (255 * colors[i]).astype('ubyte')
            cols.InsertNextTuple3(*color)
        prior_line_shape += line.shape[0]

    profileData = vtk.vtkPolyData()
    profileData.SetPoints(points)
    profileData.SetLines(streamlines)
    profileData.GetPointData().AddArray(cols)

    # Add thickness to the resulting line.
    profileTubes = vtk.vtkTubeFilter()
    profileTubes.SetNumberOfSides(tube_sides)

    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        profileTubes.SetInput(profileData)
    else:
        profileTubes.SetInputData(profileData)

    # profileTubes.SetInput(profileData)
    profileTubes.SetRadius(linewidth)

    profileMapper = vtk.vtkPolyDataMapper()
    profileMapper.SetInputConnection(profileTubes.GetOutputPort())
    profileMapper.ScalarVisibilityOn()
    profileMapper.SetScalarModeToUsePointFieldData()
    profileMapper.SelectColorArray("Cols")
    profileMapper.GlobalImmediateModeRenderingOn()

    if lod:
        profile = vtk.vtkLODActor()
        profile.SetNumberOfCloudPoints(lod_points)
        profile.GetProperty().SetPointSize(lod_points_size)
    else:
        profile = vtk.vtkActor()
    profile.SetMapper(profileMapper)

    profile.GetProperty().SetAmbient(0)  # .3
    profile.GetProperty().SetSpecular(0)  # .3
    profile.GetProperty().SetSpecularPower(10)
    profile.GetProperty().SetInterpolationToGouraud()
    profile.GetProperty().BackfaceCullingOn()
    profile.GetProperty().SetOpacity(opacity)

    return profile
Esempio n. 58
0
iso.SetValue(0, .24)

normals = vtk.vtkPolyDataNormals()
normals.SetInputConnection(iso.GetOutputPort())
normals.SetFeatureAngle(45)

# We indicate to the mapper to use the velcoity magnitude, which is a
# vtkDataArray that makes up part of the point attribute data.
isoMapper = vtk.vtkPolyDataMapper()
isoMapper.SetInputConnection(normals.GetOutputPort())
isoMapper.ScalarVisibilityOn()
isoMapper.SetScalarRange(0, 1500)
isoMapper.SetScalarModeToUsePointFieldData()
isoMapper.ColorByArrayComponent("VelocityMagnitude", 0)

isoActor = vtk.vtkLODActor()
isoActor.SetMapper(isoMapper)
isoActor.SetNumberOfCloudPoints(1000)

outline = vtk.vtkStructuredGridOutlineFilter()
outline.SetInputData(pl3d_output)
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)

# Create the usual rendering stuff.
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
Esempio n. 59
0
    def __init__(self, ren, renWin, iren):

        self.ren = ren
        self.renWin = renWin
        self.iren = iren

        colors = self.Colors()

        self.renWin.AddRenderer(self.ren)

        self.iren.SetRenderWindow(self.renWin)
        self.iren.SetDesiredUpdateRate(.00001)

        # Create a sphere source and actor

        sphere = vtk.vtkSphereSource()

        sphereMapper = vtk.vtkPolyDataMapper()
        sphereMapper.SetInputConnection(sphere.GetOutputPort())

        sphereActor = vtk.vtkLODActor()
        sphereActor.SetMapper(sphereMapper)

        sphereActor.GetProperty().SetDiffuseColor(colors.GetRGBColor('banana'))
        sphereActor.GetProperty().SetSpecular(.4)
        sphereActor.GetProperty().SetSpecularPower(20)

        # Create the spikes using a cone source and the sphere source

        cone = vtk.vtkConeSource()
        cone.SetResolution(20)

        glyph = vtk.vtkGlyph3D()
        glyph.SetInputConnection(sphere.GetOutputPort())
        glyph.SetSourceConnection(cone.GetOutputPort())
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleModeToScaleByVector()
        glyph.SetScaleFactor(0.25)

        spikeMapper = vtk.vtkPolyDataMapper()
        spikeMapper.SetInputConnection(glyph.GetOutputPort())

        spikeActor = vtk.vtkLODActor()
        spikeActor.SetMapper(spikeMapper)

        spikeActor.GetProperty().SetDiffuseColor(colors.GetRGBColor('tomato'))
        spikeActor.GetProperty().SetSpecular(.4)
        spikeActor.GetProperty().SetSpecularPower(20)

        # Add the actors to the renderer, set the background and size

        self.ren.AddActor(sphereActor)
        self.ren.AddActor(spikeActor)
        self.ren.SetBackground(0.1, 0.2, 0.4)

        self.renWin.SetSize(300, 300)

        # Render the image

        self.ren.ResetCamera()
        cam1 = ren.GetActiveCamera()
        cam1.Zoom(1.4)
        cam1.Azimuth(30)
        cam1.Elevation(30)

        self.renWin.Render()