def zoomToRubberband(self):
        """
		Zoom to rubberband
		"""
        self.rubberband = 1
        self.oldStyle = self.iren.GetInteractorStyle()
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandZoom())
예제 #2
0
    def SetInteractorStyle(self, state):
        action = {
            const.STATE_PAN: {
                "MouseMoveEvent": self.OnPanMove,
                "LeftButtonPressEvent": self.OnPanClick,
                "LeftButtonReleaseEvent": self.OnReleasePanClick,
            },
            const.STATE_ZOOM: {
                "MouseMoveEvent": self.OnZoomMove,
                "LeftButtonPressEvent": self.OnZoomClick,
                "LeftButtonReleaseEvent": self.OnReleaseZoomClick,
            },
            const.STATE_SPIN: {
                "MouseMoveEvent": self.OnSpinMove,
                "LeftButtonPressEvent": self.OnSpinClick,
                "LeftButtonReleaseEvent": self.OnReleaseSpinClick,
            },
            const.STATE_WL: {
                "MouseMoveEvent": self.OnWindowLevelMove,
                "LeftButtonPressEvent": self.OnWindowLevelClick,
                "LeftButtonReleaseEvent": self.OnWindowLevelRelease,
            },
            const.STATE_DEFAULT: {},
            const.VOLUME_STATE_SEED: {"LeftButtonPressEvent": self.OnInsertSeed},
            const.STATE_MEASURE_DISTANCE: {"LeftButtonPressEvent": self.OnInsertLinearMeasurePoint},
            const.STATE_MEASURE_ANGLE: {"LeftButtonPressEvent": self.OnInsertAngularMeasurePoint},
        }

        if self._last_state in (const.STATE_MEASURE_DISTANCE, const.STATE_MEASURE_ANGLE):
            if self.measures and not self.measures[-1].text_actor:
                del self.measures[-1]

        if state == const.STATE_WL:
            self.on_wl = True
            if self.raycasting_volume:
                self.text.Show()
                self.interactor.Render()
        else:
            self.on_wl = False
            self.text.Hide()
            self.interactor.Render()

        if state in (const.STATE_MEASURE_DISTANCE, const.STATE_MEASURE_ANGLE):
            self.interactor.SetPicker(self.measure_picker)

        if state == const.STATE_ZOOM_SL:
            style = vtk.vtkInteractorStyleRubberBandZoom()
            self.interactor.SetInteractorStyle(style)
            self.style = style
        else:
            style = vtk.vtkInteractorStyleTrackballCamera()
            self.interactor.SetInteractorStyle(style)
            self.style = style

            # Check each event available for each mode
            for event in action[state]:
                # Bind event
                style.AddObserver(event, action[state][event])

        self._last_state = state
예제 #3
0
    def zoomToRubberband(self):
        """
		Zoom to rubberband
		"""
        self.rubberband = 1
        self.oldStyle = self.iren.GetInteractorStyle()
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandZoom())
예제 #4
0
    def initPipeline(self):
        try:
            if self.pipelineInitialized:
                # default state
                self.style.LockAspectToViewportOff()
                self.style.CenterAtStartPositionOff()
                self.style.UseDollyForPerspectiveProjectionOn()

                # reset camera too
                self.renderer.ResetCamera()
                self.renderWindow.Render()
        except AttributeError:
            pass

        self.pipelineInitialized = True

        self.sphere = vtk.vtkSphereSource()
        self.idFilter = vtk.vtkIdFilter()
        self.mapper = vtk.vtkPolyDataMapper()
        self.actor = vtk.vtkActor()

        self.idFilter.PointIdsOff()
        self.idFilter.CellIdsOn()
        self.idFilter.SetInputConnection(self.sphere.GetOutputPort())

        self.mapper.SetInputConnection(self.idFilter.GetOutputPort())
        self.mapper.SetColorModeToMapScalars()
        self.mapper.SetScalarModeToUseCellFieldData()
        self.mapper.SelectColorArray("vtkIdFilter_Ids")
        self.mapper.UseLookupTableScalarRangeOff()
        self.mapper.SetScalarRange(0, 95)
        self.actor.SetMapper(self.mapper)

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

        self.renderWindow = vtk.vtkRenderWindow()
        self.renderWindow.AddRenderer(self.renderer)

        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renderWindow)

        self.style = vtk.vtkInteractorStyleRubberBandZoom()
        self.iren.SetInteractorStyle(self.style)

        self.renderer.GetActiveCamera().SetPosition(0, 0, -1)
        self.renderer.ResetCamera()
        self.renderWindow.Render()
    def initPipeline(self):
        try:
            if self.pipelineInitialized:
                # default state
                self.style.LockAspectToViewportOff()
                self.style.CenterAtStartPositionOff()
                self.style.UseDollyForPerspectiveProjectionOn()

                # reset camera too
                self.renderer.ResetCamera()
                self.renderWindow.Render()
        except AttributeError:
            pass

        self.pipelineInitialized = True

        self.sphere = vtk.vtkSphereSource()
        self.idFilter = vtk.vtkIdFilter()
        self.mapper = vtk.vtkPolyDataMapper()
        self.actor = vtk.vtkActor()

        self.idFilter.PointIdsOff()
        self.idFilter.CellIdsOn()
        self.idFilter.SetInputConnection(self.sphere.GetOutputPort())

        self.mapper.SetInputConnection(self.idFilter.GetOutputPort())
        self.mapper.SetColorModeToMapScalars()
        self.mapper.SetScalarModeToUseCellFieldData()
        self.mapper.SelectColorArray("vtkIdFilter_Ids")
        self.mapper.UseLookupTableScalarRangeOff()
        self.mapper.SetScalarRange(0, 95)
        self.actor.SetMapper(self.mapper)

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

        self.renderWindow = vtk.vtkRenderWindow()
        self.renderWindow.AddRenderer(self.renderer)

        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renderWindow)

        self.style = vtk.vtkInteractorStyleRubberBandZoom()
        self.iren.SetInteractorStyle(self.style)

        self.renderer.GetActiveCamera().SetPosition(0, 0, -1)
        self.renderer.ResetCamera()
        self.renderWindow.Render()
