コード例 #1
0
    def do(self):
        vw = vtk.vtkButtonWidget()
        vr = vtk.vtkTexturedButtonRepresentation2D()

        vr.SetNumberOfStates(1)
        r = vtk.vtkPNGReader()
        r.SetFileName("tests/vtk_ui/Pepper.png")
        r.Update()
        image = r.GetOutput()
        vr.SetButtonTexture(0, image)
        vw.SetRepresentation(vr)

        w = vcs.vtk_ui.widget.Widget(self.inter, vw)
        w.show()

        width, height, _ = image.GetDimensions()
        bounds = (0, 0 + width, 0, height, 0, 0)
        vr.SetPlaceFactor(1)
        vr.PlaceWidget(bounds)

        w.detach()
        assert vr.GetRenderer() is None and vw.GetCurrentRenderer(
        ) is None, "Renderer is set after detach"
        assert vw.GetInteractor() is None, "Interactor set after detach"
        assert w.showing() == False, "Widget is flagged as Enabled"
        assert w not in vcs.vtk_ui.manager.get_manager(
            self.inter).widgets, "Widget still being managed"
        assert w.interactor is None, "Widget has a reference to interactor"
        self.passed = 0
コード例 #2
0
    def do_test(self):
        vw = vtk.vtkButtonWidget()
        vr = vtk.vtkTexturedButtonRepresentation2D()

        vr.SetNumberOfStates(1)
        r = vtk.vtkPNGReader()
        r.SetFileName("Pepper.png")
        r.Update()
        image = r.GetOutput()
        vr.SetButtonTexture(0, image)
        vw.SetRepresentation(vr)

        w = vcs.vtk_ui.widget.Widget(self.inter, vw)
        w.show()

        width, height, _ = image.GetDimensions()
        bounds = (0, 0 + width, 0, height, 0, 0)
        vr.SetPlaceFactor(1)
        vr.PlaceWidget(bounds)

        w.detach()
        assert vr.GetRenderer() is None and vw.GetCurrentRenderer() is None, "Renderer is set after detach"
        assert vw.GetInteractor() is None, "Interactor set after detach"
        assert w.showing() == False, "Widget is flagged as Enabled"
        assert w not in vcs.vtk_ui.manager.get_manager(self.inter).widgets, "Widget still being managed"
        assert w.interactor is None, "Widget has a reference to interactor"
        self.passed = 0
コード例 #3
0
ファイル: ListWidget.py プロジェクト: CDAT/UVIS_DV3D
    def getButtonRepresentation(self, **args):
        buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
        cmap_name = args.get('name', None)
        button_id = args.get('id', cmap_name)
        if cmap_name:
            buttonRepresentation.SetNumberOfStates(2)
            for image_index in range(2):
                image_data = self.getColorbarImage(cmap_name,
                                                   invert=(image_index == 1))
                buttonRepresentation.SetButtonTexture(image_index, image_data)


#         labels = args.get( 'labels', None )
#         if labels:
#             if self.textMapper == None:
#                 size = args.get( 'size', [ 30.0, 30.0 ] )
#                 self.textMapper = vtk.vtkFreeTypeUtilities()
#             nstates = len( labels )
#             buttonRepresentation.SetNumberOfStates(nstates)
#             tprop = vtk.vtkTextProperty()
#             for label_index in range( nstates ):
#                 texture = vtk.vtkImageData()
#                 label = labels[label_index]
#                 if button_id == None: button_id = label
#                 self.textRenderer.RenderString( tprop, label, 0, 0, texture )
#                 buttonRepresentation.SetButtonTexture( label_index, texture )
        return button_id, buttonRepresentation
