Example #1
0
def main():
    img_reader = ImageReaderFactory().GenerateImageReader(
        "./data/0000000000.png")

    img_actor = ImageActor(img_reader.GetOutputPort())

    contour_widget = vtk.vtkContourWidget()

    contourRepresentation = vtk.vtkOrientedGlyphContourRepresentation()
    contourRepresentation.GetLinesProperty().SetColor(1, 1, 0)

    contour_widget.SetRepresentation(contourRepresentation)
    contour_widget.GetContourRepresentation().SetLineInterpolator(
        vtk.vtkLinearContourLineInterpolator())

    numPts = 10

    points = vtk.vtkPoints()

    for i in range(numPts):
        angle = 2.0 * vtk.vtkMath.Pi() * i / numPts
        points.InsertNextPoint(
            [0.1 * math.cos(angle), 0.1 * math.sin(angle), -1.0])

    vertexIndices = vtk.vtkIdList()
    for i in range(numPts):
        vertexIndices.InsertNextId(i)
    # vertexIndices.InsertNextId(0)

    lines = vtk.vtkCellArray()
    lines.InsertNextCell(vertexIndices)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(lines)

    mapper = vtk.vtkPolyDataMapper2D()
    mapper.SetInputData(polydata)
    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderer.SetBackground(0.1, 0.2, 0.4)
    renderer.AddActor(img_actor.actor)
    renderer.AddActor(actor)

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

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

    style = vtk.vtkInteractorStyleJoystickCamera()
    interactor.SetInteractorStyle(style)

    contour_widget.SetInteractor(interactor)
    contour_widget.On()
    contour_widget.Initialize(polydata)
    renderer.ResetCamera()
    interactor.Start()
Example #2
0
 def InitInteractor(self, observer=None):
     """Sets up default VTK 3D interactor"""
     self.windowInteractor = vtk.vtkRenderWindowInteractor()
     self.windowInteractor.SetRenderWindow(self.renderWindow)
     style = vtk.vtkInteractorStyleJoystickCamera()
     self.windowInteractor.SetInteractorStyle(style)
     self.windowInteractor.Initialize()
     if observer != None:
         self.windowInteractor.AddObserver(vtk.vtkCommand.MouseMoveEvent,
                                           observer, 1)