# Set up the pipeline
reader = vtk.vtkTIFFReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
reader.SetOrientationType(4)
ia = vtk.vtkImageActor()
ia.GetMapper().SetInputConnection(reader.GetOutputPort())
ren = vtk.vtkRenderer()
ren.AddActor(ia)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(400, 400)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
rbz = vtk.vtkInteractorStyleRubberBandZoom()
rbz.SetInteractor(iren)
iren.SetInteractorStyle(rbz)
renWin.Render()
# Test style
iren.SetEventInformationFlipY(250, 250, 0, 0, "0", 0, "0")
iren.InvokeEvent("LeftButtonPressEvent")
iren.SetEventInformationFlipY(100, 100, 0, 0, "0", 0, "0")
iren.InvokeEvent("MouseMoveEvent")
iren.InvokeEvent("LeftButtonReleaseEvent")
# --- end of script --
# Set up the pipeline
reader = vtk.vtkTIFFReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
reader.SetOrientationType(4)
ia = vtk.vtkImageActor()
ia.GetMapper().SetInputConnection(reader.GetOutputPort())
ren = vtk.vtkRenderer()
ren.AddActor(ia)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(400,400)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
rbz = vtk.vtkInteractorStyleRubberBandZoom()
rbz.SetInteractor(iren)
iren.SetInteractorStyle(rbz)
renWin.Render()
# Test style
iren.SetEventInformationFlipY(250,250,0,0,"0",0,"0")
iren.InvokeEvent("LeftButtonPressEvent")
iren.SetEventInformationFlipY(100,100,0,0,"0",0,"0")
iren.InvokeEvent("MouseMoveEvent")
iren.InvokeEvent("LeftButtonReleaseEvent")
# --- end of script --
예제 #8
0
    def SetInteractorStyle(self, state):
        action = {
              const.STATE_PAN:
                    {
                    "MouseMoveEvent": self.OnPanMove,
                    "LeftButtonPressEvent": self.OnPanClick,
                    "LeftButtonReleaseEvent": self.OnReleasePanClick
                    },
              const.STATE_ZOOM:
                    {
                    "MouseMoveEvent": self.OnZoomMove,
                    "LeftButtonPressEvent": self.OnZoomClick,
                    "LeftButtonReleaseEvent": self.OnReleaseZoomClick,
                    },
              const.STATE_SPIN:
                    {
                    "MouseMoveEvent": self.OnSpinMove,
                    "LeftButtonPressEvent": self.OnSpinClick,
                    "LeftButtonReleaseEvent": self.OnReleaseSpinClick,
                    },
              const.STATE_WL:
                    { 
                    "MouseMoveEvent": self.OnWindowLevelMove,
                    "LeftButtonPressEvent": self.OnWindowLevelClick,
                    "LeftButtonReleaseEvent":self.OnWindowLevelRelease
                    },
              const.STATE_DEFAULT:
                    {
                    },
              const.VOLUME_STATE_SEED:
                    {
                    "LeftButtonPressEvent": self.OnInsertSeed
                    },
              const.STATE_MEASURE_DISTANCE:
                  {
                  "LeftButtonPressEvent": self.OnInsertLinearMeasurePoint
                  },
              const.STATE_MEASURE_ANGLE:
                  {
                  "LeftButtonPressEvent": self.OnInsertAngularMeasurePoint
                  }
              }

        if self._last_state in (const.STATE_MEASURE_DISTANCE,
                const.STATE_MEASURE_ANGLE):
            if self.measures and not self.measures[-1].text_actor:
                del self.measures[-1]

        if state == const.STATE_WL:
            self.on_wl = True
            if self.raycasting_volume:
                self.text.Show()
                self.interactor.Render()
        else:
            self.on_wl = False
            self.text.Hide()
            self.interactor.Render()

        if state in (const.STATE_MEASURE_DISTANCE,
                const.STATE_MEASURE_ANGLE):
            self.interactor.SetPicker(self.measure_picker)

        if (state == const.STATE_ZOOM_SL):
            style = vtk.vtkInteractorStyleRubberBandZoom()
            self.interactor.SetInteractorStyle(style)
            self.style = style
        else:
            style = vtk.vtkInteractorStyleTrackballCamera()
            self.interactor.SetInteractorStyle(style)
            self.style = style  

            # Check each event available for each mode
            for event in action[state]:
                # Bind event
                style.AddObserver(event,action[state][event])

        self._last_state = state