コード例 #4
0
    def do_test(self):
        self.win.SetSize((100, 100))

        vw = vtk.vtkButtonWidget()
        vr = vtk.vtkTexturedButtonRepresentation2D()

        vr.SetNumberOfStates(1)
        r = vtk.vtkPNGReader()
        r.SetFileName("Pepper.png")
        r.Update()
        image = r.GetOutput()
        vr.SetButtonTexture(0, image)
        vw.SetRepresentation(vr)

        w = vcs.vtk_ui.widget.Widget(self.inter, vw)
        w.show()

        def dummy(*args, **kwargs):
            pass

        w.subscribe("StartInteractionEvent", dummy)

        # Make sure event was properly subscribed to
        assert "StartInteractionEvent" in w.subscriptions, "Event not in subscriptions"

        # Check observers of w for the tag in w.subscriptions
        tag = w.subscriptions["StartInteractionEvent"]
        c = vw.GetCommand(tag)
        assert c is not None, "Listener not attached to widget"

        try:
            w.subscribe("StartInteractionEvent", dummy)
            print "Failed to notice double event subscription on widget"
            return
        except KeyError:
            pass

        w.unsubscribe("StartInteractionEvent")
        assert "StartInteractionEvent" not in w.subscriptions, "Did not remove event from subscriptions on unsubscribe"

        # Test multiple unsubscriptions
        w.subscribe("EndInteractionEvent", dummy)
        w.subscribe("StartInteractionEvent", dummy)
        w.unsubscribe("StartInteractionEvent", "EndInteractionEvent")
        assert (
            "EndInteractionEvent" not in w.subscriptions and "StartInteractionEvent" not in w.subscriptions
        ), "Did not remove both events from widget subscriptions"

        try:
            w.unsubscribe("StartInteractionEvent")
            print "Failed to notice double unsubscribe on widget"
            return
        except KeyError:
            pass

        self.passed = 0
コード例 #5
0
    def do_test(self):
        self.win.SetSize((100, 100))

        vw = vtk.vtkButtonWidget()
        vr = vtk.vtkTexturedButtonRepresentation2D()

        vr.SetNumberOfStates(1)
        r = vtk.vtkPNGReader()
        r.SetFileName("Pepper.png")
        r.Update()
        image = r.GetOutput()
        vr.SetButtonTexture(0, image)
        vw.SetRepresentation(vr)

        w = vcs.vtk_ui.widget.Widget(self.inter, vw)
        w.show()

        def dummy(*args, **kwargs):
            pass

        w.subscribe("StartInteractionEvent", dummy)

        # Make sure event was properly subscribed to
        assert "StartInteractionEvent" in w.subscriptions, "Event not in subscriptions"

        # Check observers of w for the tag in w.subscriptions
        tag = w.subscriptions["StartInteractionEvent"]
        c = vw.GetCommand(tag)
        assert c is not None, "Listener not attached to widget"

        try:
            w.subscribe("StartInteractionEvent", dummy)
            print "Failed to notice double event subscription on widget"
            return
        except KeyError:
            pass

        w.unsubscribe("StartInteractionEvent")
        assert "StartInteractionEvent" not in w.subscriptions, "Did not remove event from subscriptions on unsubscribe"

        # Test multiple unsubscriptions
        w.subscribe("EndInteractionEvent", dummy)
        w.subscribe("StartInteractionEvent", dummy)
        w.unsubscribe("StartInteractionEvent", "EndInteractionEvent")
        assert "EndInteractionEvent" not in w.subscriptions and "StartInteractionEvent" not in w.subscriptions, "Did not remove both events from widget subscriptions"

        try:
            w.unsubscribe("StartInteractionEvent")
            print "Failed to notice double unsubscribe on widget"
            return
        except KeyError:
            pass

        self.passed = 0
コード例 #6
0
    def do(self):
        self.args = [
            'test_vtk_ui_widget_show.png', 'test_vtk_ui_widget_hide.png'
        ]
        self.win.SetSize((100, 100))

        vw = vtk.vtkButtonWidget()
        vr = vtk.vtkTexturedButtonRepresentation2D()

        vr.SetNumberOfStates(1)
        r = vtk.vtkPNGReader()
        r.SetFileName("tests/vtk_ui/Pepper.png")
        r.Update()
        image = r.GetOutput()
        vr.SetButtonTexture(0, image)
        vw.SetRepresentation(vr)

        w = vcs.vtk_ui.widget.Widget(self.inter, vw)
        w.show()

        width, height, _ = image.GetDimensions()
        bounds = (0, 0 + width, 0, height, 0, 0)
        vr.SetPlaceFactor(1)
        vr.PlaceWidget(bounds)

        self.test_file = "test_vtk_ui_widget_show.png"
        if self.args:
            self.passed = self.check_image(self.args[0])
            if self.passed == 1:
                print "Failed to show correctly"
                return
        else:
            vtk_ui_test.generate_png(self.win, self.test_file)

        assert w.showing(), "showing() thinks hidden while showing"

        w.hide()

        assert w.showing() == False, "showing() thinks showing while hidden"

        self.test_file = "test_vtk_ui_widget_hide.png"
        if len(self.args) > 1:
            self.passed = self.check_image(self.args[1])
            if self.passed == 1:
                print "Failed to hide correctly"
                return
        else:
            vtk_ui_test.generate_png(self.win, self.test_file)
        self.test_file = None
        self.passed = 0
