Пример #1
0
	def start_pick(self):
		#Required to change interactor
		style=vtk.vtkInteractorStyleRubberBandPick()
		self.iren.SetInteractorStyle(style)
		picker = vtk.vtkAreaPicker()
		self.iren.SetPicker(picker)
		picker.AddObserver("EndPickEvent", self.picker_callback)
Пример #2
0
    def create_cell_picker(self):
        """creates the vtk picker objects"""
        self.cell_picker = vtk.vtkCellPicker()
        self.node_picker = vtk.vtkPointPicker()

        self.area_picker = vtk.vtkAreaPicker()  # vtkRenderedAreaPicker?
        self.rubber_band_style = vtk.vtkInteractorStyleRubberBandPick()
        #vtk.vtkInteractorStyleRubberBand2D
        #vtk.vtkInteractorStyleRubberBand3D
        #vtk.vtkInteractorStyleRubberBandZoom
        #vtk.vtkInteractorStyleAreaSelectHover
        #vtk.vtkInteractorStyleDrawPolygon

        #vtk.vtkAngleWidget
        #vtk.vtkAngleRepresentation2D
        #vtk.vtkAngleRepresentation3D
        #vtk.vtkAnnotation
        #vtk.vtkArrowSource
        #vtk.vtkGlyph2D
        #vtk.vtkGlyph3D
        #vtk.vtkHedgeHog
        #vtk.vtkLegendBoxActor
        #vtk.vtkLegendScaleActor
        #vtk.vtkLabelPlacer

        self.cell_picker.SetTolerance(0.001)
        self.node_picker.SetTolerance(0.001)
Пример #3
0
 def start_pick(self):
     #Required to change interactor
     style = vtk.vtkInteractorStyleRubberBandPick()
     self.iren.SetInteractorStyle(style)
     picker = vtk.vtkAreaPicker()
     self.iren.SetPicker(picker)
     picker.AddObserver("EndPickEvent", self.picker_callback)
Пример #4
0
    def start_pick(self):

        style = vtk.vtkInteractorStyleRubberBandPick()
        self.iren.SetInteractorStyle(style)
        picker = vtk.vtkAreaPicker()
        self.iren.SetPicker(picker)

        picker.AddObserver("EndPickEvent", self.picker_callback)
        self.ui.vtkWidget.setFocus()
def main():
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(20)
    pointSource.Update()

    idFilter = vtk.vtkIdFilter()
    idFilter.SetInputConnection(pointSource.GetOutputPort())
    idFilter.SetIdsArrayName("OriginalIds")
    idFilter.Update()

    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(idFilter.GetOutputPort())
    surfaceFilter.Update()

    poly_input = surfaceFilter.GetOutput()

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()

    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInputConnection(poly_input.GetProducerPort())
    else:
        mapper.SetInputData(poly_input)
    mapper.ScalarVisibilityOff()

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

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    areaPicker = vtk.vtkAreaPicker()
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetPicker(areaPicker)
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    #renderer.SetBackground(1,1,1) # Background color white

    renderWindow.Render()

    style = vtk.vtkRenderWindowInteractor()
    #style = myInteractorStyle()
    #style = InteractorStyle()
    #style = QVTKRenderWindowInteractor()
    #style.SetPoints(poly_input)
    renderWindowInteractor.SetInteractorStyle(style)

    renderWindowInteractor.Start()
    def pickActors(self):
        renderer = self.GetDefaultRenderer() or self.GetCurrentRenderer()
        if renderer is None:
            return 

        self.lowlight(self.getSelectedActors())

        x1, y1 = self.clickPosition
        x2, y2 = self.mousePosition

        tolerance = 5 
        tooSmall = (abs(x1-x2) < tolerance) or (abs(y1-y2) < tolerance)
        pickedActors = set()

        if tooSmall:
            picker = vtk.vtkPropPicker()
            picker.Pick(x2, y2, 0, renderer)
            actor = picker.GetActor()
            if actor:
                pickedActors.add(actor)
        else:
            picker = vtk.vtkAreaPicker()
            picker.AreaPick(x1, y1, x2, y2, renderer)
            actors = set(picker.GetProp3Ds())
            pickedActors.update(actors)

        controlPressed = self.GetInteractor().GetControlKey()
        shiftPressed = self.GetInteractor().GetShiftKey()
        altPressed = self.__altKeyClicked

        if self.checkPoints(pickedActors) or self.checkElements(pickedActors):
            self.pickActors()
            return

        if controlPressed or shiftPressed:
            self.__selectedActors |= pickedActors      
        elif altPressed:
            self.__selectedActors -= pickedActors  
        else:
            self.__selectedActors = pickedActors

        self.highlight(self.getSelectedActors())       

        function, args, kwargs = self.__callOnSelection
        if function is not None:
            actors = self.getSelectedActors()
            function(actors, *args, **kwargs)

        self.__renderer.updateInfoText()
        self.__renderer.update()