예제 #9
0
파일: plotter.py 프로젝트: ifve/vtkplotter
    def show(
        self, *actors, **options
        #        at=None,
        #        axes=None,
        #        c=None,
        #        alpha=None,
        #        wire=False,
        #        bc=None,
        #        resetcam=True,
        #        zoom=False,
        #        interactive=None,
        #        rate=None,
        #        viewup="",
        #        azimuth=0,
        #        elevation=0,
        #        roll=0,
        #        interactorStyle=0,
        #        q=False,
    ):
        """
        Render a list of actors.

        Allowed input objects are: ``filename``, ``vtkPolyData``, ``vtkActor``,
        ``vtkActor2D``, ``vtkImageActor``, ``vtkAssembly`` or ``vtkVolume``.

        If filename is given, its type is guessed based on its extension.
        Supported formats are:
        `vtu, vts, vtp, ply, obj, stl, 3ds, xml, neutral, gmsh, pcd, xyz, txt, byu,
        tif, slc, vti, mhd, png, jpg`.

        :param int at: number of the renderer to plot to, if more than one exists
        :param int axes: set the type of axes to be shown

              - 0,  no axes,
              - 1,  draw three gray grid walls
              - 2,  show cartesian axes from (0,0,0)
              - 3,  show positive range of cartesian axes from (0,0,0)
              - 4,  show a triad at bottom left
              - 5,  show a cube at bottom left
              - 6,  mark the corners of the bounding box
              - 7,  draw a simple ruler at the bottom of the window
              - 8,  show the ``vtkCubeAxesActor`` object,
              - 9,  show the bounding box outLine,
              - 10, show three circles representing the maximum bounding box

        :param c:     surface color, in rgb, hex or name formats
        :param bc:    set a color for the internal surface face
        :param bool wire:  show actor in wireframe representation
        :param float azimuth/elevation/roll:  move camera accordingly
        :param str viewup:  either ['x', 'y', 'z'] or a vector to set vertical direction
        :param bool resetcam:  re-adjust camera position to fit objects
        :param bool interactive:  pause and interact with window (True)
            or continue execution (False)
        :param float rate:  maximum rate of `show()` in Hertz
        :param int interactorStyle: set the type of interaction

            - 0, TrackballCamera
            - 1, TrackballActor
            - 2, JoystickCamera
            - 3, Unicam
            - 4, Flight
            - 5, RubberBand3D
            - 6, RubberBandZoom

        :param bool q:  force program to quit after `show()` command returns.
        """
        if not hasattr(self, 'window'):
            return

        at = options.pop("at", None)
        axes = options.pop("axes", None)
        c = options.pop("c", None)
        alpha = options.pop("alpha", None)
        wire = options.pop("wire", False)
        bc = options.pop("bc", None)
        resetcam = options.pop("resetcam", True)
        zoom = options.pop("zoom", False)
        interactive = options.pop("interactive", None)
        rate = options.pop("rate", None)
        viewup = options.pop("viewup", "")
        azimuth = options.pop("azimuth", 0)
        elevation = options.pop("elevation", 0)
        roll = options.pop("roll", 0)
        interactorStyle = options.pop("interactorStyle", 0)
        q = options.pop("q", False)

        if self.offscreen:
            interactive = False
            self.interactive = False

        def scan(wannabeacts):
            scannedacts = []
            if not utils.isSequence(wannabeacts):
                wannabeacts = [wannabeacts]
            for a in wannabeacts:  # scan content of list
                if isinstance(a, vtk.vtkActor):
                    scannedacts.append(a)
                    if hasattr(a, 'trail'
                               ) and a.trail and not a.trail in self.actors:
                        scannedacts.append(a.trail)
                elif isinstance(a, vtk.vtkAssembly):
                    scannedacts.append(a)
                    if a.trail and not a.trail in self.actors:
                        scannedacts.append(a.trail)
                elif isinstance(a, vtk.vtkActor2D):
                    if isinstance(a, vtk.vtkCornerAnnotation):
                        for a2 in settings.collectable_actors:
                            if isinstance(a2, vtk.vtkCornerAnnotation):
                                if at in a2.renderedAt:  # remove old message
                                    self.removeActor(a2)
                        scannedacts.append(a)
                elif isinstance(a, vtk.vtkImageActor):
                    scannedacts.append(a)
                elif isinstance(a, vtk.vtkVolume):
                    scannedacts.append(a)
                elif isinstance(a, vtk.vtkImageData):
                    scannedacts.append(Volume(a))
                elif isinstance(a, vtk.vtkPolyData):
                    scannedacts.append(Actor(a, c, alpha, wire, bc))
                elif isinstance(a, str):  # assume a filepath was given
                    out = vtkio.load(a, c, alpha, wire, bc)
                    if isinstance(out, str):
                        colors.printc("~times File not found:", out, c=1)
                        scannedacts.append(None)
                    else:
                        scannedacts.append(out)
                elif "dolfin" in str(type(a)):  # assume a dolfin.Mesh object
                    from vtkplotter.dolfin import MeshActor
                    out = MeshActor(a, c=c, alpha=alpha, wire=True, bc=bc)
                    scannedacts.append(out)
                elif a is None:
                    pass
                elif isinstance(a, vtk.vtkUnstructuredGrid):
                    gf = vtk.vtkGeometryFilter()
                    gf.SetInputData(a)
                    gf.Update()
                    scannedacts.append(
                        Actor(gf.GetOutput(), c, alpha, wire, bc))
                elif isinstance(a, vtk.vtkStructuredGrid):
                    gf = vtk.vtkGeometryFilter()
                    gf.SetInputData(a)
                    gf.Update()
                    scannedacts.append(
                        Actor(gf.GetOutput(), c, alpha, wire, bc))
                elif isinstance(a, vtk.vtkRectilinearGrid):
                    gf = vtk.vtkRectilinearGridGeometryFilter()
                    gf.SetInputData(a)
                    gf.Update()
                    scannedacts.append(
                        Actor(gf.GetOutput(), c, alpha, wire, bc))
                elif isinstance(a, vtk.vtkMultiBlockDataSet):
                    for i in range(a.GetNumberOfBlocks()):
                        b = a.GetBlock(i)
                        if isinstance(b, vtk.vtkPolyData):
                            scannedacts.append(Actor(b, c, alpha, wire, bc))
                        elif isinstance(b, vtk.vtkImageData):
                            scannedacts.append(Volume(b))
                else:
                    colors.printc("~!? Cannot understand input in show():",
                                  type(a),
                                  c=1)
                    scannedacts.append(None)
            return scannedacts

        if len(actors) == 0:
            actors = None
        elif len(actors) == 1:
            actors = actors[0]
        else:
            actors = utils.flatten(actors)

        if actors is not None:
            self.actors = []
            actors2show = scan(actors)
            for a in actors2show:
                if a not in self.actors:
                    self.actors.append(a)
        else:
            actors2show = scan(self.actors)
            self.actors = list(actors2show)

        if axes is not None:
            self.axes = axes

        if interactive is not None:
            self.interactive = interactive

        if at is None and len(self.renderers) > 1:
            # in case of multiple renderers a call to show w/o specifing
            # at which renderer will just render the whole thing and return
            if self.interactor:
                if zoom:
                    self.camera.Zoom(zoom)
                self.interactor.Render()
                if self.interactive:
                    self.interactor.Start()
                return

        if at is None:
            at = 0

        if at < len(self.renderers):
            self.renderer = self.renderers[at]
        else:
            colors.printc("~times Error in show(): wrong renderer index",
                          at,
                          c=1)
            return

        if not self.camera:
            self.camera = self.renderer.GetActiveCamera()

        self.camera.SetParallelProjection(self.infinity)

        if self.camThickness:
            self.camera.SetThickness(self.camThickness)

        if self.sharecam:
            for r in self.renderers:
                r.SetActiveCamera(self.camera)

        if len(self.renderers) == 1:
            self.renderer.SetActiveCamera(self.camera)

        # rendering
        for ia in actors2show:  # add the actors that are not already in scene
            if ia:
                if isinstance(ia, vtk.vtkVolume):
                    self.renderer.AddVolume(ia)
                else:
                    self.renderer.AddActor(ia)
                if hasattr(ia, 'renderedAt'):
                    ia.renderedAt.add(at)
            else:
                colors.printc(
                    "~lightning Warning: Invalid actor in actors list, skip.",
                    c=5)

        # remove the ones that are not in actors2show
        for ia in self.getActors(at):
            if ia not in actors2show:
                self.renderer.RemoveActor(ia)
                if hasattr(ia, 'renderedAt'):
                    ia.renderedAt.discard(at)

        for c in self.scalarbars:
            self.renderer.RemoveActor(c)
            if hasattr(c, 'renderedAt'):
                c.renderedAt.discard(at)

        if self.axes is not None:
            addons.addAxes()

        addons.addLegend()

        if self.showFrame and len(self.renderers) > 1:
            addons.addFrame()

        if resetcam or self.initializedIren == False:
            self.renderer.ResetCamera()

        if not self.initializedIren and self.interactor:
            self.initializedIren = True
            self.interactor.Initialize()
            self.interactor.RemoveObservers("CharEvent")

            if self.verbose and self.interactive:
                docs.onelinetip()

        self.initializedPlotter = True

        if zoom:
            self.camera.Zoom(zoom)
        if azimuth:
            self.camera.Azimuth(azimuth)
        if elevation:
            self.camera.Elevation(elevation)
        if roll:
            self.camera.Roll(roll)

        if len(viewup):
            if viewup == "x":
                viewup = [1, 0, 0]
            elif viewup == "y":
                viewup = [0, 1, 0]
            elif viewup == "z":
                viewup = [0, 0, 1]
                self.camera.Azimuth(60)
                self.camera.Elevation(30)
            self.camera.Azimuth(0.01)  # otherwise camera gets locked
            self.camera.SetViewUp(viewup)

        self.renderer.ResetCameraClippingRange()

        self.window.Render()

        scbflag = False
        for a in self.actors:
            if (hasattr(a, "scalarbar") and a.scalarbar is not None
                    and utils.isSequence(a.scalarbar)):
                if len(a.scalarbar) == 5:  # addScalarBar
                    s1, s2, s3, s4, s5 = a.scalarbar
                    sb = addons.addScalarBar(a, s1, s2, s3, s4, s5)
                    scbflag = True
                    a.scalarbar = sb  # save scalarbar actor
                elif len(a.scalarbar) == 10:  # addScalarBar3D
                    s0, s1, s2, s3, s4, s5, s6, s7, s8 = a.scalarbar
                    sb = addons.addScalarBar3D(a, at, s0, s1, s2, s3, s4, s5,
                                               s6, s7, s8)
                    scbflag = True
                    a.scalarbar = sb  # save scalarbar actor
        if scbflag:
            self.window.Render()

        if settings.allowInteraction and not self.offscreen:
            self.allowInteraction()

        if settings.interactorStyle is not None:
            interactorStyle = settings.interactorStyle

        if interactorStyle == 0 or interactorStyle == "TrackballCamera":
            pass  # do nothing
        elif interactorStyle == 1 or interactorStyle == "TrackballActor":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleTrackballActor())
        elif interactorStyle == 2 or interactorStyle == "JoystickCamera":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleJoystickCamera())
        elif interactorStyle == 3 or interactorStyle == "Unicam":
            self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleUnicam())
        elif interactorStyle == 4 or interactorStyle == "Flight":
            self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleFlight())
        elif interactorStyle == 5 or interactorStyle == "RubberBand3D":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleRubberBand3D())
        elif interactorStyle == 6 or interactorStyle == "RubberBandZoom":
            self.interactor.SetInteractorStyle(
                vtk.vtkInteractorStyleRubberBandZoom())

        if self.interactor and self.interactive:
            self.interactor.Start()

        if rate:
            if self.clock is None:  # set clock and limit rate
                self._clockt0 = time.time()
                self.clock = 0.0
            else:
                t = time.time() - self._clockt0
                elapsed = t - self.clock
                mint = 1.0 / rate
                if elapsed < mint:
                    time.sleep(mint - elapsed)
                self.clock = time.time() - self._clockt0

        if q:  # gracefully exit
            if self.verbose:
                print("q flag set to True. Exit.")
            sys.exit(0)