コード例 #7
0
ファイル: ButtonBarWidget.py プロジェクト: doutriaux1/uvcdat
 def createButtonRepresentation(self, **args):
     self.buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
     self.buttonRepresentation.SetPlaceFactor( args.get( 'scale', 1 ) )
     self.numberOfImages = len( self.names )
     if self.numberOfImages:
         self.buttonRepresentation.SetNumberOfStates(self.numberOfImages)
         for button_index in range( self.numberOfImages ):                
             buttonFilePath = os.path.join( ButtonDir,  '.'.join( [ self.names[ button_index ], 'jpeg' ] ) )
             JPEGReader = vtk.vtkJPEGReader()
             JPEGReader.SetFileName ( buttonFilePath )
             JPEGReader.Update()
             image_data = JPEGReader.GetOutput()
             if self.image_size == None: self.image_size = image_data.GetDimensions()
             self.buttonRepresentation.SetButtonTexture( button_index, image_data )
             self.button_files.append( buttonFilePath )
         self.setToggleProps()
コード例 #8
0
    def do_test(self):
        self.win.SetSize((100, 100))

        vw = vtk.vtkButtonWidget()
        vr = vtk.vtkTexturedButtonRepresentation2D()

        vr.SetNumberOfStates(1)
        r = vtk.vtkPNGReader()
        r.SetFileName("Pepper.png")
        r.Update()
        image = r.GetOutput()
        vr.SetButtonTexture(0, image)
        vw.SetRepresentation(vr)

        w = vcs.vtk_ui.widget.Widget(self.inter, vw)
        w.show()

        width, height, _ = image.GetDimensions()
        bounds = (0, 0 + width, 0, height, 0, 0)
        vr.SetPlaceFactor(1)
        vr.PlaceWidget(bounds)

        self.test_file = "test_vtk_ui_widget_show.png"
        if self.args:
            self.passed = self.check_image(self.args[0])
            if self.passed == 1:
                print "Failed to show correctly"
                return
        else:
            generate_png(self.win, self.test_file)

        assert w.showing(), "showing() thinks hidden while showing"

        w.hide()

        assert w.showing() == False, "showing() thinks showing while hidden"

        self.test_file = "test_vtk_ui_widget_hide.png"
        if len(self.args) > 1:
            self.passed = self.check_image(self.args[1])
            if self.passed == 1:
                print "Failed to hide correctly"
                return
        else:
            generate_png(self.win, self.test_file)
        self.test_file = None
        self.passed = 0
コード例 #9
0
    def AddCornerButton(self, texture, cb=None):
        """
    Add corner button. TODO: Support callback argument
    """

        # Render to ensure viewport has the right size (it has not)
        buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
        buttonRepresentation.SetNumberOfStates(1)
        buttonRepresentation.SetButtonTexture(0, texture)
        self.buttonWidget = vtk.vtkButtonWidget()
        self.buttonWidget.SetInteractor(self.viewer.GetInteractor())
        self.buttonWidget.SetRepresentation(buttonRepresentation)

        self.buttonWidget.On()

        renWin = self.viewer.GetRenderWindow()
        renWin.AddObserver('ModifiedEvent', self.resizeCallback)
コード例 #10
0
 def createButtonRepresentation(self, **args):
     self.buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
     self.buttonRepresentation.SetPlaceFactor( args.get( 'scale', 1 ) )
     if self.names[0] == "Run":
         print "."
     self.numberOfImages = len( self.names )
     if self.numberOfImages:
         self.buttonRepresentation.SetNumberOfStates(self.numberOfImages)
         for button_index in range( self.numberOfImages ):                
             buttonFilePath = os.path.join( ButtonDir,  '.'.join( [ self.names[ button_index ], 'jpeg' ] ) )
             JPEGReader = vtk.vtkJPEGReader()
             JPEGReader.SetFileName ( buttonFilePath )
             JPEGReader.Update()
             image_data = JPEGReader.GetOutput()
             if self.image_size == None: self.image_size = image_data.GetDimensions()
             self.buttonRepresentation.SetButtonTexture( button_index, image_data )
             self.button_files.append( buttonFilePath )
         self.setToggleProps()
コード例 #11
0
    def AddCornerButton(self, texture0, texture1):
        """
    Add corner button. TODO: Support callback argument
    """

        # Render to ensure viewport has the right size (it has not)
        buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
        buttonRepresentation.SetNumberOfStates(2)
        buttonRepresentation.SetButtonTexture(0, texture0)
        buttonRepresentation.SetButtonTexture(1, texture1)
        buttonWidget = vtk.vtkButtonWidget()
        buttonWidget.SetInteractor(self.interactor)
        buttonWidget.SetRepresentation(buttonRepresentation)
        buttonWidget.AddObserver(vtk.vtkCommand.StateChangedEvent,
                                 self.onTogglePlanesClicked)
        buttonWidget.On()
        self.buttonWidgets.append(buttonWidget)

        renWin = self.interactor.GetRenderWindow()
        renWin.AddObserver('ModifiedEvent', self.resizeCallback)