Example #3
0
"""

import logging

from atom.api import Atom, Dict, Str, observe, Value, Int, Tuple, List
from functools import partial
import vtk

logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
                    level=logging.DEBUG)

INTERACTION_STYLES = {
    'TrackBallActor': vtk.vtkInteractorStyleTrackballActor(),
    'TrackBallCamera':
    vtk.vtkInteractorStyleTrackballCamera(),  # default style
    'JoystickCamera': vtk.vtkInteractorStyleJoystickCamera(),
    'JoystickActor': vtk.vtkInteractorStyleJoystickActor(),
    'Terrain': vtk.vtkInteractorStyleTerrain(),
}


class VTKRenderController(Atom):
    """ vtk render controller - supply renderers to VTKCanvas  """

    zoomFactor = Value()
    numOfRenderers = Int()
    callbacks = Dict()
    customPorts = Dict()
    customBackgrounds = Dict()
    interactorStyle = Str()
    style = Value()
Example #4
0
def _keypress(iren, event):
    # qt creates and passes a vtkGenericRenderWindowInteractor

    vp = settings.plotter_instance
    key = iren.GetKeySym()
    #print('Pressed key:', key, [vp])

    if key in ["q", "Q", "space", "Return"]:
        iren.ExitCallback()
        return

    elif key == "Escape":
        sys.stdout.flush()
        settings.plotter_instance.closeWindow()

    elif key in ["F1", "Pause"]:
        sys.stdout.flush()
        colors.printc('\n[F1] Execution aborted. Exiting python now.')
        settings.plotter_instance.closeWindow()
        sys.exit(0)

    elif key == "m":
        if vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetOpacity(0.02)
            bfp = vp.clickedActor.GetBackfaceProperty()
            if bfp and hasattr(vp.clickedActor, "_bfprop"):
                vp.clickedActor._bfprop = bfp  # save it
                vp.clickedActor.SetBackfaceProperty(None)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    a.GetProperty().SetOpacity(0.02)
                    bfp = a.GetBackfaceProperty()
                    if bfp and hasattr(a, "_bfprop"):
                        a._bfprop = bfp
                        a.SetBackfaceProperty(None)

    elif key == "comma":
        if vp.clickedActor in vp.getActors():
            ap = vp.clickedActor.GetProperty()
            aal = max([ap.GetOpacity() * 0.75, 0.01])
            ap.SetOpacity(aal)
            bfp = vp.clickedActor.GetBackfaceProperty()
            if bfp and hasattr(vp.clickedActor, "_bfprop"):
                vp.clickedActor._bfprop = bfp
                vp.clickedActor.SetBackfaceProperty(None)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    ap = a.GetProperty()
                    aal = max([ap.GetOpacity() * 0.75, 0.01])
                    ap.SetOpacity(aal)
                    bfp = a.GetBackfaceProperty()
                    if bfp and hasattr(a, "_bfprop"):
                        a._bfprop = bfp
                        a.SetBackfaceProperty(None)

    elif key == "period":
        if vp.clickedActor in vp.getActors():
            ap = vp.clickedActor.GetProperty()
            aal = min([ap.GetOpacity() * 1.25, 1.0])
            ap.SetOpacity(aal)
            if aal == 1 and hasattr(vp.clickedActor,
                                    "_bfprop") and vp.clickedActor._bfprop:
                # put back
                vp.clickedActor.SetBackfaceProperty(vp.clickedActor._bfprop)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    ap = a.GetProperty()
                    aal = min([ap.GetOpacity() * 1.25, 1.0])
                    ap.SetOpacity(aal)
                    if aal == 1 and hasattr(a, "_bfprop") and a._bfprop:
                        a.SetBackfaceProperty(a._bfprop)

    elif key == "slash":
        if vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetOpacity(1)
            if hasattr(vp.clickedActor, "_bfprop") and vp.clickedActor._bfprop:
                vp.clickedActor.SetBackfaceProperty(vp.clickedActor._bfprop)
        else:
            for a in vp.getActors():
                if a.GetPickable():
                    a.GetProperty().SetOpacity(1)
                    if hasattr(a, "_bfprop") and a._bfprop:
                        a.clickedActor.SetBackfaceProperty(a._bfprop)

    elif key == "P":
        if vp.clickedActor in vp.getActors():
            acts = [vp.clickedActor]
        else:
            acts = vp.getActors()
        for ia in acts:
            if ia.GetPickable():
                try:
                    ps = ia.GetProperty().GetPointSize()
                    if ps > 1:
                        ia.GetProperty().SetPointSize(ps - 1)
                    ia.GetProperty().SetRepresentationToPoints()
                except AttributeError:
                    pass

    elif key == "p":
        if vp.clickedActor in vp.getActors():
            acts = [vp.clickedActor]
        else:
            acts = vp.getActors()
        for ia in acts:
            if ia.GetPickable():
                try:
                    ps = ia.GetProperty().GetPointSize()
                    ia.GetProperty().SetPointSize(ps + 2)
                    ia.GetProperty().SetRepresentationToPoints()
                except AttributeError:
                    pass

    elif key == "w":
        if vp.clickedActor and vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetRepresentationToWireframe()
        else:
            for a in vp.getActors():
                if a and a.GetPickable():
                    if a.GetProperty().GetRepresentation() == 1:  # toggle
                        a.GetProperty().SetRepresentationToSurface()
                    else:
                        a.GetProperty().SetRepresentationToWireframe()

    elif key == "r":
        vp.renderer.ResetCamera()

    #############################################################
    ### now intercept custom observer ###########################
    #############################################################
    if vp.keyPressFunction:
        if key not in ["Shift_L", "Control_L", "Super_L", "Alt_L"]:
            if key not in ["Shift_R", "Control_R", "Super_R", "Alt_R"]:
                vp.verbose = False
                vp.keyPressFunction(key)
                return

    if key == "h":
        from vtkplotter.docs import tips

        tips()
        return

    if key == "a":
        iren.ExitCallback()
        cur = iren.GetInteractorStyle()
        if isinstance(cur, vtk.vtkInteractorStyleTrackballCamera):
            print("\nInteractor style changed to TrackballActor")
            print("  you can now move and rotate individual meshes:")
            print("  press X twice to save the repositioned mesh,")
            print("  press 'a' to go back to normal style.")
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballActor())
        else:
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        iren.Start()
        return

    if key == "j":
        iren.ExitCallback()
        cur = iren.GetInteractorStyle()
        if isinstance(cur, vtk.vtkInteractorStyleJoystickCamera):
            iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        else:
            print("\nInteractor style changed to Joystick,", end="")
            print(" press j to go back to normal.")
            iren.SetInteractorStyle(vtk.vtkInteractorStyleJoystickCamera())
        iren.Start()
        return

    if key == "S":
        screenshot("screenshot.png")
        colors.printc("~camera Saved rendering window as screenshot.png",
                      c="blue")
        return

    if key == "C":
        cam = vp.renderer.GetActiveCamera()
        print('\n### Example code to position this vtkCamera:')
        print('vp = vtkplotter.Plotter()\n...')
        print('vp.camera.SetPosition(',
              [round(e, 3) for e in cam.GetPosition()], ')')
        print('vp.camera.SetFocalPoint(',
              [round(e, 3) for e in cam.GetFocalPoint()], ')')
        print('vp.camera.SetViewUp(', [round(e, 3) for e in cam.GetViewUp()],
              ')')
        print('vp.camera.SetDistance(', round(cam.GetDistance(), 3), ')')
        print('vp.camera.SetClippingRange(',
              [round(e, 3) for e in cam.GetClippingRange()], ')')
        return

    if key == "s":
        if vp.clickedActor and vp.clickedActor in vp.getActors():
            vp.clickedActor.GetProperty().SetRepresentationToSurface()
        else:
            for a in vp.getActors():
                if a and a.GetPickable():
                    a.GetProperty().SetRepresentationToSurface()

    elif key == "V":
        if not (vp.verbose):
            vp._tips()
        vp.verbose = not (vp.verbose)
        print("Verbose: ", vp.verbose)

    elif key == "1":
        vp.icol += 1
        if vp.clickedActor and hasattr(vp.clickedActor, "GetProperty"):
            vp.clickedActor.GetMapper().ScalarVisibilityOff()
            vp.clickedActor.GetProperty().SetColor(colors.colors1[(vp.icol) %
                                                                  10])
        else:
            for i, ia in enumerate(vp.getActors()):
                if not ia.GetPickable():
                    continue
                ia.GetProperty().SetColor(colors.colors1[(i + vp.icol) % 10])
                ia.GetMapper().ScalarVisibilityOff()
        addons.addLegend()

    elif key == "2":
        vp.icol += 1
        if vp.clickedActor and hasattr(vp.clickedActor, "GetProperty"):
            vp.clickedActor.GetMapper().ScalarVisibilityOff()
            vp.clickedActor.GetProperty().SetColor(colors.colors2[(vp.icol) %
                                                                  10])
        else:
            for i, ia in enumerate(vp.getActors()):
                if not ia.GetPickable():
                    continue
                ia.GetProperty().SetColor(colors.colors2[(i + vp.icol) % 10])
                ia.GetMapper().ScalarVisibilityOff()
        addons.addLegend()

    elif key == "3":
        c = colors.getColor("gold")
        acs = vp.getActors()
        if len(acs) == 0: return
        alpha = 1.0 / len(acs)
        for ia in acs:
            if not ia.GetPickable():
                continue
            ia.GetProperty().SetColor(c)
            ia.GetProperty().SetOpacity(alpha)
            ia.GetMapper().ScalarVisibilityOff()
        addons.addLegend()

    elif key == "4":
        for ia in vp.getActors():
            if not ia.GetPickable():
                continue
            if isinstance(ia, Actor):
                iascals = ia.scalars()
                if len(iascals):
                    stype, sname = iascals[ia._scals_idx]
                    if "ormal" not in sname:  # exclude normals
                        ia.scalars(ia._scals_idx)
                        ia.GetMapper().ScalarVisibilityOn()
                        colors.printc("..active scalars set to:",
                                      sname,
                                      "\ttype:",
                                      stype,
                                      c='g',
                                      bold=0)
                    ia._scals_idx += 1
                    if ia._scals_idx >= len(iascals):
                        ia._scals_idx = 0
        addons.addLegend()

    elif key == "5":
        bgc = numpy.array(vp.renderer.GetBackground()).sum() / 3
        if bgc <= 0:
            bgc = 0.223
        elif 0 < bgc < 1:
            bgc = 1
        else:
            bgc = 0
        vp.renderer.SetBackground(bgc, bgc, bgc)

    elif "KP_" in key:  # change axes style
        asso = {
            "KP_Insert": 0,
            "KP_0": 0,
            "KP_End": 1,
            "KP_1": 1,
            "KP_Down": 2,
            "KP_2": 2,
            "KP_Next": 3,
            "KP_3": 3,
            "KP_Left": 4,
            "KP_4": 4,
            "KP_Begin": 5,
            "KP_5": 5,
            "KP_Right": 6,
            "KP_6": 6,
            "KP_Home": 7,
            "KP_7": 7,
            "KP_Up": 8,
            "KP_8": 8,
            "KP_Prior": 9,
            "KP_9": 9,
        }
        clickedr = vp.renderers.index(vp.renderer)
        if key in asso.keys():
            if vp.axes_instances[clickedr]:
                if hasattr(vp.axes_instances[clickedr],
                           "EnabledOff"):  # widget
                    vp.axes_instances[clickedr].EnabledOff()
                else:
                    vp.renderer.RemoveActor(vp.axes_instances[clickedr])
                vp.axes_instances[clickedr] = None
            addons.addAxes(axtype=asso[key], c=None)
            vp.interactor.Render()

    elif key in ["k", "K"]:
        for a in vp.getActors():
            ptdata = a.GetMapper().GetInput().GetPointData()
            cldata = a.GetMapper().GetInput().GetCellData()

            arrtypes = dict()
            arrtypes[vtk.VTK_UNSIGNED_CHAR] = "UNSIGNED_CHAR"
            arrtypes[vtk.VTK_UNSIGNED_INT] = "UNSIGNED_INT"
            arrtypes[vtk.VTK_FLOAT] = "FLOAT"
            arrtypes[vtk.VTK_DOUBLE] = "DOUBLE"
            foundarr = 0

            if key == "k":
                for i in range(ptdata.GetNumberOfArrays()):
                    name = ptdata.GetArrayName(i)
                    if name == "Normals":
                        continue
                    ptdata.SetActiveScalars(name)
                    foundarr = 1
                if not foundarr:
                    print("No vtkArray is associated to points", end="")
                    if hasattr(a, "_legend"):
                        print(" for actor:", a._legend)
                    else:
                        print()

            if key == "K":
                for i in range(cldata.GetNumberOfArrays()):
                    name = cldata.GetArrayName(i)
                    if name == "Normals":
                        continue
                    cldata.SetActiveScalars(name)
                    foundarr = 1
                if not foundarr:
                    print("No vtkArray is associated to cells", end="")
                    if hasattr(a, "_legend"):
                        print(" for actor:", a._legend)
                    else:
                        print()

            a.GetMapper().ScalarVisibilityOn()

    elif key == "l":
        if vp.clickedActor in vp.getActors():
            acts = [vp.clickedActor]
        else:
            acts = vp.getActors()
        for ia in acts:
            if not ia.GetPickable():
                continue
            try:
                ev = ia.GetProperty().GetEdgeVisibility()
                ia.GetProperty().SetEdgeVisibility(not ev)
                ia.GetProperty().SetRepresentationToSurface()
                ia.GetProperty().SetLineWidth(0.1)
            except AttributeError:
                pass

    elif key == "n":  # show normals to an actor
        from vtkplotter.analysis import normalLines

        if vp.clickedActor in vp.getActors():
            if vp.clickedActor.GetPickable():
                vp.renderer.AddActor(normalLines(vp.clickedActor))
                iren.Render()
        else:
            print("Click an actor and press n to add normals.")

    elif key == "x":
        if vp.justremoved is None:
            if vp.clickedActor in vp.getActors() or isinstance(
                    vp.clickedActor, vtk.vtkAssembly):
                vp.justremoved = vp.clickedActor
                vp.renderer.RemoveActor(vp.clickedActor)
            if hasattr(vp.clickedActor, '_legend') and vp.clickedActor._legend:
                print('...removing actor: ' + str(vp.clickedActor._legend) +
                      ', press x to put it back')
            else:
                print("Click an actor and press x to toggle it.")
        else:
            vp.renderer.AddActor(vp.justremoved)
            vp.renderer.Render()
            vp.justremoved = None
        addons.addLegend()

    elif key == "X":
        if vp.clickedActor:
            if not vp.cutterWidget:
                addons.addCutterTool(vp.clickedActor)
            else:
                fname = "clipped.vtk"
                confilter = vtk.vtkPolyDataConnectivityFilter()
                if isinstance(vp.clickedActor, vtk.vtkActor):
                    confilter.SetInputData(
                        vp.clickedActor.GetMapper().GetInput())
                elif isinstance(vp.clickedActor, vtk.vtkAssembly):
                    act = vp.clickedActor.getActors()[0]
                    confilter.SetInputData(act.GetMapper().GetInput())
                else:
                    confilter.SetInputData(vp.clickedActor.polydata(True))
                confilter.SetExtractionModeToLargestRegion()
                confilter.Update()
                cpd = vtk.vtkCleanPolyData()
                cpd.SetInputData(confilter.GetOutput())
                cpd.Update()
                w = vtk.vtkPolyDataWriter()
                w.SetInputData(cpd.GetOutput())
                w.SetFileName(fname)
                w.Write()
                colors.printc("~save Saved file:", fname, c="m")
                vp.cutterWidget.Off()
                vp.cutterWidget = None
        else:
            for a in vp.actors:
                if isinstance(a, vtk.vtkVolume):
                    addons.addCutterTool(a)
                    return

            colors.printc(
                "Click an actor and press X to open the cutter box widget.",
                c=4)

    elif key == "i":  # print info
        if vp.clickedActor:
            utils.printInfo(vp.clickedActor)
        else:
            utils.printInfo(vp)

    if iren:
        iren.Render()
def plotSurface(domain):
 
    domain.GetOutput().GetPointData().SetActiveScalars('TS')
    
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfColors(16)
    lut.SetHueRange(2/3,0.0)
    #lut.SetValueRange (270, 273);
    lut.SetNanColor(1,1,1,0.5)
    lut.SetNumberOfTableValues(3)
    lut.SetNumberOfColors(16)
    lut.Build()

    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    WIDTH=1200
    HEIGHT=1200
    renWin.SetSize(WIDTH,HEIGHT)
     
    # create a renderwindowinteractor
    joystickStyle = vtk.vtkInteractorStyleJoystickCamera()
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetInteractorStyle(joystickStyle)

    # mapper
    coneMapper = vtk.vtkDataSetMapper()
    coneMapper.SetInputData(domain.GetOutput())
    coneMapper.SetScalarModeToUsePointData()
    coneMapper.ScalarVisibilityOn()
    coneMapper.SetLookupTable(lut)
    coneMapper.SetScalarRange(domain.GetOutput().GetPointData().GetArray("TS").GetRange())

    # actor
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.SetScale(1,1,50)
    coneActor.GetProperty().SetEdgeColor(0.7,0.7,0.7)
    #coneActor.GetProperty().EdgeVisibilityOn()
    coneActor.GetProperty().SetAmbient(0.0)
    coneActor.GetProperty().SetSpecularPower(0)
    coneActor.GetProperty().SetDiffuse(1)

    cam = vtk.vtkCamera()
    cam.SetPosition(10.89,46.83,0.07)
    #cam.SetPosition(10.89,46.83,0.08)
    cam.SetFocalPoint(10.82,46.83,0.02)
    cam.SetViewUp(0,0,1)

    # assign actor to the renderer
    ren.SetBackground(1,1,1)
    ren.AddActor(coneActor)
    ren.SetActiveCamera(cam)
    ren.ResetCamera()

    # enable user interface interactor
    #iren.Initialize()
    renWin.OffScreenRenderingOn()
    renWin.Render()
    #iren.Start()
   
    renderLarge = vtk.vtkRenderLargeImage()
    renderLarge.SetInput(ren)
    renderLarge.SetMagnification(5)

#    w2if = vtk.vtkWindowToImageFilter()
#    w2if.SetInputConnection(renderLarge.GetOutputPort())
#    w2if.Update()

    writer = vtk.vtkPNGWriter()
    writer.SetInputConnection(renderLarge.GetOutputPort())
    writer.SetFileName('cosipy.png')
    writer.Write()
Example #6
0
    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)
Example #7
0
"""

import logging

from atom.api import Atom, Dict, Str, observe, Value, Int, Tuple, List
from functools import partial
import vtk


logging.basicConfig(format="%(asctime)s: %(levelname)s: %(message)s", level=logging.DEBUG)


INTERACTION_STYLES = {
    "TrackBallActor": vtk.vtkInteractorStyleTrackballActor(),
    "TrackBallCamera": vtk.vtkInteractorStyleTrackballCamera(),  # default style
    "JoystickCamera": vtk.vtkInteractorStyleJoystickCamera(),
    "JoystickActor": vtk.vtkInteractorStyleJoystickActor(),
    "Terrain": vtk.vtkInteractorStyleTerrain(),
}


class VTKRenderController(Atom):
    """ vtk render controller - supply renderers to VTKCanvas  """

    zoomFactor = Value()
    numOfRenderers = Int()
    callbacks = Dict()
    customPorts = Dict()
    customBackgrounds = Dict()
    interactorStyle = Str()
    style = Value()