Пример #7
0
 def vertex_select(self):
     if self.ui.choose_vertex_button.isChecked():
         self.vertex_actor.SetVisibility(True)
         self.iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick())
         picker = vtk.vtkAreaPicker()
         self.iren.SetPicker(picker)
         picker.AddObserver("EndPickEvent", self.picker_callback)
         self.ui.trans_origin_button.setEnabled(False)
         self.ui.vtkWidget.setFocus()
         self.ui.vtkWidget.update()
     else:
         self.ui.trans_origin_button.setEnabled(False)
         self.vertex_actor.SetVisibility(False)
         self.ui.trans_origin_button.setEnabled(True)
         self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
         self.transform_origin()
         self.ui.vtkWidget.update()
    def OnLeftButtonUp(self):
        # Forward events
        vtkInteractorStyleRubberBandPick.OnLeftButtonUp()

        frustum = vtk.vtkAreaPicker(
            self.GetInteractor().GetPicker()).GetFrustum()

        extract_geometry = vtk.vtkExtractGeometry()
        extract_geometry.SetImplicitFunction(frustum)

        if vtk.VTK_MAJOR_VERSION <= 5:
            extract_geometry.SetInput(self.Points)
        else:
            extract_geometry.SetInputData(self.Points)
        extract_geometry.Update()

        glyph_filter = vtk.vtkVertexGlyphFilter()
        glyph_filter.SetInputConnection(extract_geometry.GetOutputPort())
        glyph_filter.Update()

        selected = glyph_filter.GetOutput()
        print("Selected %s points" % selected.GetNumberOfPoints())
        print("Selected %s cells" % selected.GetNumberOfCells())
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.SelectedMapper.SetInput(selected)
        else:
            self.SelectedMapper.SetInputData(selected)

        self.SelectedMapper.ScalarVisibilityOff()

        ids = vtkIdTypeArray.SafeDownCast(
            selected.GetPointData().GetArray("OriginalIds"))
        for i in range(ids.GetNumberOfTuples()):
            print("Id %s : %s" % (i, ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0)  #(R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.CurrentRenderer.AddActor(selected_actor)
        self.GetInteractor().GetRenderWindow().Render()
Пример #9
0
    def leftButtonReleaseEvent(self,obj,event):
        p0 = self.GetStartPosition()
        p1 = self.GetEndPosition()

        picker = vtk.vtkAreaPicker()
        picker.AreaPick(p0[0], p0[1], p1[0], p1[1], self.GetDefaultRenderer())
        at = self.davtk_state.cur_at()
        actors = picker.GetProp3Ds()
        points = []
        # find selected points
        for actor in actors:
            if not hasattr(actor, "point_to_input_point"):
                points.append([None])
                continue
            frustum = picker.GetFrustum()
            geom = vtk.vtkExtractGeometry()
            geom.SetImplicitFunction(frustum)
            geom.SetInputData(actor.GetMapper().GetInput())
            geom.Update()

            IDs = geom.GetOutputDataObject(0).GetPointData().GetArray("IDs")
            points.append([])
            for ID_i in range(IDs.GetNumberOfTuples()):
                points[-1].append(int(IDs.GetTuple(ID_i)[0]/actor.point_to_input_point))
            points[-1] = set(points[-1])

        pick_actors(self.davtk_state.cur_at(), actors, points)
        self.davtk_state.update()

        self.OnLeftButtonUp()

        if self.prev_style is None:
            raise ValueError("leftButtonReleaseEvent prev_style not set")

        self.GetInteractor().SetInteractorStyle(self.prev_style)
        self.prev_style.GetInteractor().Render()
        self.prev_Style = None

        return
Пример #10
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setStyleSheet('background-color:#333333')
        self.vtk_layout = QtGui.QGridLayout(self)
        self.vtk_widget = QVTKRenderWindowInteractor(self)
        self.vtk_layout.addWidget(self.vtk_widget)
        self.ren = vtk.vtkRenderer()
        self.vtk_widget.GetRenderWindow().AddRenderer(self.ren)
        self.meshMapper = vtk.vtkPolyDataMapper()
        self.meshActor = vtk.vtkActor()
        self.meshActor.SetMapper(self.meshMapper)
        self.ren.AddActor(self.meshActor)
        self.interactionStyle = RubberBandFacePicker()
        self.interactionStyle.SetDefaultRenderer(self.ren)
        self.vtk_widget.SetInteractorStyle(self.interactionStyle)
        self.vtk_widget.SetPicker(vtk.vtkAreaPicker())
        self.iren = self.vtk_widget.GetRenderWindow().GetInteractor()
        self.show()
        self.iren.Initialize()

        # name2actor map for calls to display_XXXX
        self.name2actor = {}
    def OnLeftButtonUp(self):
        # Forward events
        vtkInteractorStyleRubberBandPick.OnLeftButtonUp()

        frustum = vtk.vtkAreaPicker(self.GetInteractor().GetPicker()).GetFrustum()

        extractGeometry = vtk.vtkExtractGeometry.New()
        extractGeometry.SetImplicitFunction(frustum)

        if VTK_MAJOR_VERSION <= 5:
            extractGeometry.SetInput(this.Points)
        else:
            extractGeometry.SetInputData(this.Points)
        extractGeometry.Update()

        glyphFilter = vtk.vtkVertexGlyphFilter()
        glyphFilter.SetInputConnection(extractGeometry.GetOutputPort())
        glyphFilter.Update()

        selected = glyphFilter.GetOutput()
        print("Selected %s points" % selected.GetNumberOfPoints())
        print("Selected %s cells" % selected.GetNumberOfCells())
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.SelectedMapper.SetInput(selected)
        else:
            self.SelectedMapper.SetInputData(selected)

        self.SelectedMapper.ScalarVisibilityOff()

        ids = vtkIdTypeArray.SafeDownCast(selected.GetPointData().GetArray("OriginalIds"))
        for i in range(ids.GetNumberOfTuples()):
            print("Id %s : %s" % (i, ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0) #(R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.CurrentRenderer.AddActor(SelectedActor)
        self.GetInteractor().GetRenderWindow().Render()
Пример #12
0
    def rightButtonReleaseEvent(self, obj, event):
        if not self.allowedPicker():
            return
        if self.posA is None:
            return

        self.posB = self.GetInteractor().GetEventPosition()

        #if you already have picked any actor, restore before state
        for i in range(len(self.lastSelectedEntitiesProperty)):
            self.lastSelectedActors[i].GetProperty().DeepCopy(
                self.lastSelectedEntitiesProperty[i])

        self.lastSelectedActors.clear()
        self.lastSelectedEntitiesProperty.clear()
        self.listSelectedEntities.clear()

        picker = vtk.vtkAreaPicker()
        picker.AreaPick(self.posA[0], self.posA[1], self.posB[0], self.posB[1],
                        self.GetDefaultRenderer())
        pickedActors = picker.GetProp3Ds()
        for actor in pickedActors:
            if self.renderer.actors[actor] == -1:
                continue
            current_actor_property = vtk.vtkProperty()
            current_actor_property.DeepCopy(actor.GetProperty())
            self.lastSelectedEntitiesProperty.append(current_actor_property)

            actor.GetProperty().SetColor(colors.GetColor3d('Red'))
            actor.GetProperty().SetDiffuse(1.0)
            actor.GetProperty().SetSpecular(0.0)
            self.lastSelectedActors.append(actor)
            self.listSelectedEntities.append(self.renderer.actors[actor])
        self.renderer.updateInfoText()
        self.renderer.updateAreaPicker((0, 0), (0, 0))
        self.posA = None
        self.renderer.update()
Пример #13
0
    def pickElements(self, x0, y0, x1, y1, tolerance=10):
        tooSmall = (abs(x0-x1) < tolerance) or (abs(y0-y1) < tolerance)
        if tooSmall:
            x0, x1 = (x0-tolerance//2), (x1+tolerance//2)
            y0, y1 = (y0-tolerance//2), (y1+tolerance//2)

        picker = vtk.vtkAreaPicker()
        extractor = vtk.vtkExtractSelectedFrustum()
        renderer = self.__rendererMesh._renderer
        picker.AreaPick(x0,y0,x1,y1,renderer)
        extractor.SetFrustum(picker.GetFrustum())

        elementsBounds = self.__rendererMesh.elementsBounds
        camPos = renderer.GetActiveCamera().GetPosition()
        distanceFromCamera = lambda key: distanceBoundsToPoint(camPos, elementsBounds[key])
        pickedElements = {key for key, bound in elementsBounds.items() if extractor.OverallBoundsTest(bound)}

        # when not box selecting, pick only the closest element
        if tooSmall and pickedElements:
            closest = min(pickedElements, key=distanceFromCamera)
            pickedElements.clear()
            pickedElements.add(closest)

        return pickedElements
Пример #14
0
    def get_frustrum(self):

        render = self._contour_representation.GetRenderer()
        numberNodes = self._contour_representation.GetNumberOfNodes()

        V = list()
        for i in range(numberNodes):
            v = np.array([0,0])
            self._contour_representation.GetNthNodeDisplayPosition(i, v)
            V.append(v)

        xmin = np.min(np.array(V)[:,0])
        ymin = np.min(np.array(V)[:,1])
        xmax = np.max(np.array(V)[:,0])
        ymax = np.max(np.array(V)[:,1])

        p1 = np.array([xmin, ymax])
        p2 = np.array([xmax, ymin])

        picker = vtkAreaPicker()
        picker.AreaPick( p1[0], p1[1], p2[0], p2[1], render)

        planes = picker.GetFrustum()
        return planes
Пример #15
0
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInputConnection(poly_input.GetProducerPort())
    else:
        mapper.SetInputData(poly_input)
    mapper.ScalarVisibilityOff()

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

    # Visualize
    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    area_picker = vtk.vtkAreaPicker()
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetPicker(area_picker)
    render_window_interactor.SetRenderWindow(render_window)

    renderer.AddActor(actor)
    # renderer.SetBackground(1,1,1) # Background color white

    render_window.Render()

    style = vtk.vtkRenderWindowInteractor()
    # style = myInteractorStyle()
    # style = InteractorStyle()
    # style = QVTKRenderWindowInteractor()
    # style.SetPoints(poly_input)
    render_window_interactor.SetInteractorStyle(style)
Пример #16
0
 def SetPicker(self, picker=None):
     if picker:
         self.picker = picker
     else:
         self.picker = vtk.vtkAreaPicker()
Пример #17
0
def test_vtkInteractorStyleRubberBandPick():
    ren = vtk.vtkRenderer()
    ren.SetBackground(1.0, 1.0, 1.0)

    V, T = box_model(5, 10, 1.0, 1.0)
    poly_data = numpy_to_vtkPolyData(V, faces.faces_to_cell_array(T))

    idFilter = vtk.vtkIdFilter()
    idFilter.SetInput(poly_data)
    idFilter.SetIdsArrayName('i')
    idFilter.Update()

    poly_data = idFilter.GetOutput()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(poly_data)
    mapper.SetScalarVisibility(False)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(0.0, 0.6, 0.3)

    ren.AddActor(actor)

    visible = vtk.vtkSelectVisiblePoints()
    visible.SetInput(poly_data)
    visible.SetRenderer(ren)

    # highlight
    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(0.2)

    highlight_poly_data = vtk.vtkPolyData()

    highlight_glyph = vtk.vtkGlyph3D()
    highlight_glyph.SetInput(highlight_poly_data)
    highlight_glyph.SetSourceConnection(sphere.GetOutputPort())

    highlight_mapper = vtk.vtkPolyDataMapper()
    highlight_mapper.SetInputConnection(highlight_glyph.GetOutputPort())

    highlight_actor = vtk.vtkActor()
    highlight_actor.SetMapper(highlight_mapper)
    highlight_actor.GetProperty().SetColor(1.0, 0.0, 0.0)
    highlight_actor.VisibilityOff()
    highlight_actor.PickableOff()
    ren.AddActor(highlight_actor)

    # render window
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(ren)
    render_window.SetSize(400, 400)

    picker = vtk.vtkAreaPicker()

    def pickCallback(obj, event):
        props = obj.GetProp3Ds()
        if props.GetNumberOfItems() <= 0:
            return

        extract_geometry = vtk.vtkExtractGeometry()
        extract_geometry.SetImplicitFunction(picker.GetFrustum())
        extract_geometry.SetInput(props.GetLastProp3D().GetMapper().GetInput())
        extract_geometry.Update()

        unstructured_grid = extract_geometry.GetOutput()

        if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
            return

        visible.Update()
        if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
            return

        i = np.intersect1d(
            vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i')),
            vtk_to_numpy(visible.GetOutput().GetPointData().GetArray('i')))

        if i.shape[0] <= 0:
            return

        vtk_points = vtk.vtkPoints()
        vtk_points.SetNumberOfPoints(i.shape[0])
        vtk_points_data = vtk_to_numpy(vtk_points.GetData())
        vtk_points_data.flat = np.require(V[i], np.float32, 'C')

        highlight_poly_data.SetPoints(vtk_points)
        highlight_actor.VisibilityOn()

    picker.AddObserver('EndPickEvent', pickCallback)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(render_window)
    iren.SetPicker(picker)

    ren.ResetCamera()

    render_window.Render()

    style = vtk.vtkInteractorStyleRubberBandPick()
    style.SetCurrentRenderer(ren)
    iren.SetInteractorStyle(style)

    iren.Initialize()
    iren.Start()
Пример #18
0
    def _setup_pipeline(self):
        ren = vtk.vtkRenderer()
        ren.SetBackground(1.0, 1.0, 1.0)

        color_points = vtk.vtkProgrammableFilter()

        def callback_color_points():
            input_ = color_points.GetInput()
            output = color_points.GetOutput()
            output.ShallowCopy(input_)

            lookup = vtk.vtkFloatArray()
            lookup.SetNumberOfValues(input_.GetNumberOfPoints())
            npy_lookup = vtk_to_numpy(lookup)
            npy_lookup.flat = self._k.astype(
                np.float32) / (COLORMAP.shape[0] - 1)

            output.GetPointData().SetScalars(lookup)

        color_points.SetExecuteMethod(callback_color_points)

        source = vtk.vtkCubeSource()

        vertices_glyph = vtk.vtkGlyph3D()
        vertices_glyph.SetInputConnection(color_points.GetOutputPort())
        vertices_glyph.SetSourceConnection(source.GetOutputPort())
        vertices_glyph.SetScaleModeToDataScalingOff()
        vertices_glyph.SetColorModeToColorByScalar()

        vertices_mapper = vtk.vtkPolyDataMapper()
        vertices_mapper.SetInputConnection(vertices_glyph.GetOutputPort())
        vertices_mapper.SetLookupTable(LUT)

        vertices_actor = vtk.vtkActor()
        vertices_actor.SetMapper(vertices_mapper)
        vertices_actor.GetProperty().SetColor(*COLORMAP[0, :3])
        vertices_actor.PickableOff()
        vertices_actor.VisibilityOff()
        ren.AddActor(vertices_actor)

        color_faces = vtk.vtkProgrammableFilter()

        def callback_color_faces():
            input_ = color_faces.GetInput()
            output = color_faces.GetOutput()
            output.ShallowCopy(input_)

            lookup = vtk.vtkFloatArray()
            lookup.SetNumberOfValues(input_.GetNumberOfPolys())
            npy_lookup = vtk_to_numpy(lookup)

            labelled_T = self._k[self.T]
            for i in xrange(input_.GetNumberOfPolys()):
                l = np.argmax(np.bincount(labelled_T[i]))
                npy_lookup[i] = float(l) / (COLORMAP.shape[0] - 1)

            output.GetCellData().SetScalars(lookup)

        color_faces.SetExecuteMethod(callback_color_faces)

        model_mapper = vtk.vtkPolyDataMapper()
        model_mapper.SetInputConnection(color_faces.GetOutputPort())
        model_mapper.SetLookupTable(LUT)

        model_actor = vtk.vtkActor()
        model_actor.SetMapper(model_mapper)
        model_actor.GetProperty().SetColor(*COLORMAP[0, :3])
        model_actor.VisibilityOff()
        ren.AddActor(model_actor)

        render_window = vtk.vtkRenderWindow()
        render_window.AddRenderer(ren)
        render_window.SetSize(400, 400)
        self.SetRenderWindow(render_window)

        visible = vtk.vtkSelectVisiblePoints()
        visible.SetRenderer(ren)

        picker = vtk.vtkAreaPicker()

        def callback_picker(obj, event):
            props = obj.GetProp3Ds()
            if props.GetNumberOfItems() <= 0:
                return

            extract_geometry = vtk.vtkExtractGeometry()
            extract_geometry.SetImplicitFunction(picker.GetFrustum())
            extract_geometry.SetInput(visible.GetInput())
            extract_geometry.Update()

            unstructured_grid = extract_geometry.GetOutput()
            if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
                return

            i = vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i'))

            if self.select_only_visible:
                visible.Update()

                if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
                    return

                i = np.intersect1d(
                    i,
                    vtk_to_numpy(
                        visible.GetOutput().GetPointData().GetArray('i')))

                if i.shape[0] <= 0:
                    return

            self.set_labels(self.current_label, i)

        picker.AddObserver('EndPickEvent', callback_picker)

        iren = self.GetInteractor()
        iren.SetRenderWindow(render_window)
        iren.SetPicker(picker)

        style = vtk.vtkInteractorStyleRubberBandPick()
        style.SetCurrentRenderer(ren)
        iren.SetInteractorStyle(style)

        self.pipeline = locals()

        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Expanding)
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInputConnection(poly_input.GetProducerPort())
    else:
        mapper.SetInputData(poly_input)
    mapper.ScalarVisibilityOff()

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

    # Visualize
    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    area_picker = vtk.vtkAreaPicker()
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetPicker(area_picker)
    render_window_interactor.SetRenderWindow(render_window)

    renderer.AddActor(actor)
    #renderer.SetBackground(1,1,1) # Background color white

    render_window.Render()

    style = vtk.vtkRenderWindowInteractor()
    #style = myInteractorStyle()
    #style = InteractorStyle()
    #style = QVTKRenderWindowInteractor()
    #style.SetPoints(poly_input)
    render_window_interactor.SetInteractorStyle(style)
Пример #20
0
    def __init__(self, filename, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        # Initiate the UI as defined by Qt Designer
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.poly_data = None

        self.node_ids = None
        self.element_ids = None
        self.node_count = 0

        self.read_data(filename)

        self.ui.txt_msg.appendPlainText("Model Loaded.")

        # initialize colors
        self.eidcolor = (0, 0.5, 0.5)
        self.edgecolor = (0, 0, 0)
        self.bgcolor1 = (0, 0, 1)
        self.bgcolor2 = (0.8, 0.8, 1)
        self.perspective = 0
        self.solid = 1

        self.idFilter = vtk.vtkIdFilter()
        self.idFilter.SetInputData(self.poly_data)
        self.idFilter.SetIdsArrayName("OriginalIds")
        self.idFilter.Update()

        self.surfaceFilter = vtk.vtkDataSetSurfaceFilter()
        self.surfaceFilter.SetInputConnection(self.idFilter.GetOutputPort())
        self.surfaceFilter.Update()

        self.input = self.surfaceFilter.GetOutput()

        self.renderer = vtk.vtkRenderer()
        #self.renderer2 = vtk_widget.vtkRenderer()

        viewport = [0.0,0.0,0.15,0.15]
        #self.renderer2.SetViewport(viewport)
        #self.renderer2.Transparent()

        self.renderWindowInteractor = QVTKRenderWindowInteractor(self.ui.frame)
        self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer)
        #self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer2)
        self.renderWindowInteractor.GetRenderWindow().SetAlphaBitPlanes(1)

        self.axes = CoordinateAxes(self.renderWindowInteractor)

        self.ui.vl.addWidget(self.renderWindowInteractor)

        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren = self.renderWindowInteractor.GetRenderWindow().GetInteractor()

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.input)
        self.mapper.ScalarVisibilityOff()

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetPointSize(2)
        self.actor.GetProperty().EdgeVisibilityOn()
        self.actor.GetProperty().SetColor(self.eidcolor)
        self.actor.GetProperty().SetEdgeColor(self.edgecolor)

        self.camera = vtk.vtkCamera()
        #self.camera2 = vtk_widget.vtkCamera()


        # trial... add glyph
        pd = vtk.vtkPolyData()
        pts = vtk.vtkPoints()
        scalars = vtk.vtkFloatArray()
        vectors = vtk.vtkFloatArray()
        vectors.SetNumberOfComponents(3)
        pd.SetPoints(pts)
        pd.GetPointData().SetScalars(scalars)
        pd.GetPointData().SetVectors(vectors)
        pts.InsertNextPoint(30, 30, 0.0)
        scalars.InsertNextValue(1)
        vectors.InsertNextTuple3(1, 1, 0.0)

        # Create simple PolyData for glyph table
        cs = vtk.vtkCubeSource()
        cs.SetXLength(0.5)
        cs.SetYLength(1)
        cs.SetZLength(2)
        # Set up the glyph filter
        glyph = vtk.vtkGlyph3D()
        #glyph.SetInputConnection(elev.GetOutputPort())


        point_list = vtk.vtkPoints()
        point_list.InsertNextPoint([30, 30, 0])
        poly_data = vtk.vtkPolyData()
        poly_data.SetPoints(point_list)

        idFilter = vtk.vtkIdFilter()
        idFilter.SetInputData(poly_data)
        idFilter.SetIdsArrayName("OriginalIds")
        idFilter.Update()

        surfaceFilter = vtk.vtkDataSetSurfaceFilter()
        surfaceFilter.SetInputConnection(idFilter.GetOutputPort())
        surfaceFilter.Update()


        # Here is where we build the glyph table
        # that will be indexed into according to the IndexMode
        glyph.SetSourceData(0,cs.GetOutput())
        #glyph.SetInputConnection(surfaceFilter.GetOutputPort())
        glyph.SetInputData(pd)
        glyph.SetIndexModeToScalar()
        glyph.SetRange(0, 1)
        glyph.SetScaleModeToDataScalingOff()
        glyph.OrientOn()
        mapper3 = vtk.vtkPolyDataMapper()
        mapper3.SetInputConnection(glyph.GetOutputPort())
        mapper3.SetScalarModeToUsePointFieldData()
        mapper3.SetColorModeToMapScalars()
        mapper3.ScalarVisibilityOn()
        mapper3.SetScalarRange(0, 1)
        actor3 = vtk.vtkActor()
        actor3.SetMapper(mapper3)
        #actor3.GetProperty().SetBackgroundOpacity(0.5)        


        gs = vtk.vtkGlyphSource2D()
        gs.SetGlyphTypeToCircle()
        gs.SetScale(25)
        gs.FilledOff()
        #gs.CrossOn()
        gs.Update()

        # Create a table of glyphs
        glypher = vtk.vtkGlyph2D()
        glypher.SetInputData(pd)
        glypher.SetSourceData(0, gs.GetOutput())
        glypher.SetIndexModeToScalar()
        glypher.SetRange(0, 1)
        glypher.SetScaleModeToDataScalingOff()
        mapper = vtk.vtkPolyDataMapper2D()
        mapper.SetInputConnection(glypher.GetOutputPort())
        mapper.SetScalarRange(0, 1)
        actor2D = vtk.vtkActor2D()
        actor2D.SetMapper(mapper)


        self.renderer.AddActor(self.actor)
        #self.renderer.AddActor(mapper)
        #self.renderer2.AddActor(actor3)


        self.renderer.SetBackground(self.bgcolor1)
        self.renderer.SetBackground2(self.bgcolor2)
        self.renderer.GradientBackgroundOn()

        self.renderer.SetActiveCamera(self.camera)
        self.renderer.ResetCamera()

        #self.camera.ZoomOff()        

        #self.renderer2.SetActiveCamera(self.camera)
        #self.renderer2.ResetCamera()
        #self.renderer2.SetBackground(0,0,0)

        #self.renderer2.GetProperty().SetBackgroundOpacity(0.5)
        #self.renderer2.SetLayer(1)


        #self.renderer2.Clear()

        self.areaPicker = vtk.vtkAreaPicker()
        self.renderWindowInteractor.SetPicker(self.areaPicker)

        self.style = MyInteractorStyle()
        self.style.SetPoints(self.input)
        self.style.SetDefaultRenderer(self.renderer)
        self.style.Data = self.idFilter.GetOutput()
        self.style.camera = self.camera
        self.style.node_ids = self.node_ids
        self.style.element_ids = self.element_ids
        self.style.node_count = self.node_count
        self.style.window = self
        self.style.print_message = self.ui.txt_msg.appendPlainText
        self.renderWindowInteractor.SetInteractorStyle(self.style)

        self.renderWindowInteractor.Start()

        # screenshot code:e
        #self.w2if = vtk_widget.vtkWindowToImageFilter()
        #self.w2if.SetInput(self.renWin)
        #self.w2if.Update()

        self.show()
        self.iren.Initialize()
        #self.iren.Start()



        # Setup Connections
        self.ui.btn_bgcolor1.clicked.connect(self.on_color1)
        self.ui.btn_bgcolor2.clicked.connect(self.on_color2)
        self.ui.btn_edgecolor.clicked.connect(self.on_edgecolor)
        self.ui.btn_elementcolor.clicked.connect(self.on_elementcolor)
        self.ui.btn_nofillededge.clicked.connect(self.on_nofillededge)
        self.ui.btn_switch.clicked.connect(self.on_switch)
        self.ui.btn_perspectivetoggle.clicked.connect(self.on_toggleperspective)
        self.ui.btn_saveimg.clicked.connect(self.on_saveimg)
        self.ui.btn_togglewire.clicked.connect(self.on_togglewire)

        # Setup a shortcuts
        self.setusrstyle = QtGui.QShortcut(self)
        self.setusrstyle.setKey(("CTRL+c"))
        self.setusrstyle.activated.connect(self.on_copyimg)