コード例 #12
0
ファイル: ListWidget.py プロジェクト: NESII/uvcdat
    def getButtonRepresentation(self, **args):
        buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
        cmap_name = args.get( 'name', None )
        button_id = args.get( 'id', cmap_name )
        if cmap_name:
            buttonRepresentation.SetNumberOfStates(2)
            for image_index in range( 2 ):
                image_data = self.getColorbarImage( cmap_name, invert=(image_index==1) )
                buttonRepresentation.SetButtonTexture( image_index, image_data )
#         labels = args.get( 'labels', None )
#         if labels:
#             if self.textMapper == None:
#                 size = args.get( 'size', [ 30.0, 30.0 ] )
#                 self.textMapper = vtk.vtkFreeTypeUtilities()
#             nstates = len( labels )
#             buttonRepresentation.SetNumberOfStates(nstates)
#             tprop = vtk.vtkTextProperty()
#             for label_index in range( nstates ):
#                 texture = vtk.vtkImageData()
#                 label = labels[label_index]
#                 if button_id == None: button_id = label
#                 self.textRenderer.RenderString( tprop, label, 0, 0, texture )
#                 buttonRepresentation.SetButtonTexture( label_index, texture )
        return button_id, buttonRepresentation
コード例 #13
0
def button(iren,
           ren,
           callback,
           fname,
           right_normalized_pos=(.98, .9),
           size=(50, 50)):
    """ A textured two state button widget

    Parameters
    ----------
    iren : vtkRenderWindowInteractor
        Used to process events and handle them to the button. Can also be given
        by the attribute ``ShowManager.iren``.
    ren :  vtkRenderer or Renderer
        Used to update the slider's position when the window changes. Can also
        be given by the ``ShowManager.ren`` attribute.
    callback : function
        Function that has at least ``obj`` and ``event`` as parameters. It will
        be called when the button is pressed.
    fname : str
        PNG file path of the icon used for the button.
    right_normalized_pos : tuple
        2d tuple holding the normalized right (X, Y) position of the slider.
    size: tuple
        2d tuple holding the size of the slider in pixels.

    Returns
    -------
    button : ButtonWidget
        This object inherits from vtkButtonWidget and has an additional  method
        called ``place`` which allows to update the position of the slider
        if necessary. For example when the renderer size changes.

    Notes
    ------
    The button and slider widgets have similar positioning system. This enables
    the developers to create a HUD-like collections of buttons and sliders on
    the right side of the window that always stays in place when the dimensions
    of the window change.
    """

    image1 = vtk.vtkPNGReader()
    image1.SetFileName(fname)
    image1.Update()

    button_rep = vtk.vtkTexturedButtonRepresentation2D()
    button_rep.SetNumberOfStates(2)
    button_rep.SetButtonTexture(0, image1.GetOutput())
    button_rep.SetButtonTexture(1, image1.GetOutput())

    class ButtonWidget(vtk.vtkButtonWidget):
        def place(self, renderer):

            bds = button_display_coordinates(renderer, right_normalized_pos,
                                             size)
            self.GetRepresentation().SetPlaceFactor(1)
            self.GetRepresentation().PlaceWidget(bds)
            self.On()

    button = ButtonWidget()
    button.SetInteractor(iren)
    button.SetRepresentation(button_rep)
    button.AddObserver(vtk.vtkCommand.StateChangedEvent, callback)

    # Place widget after window resizing.
    def _place_widget(obj, event):
        button.place(ren)

    iren.GetRenderWindow().AddObserver(vtk.vtkCommand.StartEvent,
                                       _place_widget)
    iren.GetRenderWindow().AddObserver(vtk.vtkCommand.ModifiedEvent,
                                       _place_widget)

    return button
コード例 #14
0
    buttonImage = vtk.vtkImageData()
    freeType = vtk.vtkFreeTypeStringToImage()
    textProperty = vtk.vtkTextProperty()
    textProperty.SetColor(1.0, 1.0, 1.0)
    textProperty.SetFontSize(64)
    textProperty.SetFontFamilyToTimes()
    freeType.RenderString(textProperty, text, 120, buttonImage)
    return buttonImage


def quit_program(obj, event):
    quit()


