def __init__( self, iren, **args ): self.PublicStateChangedSignal = SIGNAL('PublicStateChangedSignal') self.PrivateStateChangedSignal = SIGNAL('PrivateStateChangedSignal') self.invokingEvent = False self.active = True self.renderWindowInteractor = iren self.names = args.get( 'names', [] ) self._state = args.get( 'state', 0 ) self.children = args.get( 'children', [] ) self.toggle = args.get( 'toggle', False ) self.parents = args.get( 'parents', [] ) self.numberOfStates = args.get( 'nstates', ( 2 if self.toggle else len( self.names ) ) ) self.id = args.get( 'id', self.names[0] if self.numberOfStates else None ) self.key = args.get( 'key', None ) self.image_size = None self.numberOfImages = 0 self.button_files = [ ] self.functionKeys = { } self.createButtonRepresentation() self.buttonWidget = vtk.vtkButtonWidget() self.buttonWidget.SetInteractor(self.renderWindowInteractor) self.buttonWidget.SetRepresentation( self.buttonRepresentation ) self.buttonWidget.AddObserver( 'StateChangedEvent', self.processStateChangeEvent ) self.buttonRepresentation.Highlight( self._state ) self.updateWidgetState()
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
def __init__( self, iren, **args ): self.PublicStateChangedSignal = SIGNAL('PublicStateChangedSignal') self.PrivateStateChangedSignal = SIGNAL('PrivateStateChangedSignal') self.invokingEvent = False self.active = True self.renderWindowInteractor = iren self.names = args.get( 'names', [] ) self._state = args.get( 'state', 0 ) self.children = args.get( 'children', [] ) self.toggle = args.get( 'toggle', False ) self.parents = args.get( 'parents', [] ) self.numberOfStates = args.get( 'nstates', ( 2 if self.toggle else len( self.names ) ) ) self.id = args.get( 'id', self.names[0] if self.numberOfStates else None ) self.key = args.get( 'key', None ) self.image_size = None self.numberOfImages = 0 self.button_files = [ ] self.functionKeys = { } self.createButtonRepresentation() self.buttonWidget = vtk.vtkButtonWidget() self.buttonWidget.SetInteractor(self.renderWindowInteractor) self.buttonWidget.SetRepresentation( self.buttonRepresentation ) self.buttonWidget.AddObserver( 'StateChangedEvent', self.processStateChangeEvent ) self.buttonRepresentation.Highlight( self._state ) self.buttonWidget.SetPriority(1.0) self.updateWidgetState()
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
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
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
def getButton( self, **args ): button_id, buttonRepresentation = self.getButtonRepresentation( **args ) buttonRepresentation.SetPlaceFactor( args.get( 'scale', 1 ) ) position = args.get( 'position', [ 1.0, 1.0 ] ) size = args.get( 'size', [ 100.0, 20.0 ] ) buttonRepresentation.PlaceWidget( self.computeBounds(position,size) ) buttonWidget = vtk.vtkButtonWidget() buttonWidget.SetInteractor(self.interactor) buttonWidget.SetRepresentation(buttonRepresentation) buttonWidget.AddObserver( 'StateChangedEvent', self.processStateChangeEvent ) self.buttons[ buttonWidget ] = [ button_id, position, size ] return buttonWidget
def getButton(self, **args): button_id, buttonRepresentation = self.getButtonRepresentation(**args) buttonRepresentation.SetPlaceFactor(args.get('scale', 1)) position = args.get('position', [1.0, 1.0]) size = args.get('size', [100.0, 20.0]) buttonRepresentation.PlaceWidget(self.computeBounds(position, size)) buttonWidget = vtk.vtkButtonWidget() buttonWidget.SetInteractor(self.interactor) buttonWidget.SetRepresentation(buttonRepresentation) buttonWidget.AddObserver('StateChangedEvent', self.processStateChangeEvent) self.buttons[buttonWidget] = [button_id, position, size] return buttonWidget
def init_3D_scene(board_file_name): data_root = os.path.join(os.path.dirname(__file__), 'data') importer = vtk.vtkGLTFImporter() importer.SetFileName(data_root + board_file_name) importer.Read() vtk.vtkButtonWidget() global vtk_render_window vtk_renderer = importer.GetRenderer() vtk_render_window = importer.GetRenderWindow() vtk_render_window_interactor = vtk.vtkRenderWindowInteractor() vtk_render_window_interactor.SetRenderWindow(vtk_render_window) vtk_renderer.GradientBackgroundOn() vtk_renderer.SetBackground(0.2, 0.2, 0.2) vtk_renderer.SetBackground2(0.3, 0.3, 0.3) vtk_render_window.SetSize(600, 600) vtk_render_window.SetWindowName('TinyCircuits: IMU 3D Visualizer') vtk_render_window_interactor.Initialize() vtk_renderer.GetActiveCamera().Zoom(1.0) vtk_renderer.GetActiveCamera().SetRoll(90) vtk_renderer.GetActiveCamera().SetClippingRange(0.01, 100) vtk_renderer.GetActiveCamera().SetViewAngle(40) vtk_renderer.SetClippingRangeExpansion(0.1) # Adjust so clipping of polygons doesn't show vtk_renderer.TwoSidedLightingOn() vtk_renderer.SetAmbient([1, 1, 1]) vtk_renderer.ResetCamera() vtk_render_window.Render() # Add callback for getting data from Arduino vtk_render_window_interactor.CreateRepeatingTimer(1) vtk_render_window_interactor.AddObserver("TimerEvent", information_callback) global vtk_actors vtk_actors = vtk_renderer.GetActors() vtk_render_window_interactor.Start()
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
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
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)
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)
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 interpolation_on = True def toggle_interpolation(obj, event): global interpolation_on # interpolation_on = not interpolation_on
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)
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)
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: logging.warning('Encountered issue in callback: {}'.format(e)) return def callback(val):
buttonRepresentation = vtk.vtkProp3DButtonRepresentation() #buttonRepresentation.FollowCameraOn() buttonRepresentation.SetNumberOfStates(1) buttonRepresentation.SetButtonProp( 0, textActor ) # Create the Renderer, RenderWindow, and RenderWindowInteractor. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetInteractorStyle( vtk.vtkInteractorStyleTrackballCamera() ) ren.SetBackground(0.1, 0.2, 0.4) buttonWidget = vtk.vtkButtonWidget() buttonWidget.SetInteractor( iren ) position = [ 0.5, 0.5 ] size = [ 1.0, 1.0 ] # ComputeDisplayToWorld(double x, double y, double z, double worldPt[4]) bounds = computeBounds(ren, position,size) print " Bounds = ", bounds buttonRepresentation.PlaceWidget( bounds ) buttonWidget.SetRepresentation(buttonRepresentation) # Add the actors to the renderer. ren.AddActor(axesActor) # ren.AddActor(textActor) # Zoom in closer. ren.ResetCamera()
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()
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----------------------------------! #BUTTON2 START-------------------------------------! def textImage2(text): buttonImage2 = vtk.vtkImageData() freeType2 = vtk.vtkFreeTypeStringToImage() textProperty2 = vtk.vtkTextProperty() textProperty2.SetColor(1.0, 1.0, 1.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() print state #NormalsButtonWidgets normalsWidget = vtk.vtkButtonWidget() normalsWidget.SetInteractor(iact) normalsWidget.SetRepresentation(NormalsButton) normalsWidget.SetEnabled(True) normalsWidget.On() normalsWidget.AddObserver("StateChangedEvent", normals_change) #ChangeSurfaceTypeButton Wireframe_image = textImage("Wireframe On") Surface_image = textImage("Surface On") SurfaceButton = vtk.vtkTexturedButtonRepresentation2D() SurfaceButton.SetNumberOfStates(2) SurfaceButton.SetButtonTexture(0, Surface_image) SurfaceButton.SetButtonTexture(1, Wireframe_image) SurfaceButton.PlaceWidget([0, 2000, 0, 50, 0, 0])