quit_image = textImage("Quit")
buttonRep1 = vtk.vtkTexturedButtonRepresentation2D()
buttonRep1.SetNumberOfStates(2)
buttonRep1.SetButtonTexture(0, quit_image)
buttonRep1.SetButtonTexture(1, quit_image)
buttonRep1.PlaceWidget([0, 100, 0, 50, 0, 50])

buttonWidget1 = vtk.vtkButtonWidget()
buttonWidget1.SetInteractor(iact)
buttonWidget1.SetRepresentation(buttonRep1)
buttonWidget1.SetEnabled(True)
buttonWidget1.On()
buttonWidget1.AddObserver("StateChangedEvent", quit_program)
#end quit

#begin interp button
#toggle behavior booleon
コード例 #15
0
ファイル: button.py プロジェクト: devarajun/uvcdat
    def __init__(self, interactor, action=None, corner_radius=5, width=None, font="Arial",
                 height=None, left=0, top=0, image=None, label="", bgcolor=(.5, .5, .5), fgcolor=(1,1,1),
                 opacity=1, size=14, states = None, halign=LEFT_ALIGN, valign=CENTER_ALIGN, tooltip=None, tooltip_property=None):
        """
        @kwargs:
            action: A callback function that will receive the current state ID when the button is clicked.
            width: if width is None, use the size of the label to determine width
            height: if height is None, use the size of the label to determine height
            left: Distance from the left of the window to place the button
            top: Distance from the top of the window to place the button
            image: Icon to place on top of the background
            label: Default label to use for all states (if no states are provided, creates a state using defaults)
            bgcolor: Default background color of the button (if states do not provide a bgcolor, this one is used)
            fgcolor: Default font color of the label (if states do not provide an fgcolor, this one is used)
            opacity: Default opacity of button & label (if states do not provide an opacity, this one is used)
            size: Default font size of the label (if states do not provide a font size, this one is used)
            halign: If the button states have multiple widths (different labels/images), this will align them horizontally as specified
            valign: If the button states have multiple heights (labels with newlines, images), this will align them vertically as specified
        """

        self.width = width
        self.height = height
        self.left = left
        self.top = top
        self.radius = corner_radius
        self.action = action

        if halign not in (LEFT_ALIGN, RIGHT_ALIGN, CENTER_ALIGN):
            raise TypeError("halign must be one of LEFT_ALIGN, RIGHT_ALIGN, or CENTER_ALIGN")
        self.halign = halign

        if valign not in (TOP_ALIGN, BOTTOM_ALIGN, CENTER_ALIGN):
            raise TypeError("valign must be one of TOP_ALIGN, BOTTOM_ALIGN, or CENTER_ALIGN")
        self.valign = valign
        if image:
            self.image = load_image(image)
        else:
            self.image = None

        self.__placing__ = False

        text = states[0].label if states else label
        # Text widget will be placed over the button; clicks on it have to propogate down
        self.text_widget = Label(interactor, text, on_click = self.__advance__, size=size, font=font)

        self.label = label
        self.size = size
        self.opacity = opacity
        self.fgcolor = fgcolor
        self.bgcolor = bgcolor

        if states:
            self.states = states
        else:
            self.states = [ButtonState(label=label)]

        widget = vtk.vtkButtonWidget()
        widget.SetRepresentation(vtk.vtkTexturedButtonRepresentation2D())

        super(Button, self).__init__(interactor, widget)

        if tooltip:
            if tooltip_property is not None:
                tooltip_property.SetVerticalJustificationToTop()
            self.tooltip_label = Label(interactor, tooltip, textproperty=tooltip_property)
            self.hover_handler = self.interactor.AddObserver("MouseMoveEvent", self.hover)
            self.hover_timer = None
            self.timer_handler = self.interactor.AddObserver("TimerEvent", self.still_hovering)

        self.update()
        self.subscribe( 'StateChangedEvent', self.clicked)
コード例 #16
0
ファイル: button.py プロジェクト: dorukozturk/vcs
    def __init__(self,
                 interactor,
                 action=None,
                 corner_radius=5,
                 width=None,
                 font="Arial",
                 height=None,
                 left=0,
                 top=0,
                 image=None,
                 label="",
                 bgcolor=(.5, .5, .5),
                 fgcolor=(1, 1, 1),
                 opacity=1,
                 size=14,
                 states=None,
                 halign=LEFT_ALIGN,
                 valign=CENTER_ALIGN,
                 tooltip=None,
                 tooltip_property=None):
        """
        @kwargs:
            action: A callback function that will receive the current state ID when the button is clicked.
            width: if width is None, use the size of the label to determine width
            height: if height is None, use the size of the label to determine height
            left: Distance from the left of the window to place the button
            top: Distance from the top of the window to place the button
            image: Icon to place on top of the background
            label: Default label to use for all states (if no states are provided, creates a state using defaults)
            bgcolor: Default background color of the button (if states do not provide a bgcolor, this one is used)
            fgcolor: Default font color of the label (if states do not provide an fgcolor, this one is used)
            opacity: Default opacity of button & label (if states do not provide an opacity, this one is used)
            size: Default font size of the label (if states do not provide a font size, this one is used)
            halign: If the button states have multiple widths (different labels/images), this will align them horizontally as specified
            valign: If the button states have multiple heights (labels with newlines, images), this will align them vertically as specified
        """  # noqa

        self.width = width
        self.height = height
        self.left = left
        self.top = top
        self.radius = corner_radius
        self.action = action

        if halign not in (LEFT_ALIGN, RIGHT_ALIGN, CENTER_ALIGN):
            raise TypeError(
                "halign must be one of LEFT_ALIGN, RIGHT_ALIGN, or CENTER_ALIGN"
            )
        self.halign = halign

        if valign not in (TOP_ALIGN, BOTTOM_ALIGN, CENTER_ALIGN):
            raise TypeError(
                "valign must be one of TOP_ALIGN, BOTTOM_ALIGN, or CENTER_ALIGN"
            )
        self.valign = valign
        if image:
            self.image = load_image(image)
        else:
            self.image = None

        self.__placing__ = False

        text = states[0].label if states else label
        # Text widget will be placed over the button; clicks on it have to
        # propogate down
        self.text_widget = Label(interactor,
                                 text,
                                 on_click=self.__advance__,
                                 size=size,
                                 font=font)

        self.label = label
        self.size = size
        self.opacity = opacity
        self.fgcolor = fgcolor
        self.bgcolor = bgcolor

        if states:
            self.states = states
        else:
            self.states = [ButtonState(label=label)]

        widget = vtk.vtkButtonWidget()
        widget.SetRepresentation(vtk.vtkTexturedButtonRepresentation2D())

        super(Button, self).__init__(interactor, widget)

        if tooltip:
            if tooltip_property is not None:
                tooltip_property.SetVerticalJustificationToTop()
            self.tooltip_label = Label(interactor,
                                       tooltip,
                                       textproperty=tooltip_property)
            self.hover_handler = self.interactor.AddObserver(
                "MouseMoveEvent", self.hover)
            self.hover_timer = None
            self.timer_handler = self.interactor.AddObserver(
                "TimerEvent", self.still_hovering)

        self.update()
        self.subscribe('StateChangedEvent', self.clicked)
コード例 #17
0
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

# An interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

# Create two images for texture
image1 = vtk.vtkImageData()
image2 = vtk.vtkImageData()
CreateButtonOff(image1)
CreateButtonOn(image2)

# Create the widget and its representation
buttonRepresentation = vtk.vtkTexturedButtonRepresentation2D()
buttonRepresentation.SetNumberOfStates(2)
buttonRepresentation.SetButtonTexture(0, image1)
buttonRepresentation.SetButtonTexture(1, image2)

buttonWidget = vtk.vtkButtonWidget()
buttonWidget.SetInteractor(renderWindowInteractor)
buttonWidget.SetRepresentation(buttonRepresentation)


def try_callback(func, *args):
    """Wrap a given callback in a try statement."""
    import logging
    try:
        func(*args)
    except Exception as e:
コード例 #18
0
ファイル: om_display.py プロジェクト: dang-kai/openmeeg
def om_display_vtp(f, n = 0):
    """
    This function displays a VTK::vtp file generated with OpenMEEG.
    Such a file defines a polydata, containing points and triangles of several
    meshes which are labelled through a vtkAbstractArray (Strings) associated to
    the cells (mesh names).
    Results of the forward problem (or a cortical mapping) can be seen thanks to
    arrays associated to points and cells (respectively potentials and normals
    currents).
    """
    welcome = """Welcome\n\n
    Switch the button: To either see Potentials (on points) or Currents (on triangles)\n
    Move the slider to see all sources (columns of the input matrix)\n
    Press 'r': To select points/cells.\n"""

    # This callback function does updates the mappers for where n is the slider value
    def CleanPickData(object, event):
        for i in range(4):
            rens[i].RemoveActor(selactor)
        if buttonWidget.GetRepresentation().GetState():
            PickData(object, event, selactor, 1, view, text_init)
        else:
            PickData(object, event, selactor, 0, view, text_init)
    def SelectSource(object, event): # object will be the slider2D
        slidervalue = int(round(object.GetRepresentation().GetValue()))
        for i in range(4):
            mappers[i].GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue))
            mappers[i].GetInput().GetCellData().SetActiveScalars("Currents-"+str(slidervalue))
            renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue))
            UpdateColorBar(colorBars[i], mappers[i])

    # This callback function does updates the Scalar Mode To Use
    def SelectMode(object, event):
        # object will be the buttonWidget
        for i in range(4):
            if (object.GetRepresentation().GetState()):
                mappers[i].SetScalarModeToUseCellData()
                renWin.SetWindowName(renWin.GetWindowName().replace('Potentials','Currents'))
            else:
                mappers[i].SetScalarModeToUsePointData()
                renWin.SetWindowName(renWin.GetWindowName().replace('Currents','Potentials'))
            UpdateColorBar(colorBars[i], mappers[i])

    # A window with an interactor
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick())
    # A picker (to pick points/cells)
    picker = vtk.vtkRenderedAreaPicker()
    iren.SetPicker(picker)
    # Read the input file
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(f); reader.Update()
    poly = reader.GetOutput()
    renWin.SetWindowName(f+' Potentials-'+str(n))
    # determine the number of sources
    nb_sources = 0
    for i in range(poly.GetPointData().GetNumberOfArrays()):
        if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)):
            nb_sources += 1
    if n < nb_sources:
        poly.GetPointData().SetActiveScalars('Potentials-'+str(n))
        poly.GetCellData().SetActiveScalars('Currents-'+str(n))
    # Get the mesh names
    cell_labels = poly.GetCellData().GetAbstractArray(0)
    assert(cell_labels.GetName()=='Names')
    s = set(); nb_meshes = 0; cell_ids = list()
    for i in range(cell_labels.GetNumberOfValues()):
        s.add(cell_labels.GetValue(i))
        if len(s)>nb_meshes:
            # if a label is added, store the ID for the connectivity filter
            cell_ids.append(i)
            nb_meshes += 1
    # Number of meshes
    assert(nb_meshes<=4)
    # Multiple viewports: 4
    xmins = [0,.5,0,.5]; xmaxs = [0.5,1,0.5,1]; ymins = [0,0,.5,.5]; ymaxs = [0.5,0.5,1,1]

    mappers   = [vtk.vtkPolyDataMapper() for i in range(4)]
    colorBars = [vtk.vtkScalarBarActor() for i in range(4)]
    actors    = [vtk.vtkActor() for i in range(4)]
    rens      = [vtk.vtkRenderer() for i in range(4)]

    for i in range(4):
        rens[i].SetViewport(xmins[i],ymins[i],xmaxs[i],ymaxs[i]);
        # Display the meshes
        if (i < nb_meshes):
            # Create a connectivity filter based on cell seeded region (to display
            # only one mesh per viewport)
            conn = vtk.vtkPolyDataConnectivityFilter()
            conn.SetInput(poly)
            conn.SetExtractionModeToCellSeededRegions()
            conn.AddSeed(cell_ids[i]); conn.Update()
            actor_meshname = vtk.vtkTextActor();
            actor_meshname.SetInput(cell_labels.GetValue(cell_ids[i]));
            actor_meshname.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport();
            actor_meshname.SetPosition(0.5, 0.85); tprop = actor_meshname.GetTextProperty(); tprop.SetFontSize(30)
            tprop.SetFontFamilyToArial(); tprop.SetColor(1, 1, 1); tprop.SetJustificationToCentered()
            mappers[i].SetInputConnection(conn.GetOutputPort())
            mappers[i].SetScalarModeToUsePointData(); mappers[i].Update()
            if nb_sources:
                rens[i].AddActor2D(colorBars[i])
            actors[i].SetMapper(mappers[i])
            rens[i].AddActor2D(actor_meshname)
            rens[i].AddActor(actors[i])
            if (i == 0):
                cam = rens[i].GetActiveCamera()
                rens[i].ResetCamera()
        else:
            # Create a plane to cut
            plane = vtk.vtkPlane(); plane.SetOrigin(0,0,0); plane.SetNormal(1,0,0);
            # Create cutter
            extract = vtk.vtkExtractPolyDataGeometry(); extract.SetInput(poly)
            extract.SetImplicitFunction(plane); extract.ExtractBoundaryCellsOff()
            mappers[i].SetInputConnection(extract.GetOutputPort())
            mappers[i].SetScalarModeToUsePointData(); mappers[i].Update()
            # Create plane actor
            actors[i].SetMapper(mappers[i])
            rens[i].AddActor(actors[i])
        rens[i].SetActiveCamera(cam)
        if nb_sources:
            UpdateColorBar(colorBars[i], mappers[i])
        renWin.AddRenderer(rens[i])
        renWin.Render();

    if nb_sources > 1:
        # Slider
        sliderWidget = vtk.vtkSliderWidget()
        slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1)
        slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f')
        slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources)
        slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint1Coordinate().SetValue(.0 ,0.02)
        slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint2Coordinate().SetValue(1. ,0.02);
        sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider);
        sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn();
        sliderWidget.AddObserver("InteractionEvent", SelectSource);
    if not nb_sources == 0:
        # The button for choosing Potentials/Currents
        buttonWidget = vtk.vtkButtonWidget()
        button = vtk.vtkTexturedButtonRepresentation2D(); button.SetNumberOfStates(2)
        tex1r = vtk.vtkImageData(); tex2r = vtk.vtkImageData();
        prop  = vtk.vtkTextProperty(); prop.SetFontSize(24);
        prop.SetColor(1,0,0); prop.SetBold(2); prop.SetShadow(2); 
        str2im = vtk.vtkFreeTypeStringToImage()
        str2im.RenderString(prop,'Potentials',tex1r)
        str2im.RenderString(prop,'Currents',tex2r)
        button.SetButtonTexture(0, tex1r)
        button.SetButtonTexture(1, tex2r)
        buttonWidget.SetInteractor(iren);
        buttonWidget.SetRepresentation(button);
        button.SetPlaceFactor(1);
        button.PlaceWidget([0., 100, 50, 500, 0, 0]);
        buttonWidget.On()
        buttonWidget.AddObserver(vtk.vtkCommand.StateChangedEvent,SelectMode);
        # Selection
        selactor = vtk.vtkActor()
        view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot')
        view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600)
        # Welcome text
        text_init = vtk.vtkTextActor()
        text_init.SetPosition(10, 300)
        text_init.SetInput(welcome)
        text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0)
        view.GetRenderer().AddActor2D(text_init)
        view.GetInteractor().Initialize()
        iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData)
    iren.Initialize()
    iren.Start()
コード例 #19
0
wireframe = False


def togwire(obj, event):
    global wireframe
    wireframe = not wireframe
    if (wireframe == True):
        contourActor.GetProperty().SetRepresentationToWireframe()
    else:
        contourActor.GetProperty().SetRepresentationToSurface()


wire_image = textImage("Wireframe Off")
wire_image2 = textImage("Wireframe On")
buttonRep = vtk.vtkTexturedButtonRepresentation2D()
buttonRep.SetNumberOfStates(2)
buttonRep.SetButtonTexture(0, wire_image)
buttonRep.SetButtonTexture(1, wire_image2)
buttonRep.PlaceWidget([0, 250, 0, 50, 0, 50])

buttonWidget = vtk.vtkButtonWidget()
buttonWidget.SetInteractor(iact)
buttonWidget.SetRepresentation(buttonRep)
buttonWidget.SetEnabled(True)
buttonWidget.On()
buttonWidget.AddObserver("StateChangedEvent", togwire)

#BUTTON1 END----------------------------------!

コード例 #20
0
def textImage(text):
    buttonImage = vtk.vtkImageData()
    freeType = vtk.vtkFreeTypeStringToImage()
    textProperty = vtk.vtkTextProperty()
    textProperty.SetColor(1.0, 1.0, 1.0)
    textProperty.SetFontSize(64)
    textProperty.SetFontFamilyToTimes()
    freeType.RenderString(textProperty, text, 120, buttonImage)
    return buttonImage


#ComputeNormalsButton
#The naming is a bit counterintuitive for these text images
NormalsOn_image = textImage("Normals Off")
NormalsOff_image = textImage("Normals On")
NormalsButton = vtk.vtkTexturedButtonRepresentation2D()
NormalsButton.SetNumberOfStates(2)
NormalsButton.SetButtonTexture(0, NormalsOff_image)
NormalsButton.SetButtonTexture(1, NormalsOn_image)
NormalsButton.PlaceWidget([0, 400, 0, 50, 0, 0])


def normals_change(obj, event):
    state = obj.GetSliderRepresentation().GetState()
    if state == 1:
        mc_contour[0].ComputeNormalsOff()
        mc_contour[1].ComputeNormalsOff()
    if state == 0:
        mc_contour[0].ComputeNormalsOn()
        mc_contour[1].ComputeNormalsOn()