def get_marker_at_point(self):
     
     x, y = self.GetEventPosition()
     picker = vtk.vtkPropPicker()
     picker.PickProp(x, y, self.renderer, EventHandler().get_markers())
     actor = picker.GetActor()
     return actor
Exemple #2
0
 def widget_at_point(self, x, y):
     picker = vtk.vtkPropPicker()
     if picker.PickProp(x, y, self.renderer):
         return True
     if picker.PickProp(x, y, self.actor_renderer):
         return True
     return False
  def OnRightButtonDown(self, obj, eventType):
    # The rightbutton is used to pick up the piece.

    # Get the display mouse event position
    clickPos = self.GetInteractor().GetEventPosition()

    # Use a picker to see which actor is under the mouse
    picker = vtk.vtkPropPicker()
    picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
    actor = picker.GetActor()

    # Is this a piece that we should interact with?
    if actor in self.pieces:
      # Yes! Remember it.
      self.chosenPiece = actor

      # Get the intersection of the click pos in our board plane.
      mouseDisplayZ = self.WorldZToDisplayZ(clickPos, worldZ=0)

      # Get the board xy coordinate of the picked point
      self.worldPickXY = self.DisplayToWorld(list(clickPos) + [mouseDisplayZ])[0:2]

      # Remember the original position
      self.piecePickPos = self.chosenPiece.GetPosition()

    # Call parent interaction
    vtk.vtkInteractorStyleTrackballCamera.OnRightButtonDown(self)
Exemple #4
0
    def leftButtonPressEvent(self,obj,event):
        clickPos = self.GetInteractor().GetEventPosition()
 
        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
 
        # get the new
        self.NewPickedActor = picker.GetActor()
 
        # If something was selected
        if self.NewPickedActor:
            # If we picked something before, reset its property
            if self.LastPickedActor:
                self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)
 
 
            # Save the property of the picked actor so that we can
            # restore it next time
            self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
            # Highlight the picked actor by changing its properties
            self.NewPickedActor.GetProperty().SetColor(1.0, 0.0, 0.0)
            self.NewPickedActor.GetProperty().SetDiffuse(1.0)
            self.NewPickedActor.GetProperty().SetSpecular(0.0)
 
            # save the last picked actor
            self.LastPickedActor = self.NewPickedActor
 
        self.OnLeftButtonDown()
        return
    def leftButtonPressEvent(self, obj, event):
        clickPos = self.GetInteractor().GetEventPosition()

        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())

        # get the new
        self.NewPickedActor = picker.GetActor()

        # If something was selected
        if self.NewPickedActor:
            # If we picked something before, reset its property
            if self.LastPickedActor:
                self.LastPickedActor.GetProperty().DeepCopy(
                    self.LastPickedProperty)

            # Save the property of the picked actor so that we can
            # restore it next time
            self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
            # Highlight the picked actor by changing its properties
            self.NewPickedActor.GetProperty().SetColor(1.0, 0.0, 0.0)
            self.NewPickedActor.GetProperty().SetDiffuse(1.0)
            self.NewPickedActor.GetProperty().SetSpecular(0.0)

            # save the last picked actor
            self.LastPickedActor = self.NewPickedActor

        self.OnLeftButtonDown()
        return
    def __init__(self, canvas):
        self.canvas = canvas
        self.backend = canvas.backend
        self.interactor = None
        self.display_strings = {}
        self.displays = []
        self.clicking = None
        self.clicked_info = None
        self.target = None
        self.changed = False
        self.toolbar = None
        self.fill_button = None
        self.text_button = None
        self.line_button = None
        self.marker_button = None
        self.initialized = False
        self.animation_speed = 5
        self.animation_timer = None
        self.save_timer = None
        self.save_listener = None
        self.save_anim_button = None
        self.anim_button = None
        self.listeners = []
        self.animation_last_frame_time = datetime.datetime.now()
        self.picker = vtk.vtkPropPicker()
        # Map custom templates to their source template
        self.templates = {}

        self.creating = False
        self.click_locations = None
Exemple #7
0
    def __init__(self, canvas):
        self.canvas = canvas
        self.backend = canvas.backend
        self.interactor = None
        self.display_strings = {}
        self.displays = []
        self.clicking = None
        self.clicked_info = None
        self.target = None
        self.changed = False
        self.toolbar = None
        self.fill_button = None
        self.text_button = None
        self.line_button = None
        self.marker_button = None
        self.initialized = False
        self.animation_speed = 5
        self.animation_timer = None
        self.save_timer = None
        self.save_listener = None
        self.save_anim_button = None
        self.anim_button = None
        self.listeners = []
        self.animation_last_frame_time = datetime.datetime.now()
        self.picker = vtk.vtkPropPicker()
        # Map custom templates to their source template
        self.templates = {}

        self.creating = False
        self.click_locations = None
Exemple #8
0
    def leftButtonPressEvent(self, obj, event):
        clickPos = self.GetInteractor().GetEventPosition()

        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())

        # get the new
        newPickedActor = picker.GetActor()

        # If something was selected
        if newPickedActor:
            # If we picked something before, reset its property

            if newPickedActor in self.PickedActors:
                self.PickedActors.remove(newPickedActor)
                actorOriginalProp = self.PickedActorsOriginalProperties.pop(
                    newPickedActor)
                newPickedActor.GetProperty().DeepCopy(actorOriginalProp)
            else:
                self.PickedActors.append(newPickedActor)
                pickedActorPropertyCopy = vtk.vtkProperty()

                newPickedActorProperty = newPickedActor.GetProperty()
                pickedActorPropertyCopy.DeepCopy(newPickedActorProperty)
                self.PickedActorsOriginalProperties[
                    newPickedActor] = pickedActorPropertyCopy

                newPickedActorProperty.SetDiffuse(1.0)
                newPickedActorProperty.SetSpecular(1.0)

        self.OnLeftButtonDown()
        return
Exemple #9
0
    def __init__(self):
        """Init."""
        # Interactor responsible for moving the camera.
        self.trackball_camera = vtk.vtkInteractorStyleTrackballCamera()
        # Interactor responsible for moving/rotating a selected actor.
        self.trackball_actor = vtk.vtkInteractorStyleTrackballActor()
        # Interactor responsible for panning/zooming the camera.
        self.image = vtk.vtkInteractorStyleImage()

        # The picker allows us to know which object/actor is under the mouse.
        self.picker = vtk.vtkPropPicker()
        self.chosen_element = None
        self.event = Event()
        self.event2id = {}  # To map an event's name to an ID.

        # Define some interaction states
        self.left_button_down = False
        self.right_button_down = False
        self.middle_button_down = False
        self.active_props = set()

        self.history = deque(maxlen=10)  # Events history.

        self.selected_props = {"left_button": set(),
                               "right_button": set(),
                               "middle_button": set()}
Exemple #10
0
 def do_trace(self, obj, e):             
     global im_view, trace_mode, cur_picked_point, trace_mode, traced_lines, color_red, color_green, traced_tree
     cur_slice = im_view.GetSlice()
     click_pos = self.GetInteractor().GetEventPosition()
     if trace_mode == True and choose_mode == False:
         if cur_picked_point == [] and len(traced_lines) != 0:
             print "Must Choose a Point to Start!"
         else:
             trace_picker = vtk.vtkCellPicker()
             trace_picker.Pick(click_pos[0], click_pos[1], cur_slice, im_view.GetRenderer())
             picked_pos = trace_picker.GetPickPosition()
             traced_point = np.require(picked_pos, dtype=np.uint16)
             self.save2lines(traced_point)
             self.ShowPoint(traced_point, color_red)
             if cur_picked_point != []:
                 self.ShowLine(cur_picked_point.tolist(), traced_point.tolist())
             self.changeColor(traced_point, color_green, color_red)
             cur_picked_point = traced_point
     if choose_mode == True and trace_mode == False:
         if traced_tree.size() == 0:
             print "No Point to Choose, Please Trace First!"
         else:    
             choose_picker = vtk.vtkPropPicker()
             choose_picker.Pick(click_pos[0], click_pos[1], cur_slice, im_view.GetRenderer())
             if choose_picker.GetActor() != None:
                 choosen_point = choose_picker.GetActor().GetMapper().GetInput().GetCenter()
                 choosen_point = np.array(choosen_point, dtype=np.uint16)
                 self.changeColor(choosen_point, color_green, color_red)                  
                 cur_picked_point = choosen_point
             else:
                     print "Please Choose a Point"
Exemple #11
0
    def selectCell(self, x: float, y: float):
        """
        Select a cell based on the x, y position clicked on the canvas.
        
        """
        picker = vtk.vtkPropPicker()
        picker.Pick(x, self._height - y, 0, self.renderer)

        # get the new
        self.NewPickedActor = picker.GetActor()

        position = picker.GetPickPosition()

        if not picker.GetActor():
            self._selectedCell = None
            self.update()
            return

        x, y, z = picker.GetPickPosition()

        cells = self.getCellsToRender()
        cellVariables = self.getCellVariables()

        distances = np.sqrt(
            np.square(x - cells[cellVariables['position.x']]) +
            np.square(y - cells[cellVariables['position.y']]) +
            np.square(z - cells[cellVariables['position.z']])
        ) - self.radiusOfCells(cells, cellVariables)
        minIndex = np.argmin(distances)

        if distances[minIndex] <= 0:
            self._selectedCell = cells[cellVariables['ID'], minIndex]

        self.update()
Exemple #12
0
    def renderthis(self, data):
        ren = vtk.vtkRenderer()
        self.ren = ren
        self.p1.widget.GetRenderWindow().AddRenderer(ren)
        camera = vtk.vtkCamera()
        camera.SetPosition(0, 0, 0)
        camera.SetFocalPoint(0.255739, 0.207345, 0.439719)
        camera.ParallelProjectionOn()
        ball = vtk.vtkSphereSource()
        ball.SetRadius(0.1)
        ball.SetThetaResolution(10)
        ball.SetPhiResolution(10)
        ballGlyph = vtk.vtkGlyph3D()
        self.bglyth = ballGlyph
        if self.vtkversion() == 6:
            ballGlyph.SetInputData(data)
        elif self.vtkversion() == 5:
            ballGlyph.SetInput(data)
        else:
            ballGlyph.SetInputData(data)
        ballGlyph.SetSourceConnection(ball.GetOutputPort())

        #            ballGlyph.SetScaleModeToScaleByScalar()
        #            ballGlyph.SetColorModeToColorByScalar()
        #            ballGlyph.SetScaleFactor(1.0)
        colorTransferFunction = vtk.vtkColorTransferFunction()
        colorTransferFunction.AddRGBPoint(255, 45, 45, 1.0)

        ballMapper = vtk.vtkPolyDataMapper()
        ballMapper.SetInputConnection(ballGlyph.GetOutputPort())
        ballMapper.ScalarVisibilityOff()
        ballMapper.SetLookupTable(colorTransferFunction)
        ballActor = vtk.vtkActor()
        ballActor.SetMapper(ballMapper)
        ballActor.GetProperty().SetColor(1, 1, 1)
        ren.AddActor(ballActor)
        ren.SetActiveCamera(camera)
        ren.SetBackground(0.03, 0.1, 0.2)
        ######################################AXES##################################################
        axes = vtk.vtkAxesActor()
        self.marker = vtk.vtkOrientationMarkerWidget()
        self.marker.SetInteractor(self.p1.widget)
        self.marker.SetOrientationMarker(axes)
        self.marker.SetViewport(0.75, 0, 1, 0.25)
        self.marker.SetEnabled(1)
        ############################################################################################

        pointPicker = vtk.vtkPropPicker()
        #            pointer=vtk.vtkSmartPointer.pointPicker
        #            pointPicker.SetTolerance(100)
        self.p1.widget.SetPicker(pointPicker)

        ren.ResetCamera()
        ren.ResetCameraClippingRange()
        cam = ren.GetActiveCamera()
        cam.Elevation(0)
        cam.Azimuth(0)
        self.isploted = True
        print(self.isploted)
Exemple #13
0
    def OnLeftButtonPressed(self, obj, event):

        self.bMouseClicked = True
        if self.renderer == None: return
        position = self.GetInteractor().GetEventPosition()
        picker = vtk.vtkPropPicker()
        picker.Pick(position[0], position[1], 0, self.renderer)
        self.renderer.UpdateSelectedPosition(picker.GetPickPosition())
    def __init__(self, src_actor, tar_actors):
        # super(MouseInteractorStylePP2, self).__init__()
        self.AddObserver('RightButtonReleaseEvent', self.OnRightButtonUp)

        self.src_actor = src_actor
        self.tar_actors = tar_actors
        self.prop_picker = vtk.vtkPropPicker(
        )  # vtkPointPicker seemingly can't pick the vtkImageActor
Exemple #15
0
    def OnMouseMove(self, obj, event):
        if self.renderer == None: return
        if self.bMouseClicked:
            position = self.GetInteractor().GetEventPosition()
            picker = vtk.vtkPropPicker()
            picker.Pick(position[0], position[1], 0, self.renderer)
            self.renderer.UpdateSelectedPosition(picker.GetPickPosition())

            self.renderer.CalculateDiff()
 def __init__(self):
     '''
     Constructor
     '''
     vtkPythonInteractorStyleTrackballCamera.__init__(self)
     
     self.__TrackStyle = self.TrackStyleCamera
     self.__InteractionPicker = vtk.vtkPropPicker()
     self.__InteractionProp = None
Exemple #17
0
 def in_bounds(self, x, y):
     if x < 1 and y < 1:
         w, h = self.interactor.GetRenderWindow().GetSize()
         x, y = x * w, y * h
     picker = vtkPropPicker()
     ren = self.manager.actor_renderer
     if picker.PickProp(x, y, ren) and picker.GetViewProp() == self.actor:
         return True
     else:
         return False
Exemple #18
0
    def OnLeftButtonDown(self, obj, eventType):
        clickPos = self.GetInteractor().GetEventPosition()

        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
        actor = picker.GetActor2D()

        self.chosenPiece = actor

        vtk.vtkInteractorStyleTrackballCamera.OnLeftButtonDown(self)
Exemple #19
0
 def in_bounds(self, x, y):
     if x < 1 and y < 1:
         w, h = self.interactor.GetRenderWindow().GetSize()
         x, y = x * w, y * h
     picker = vtkPropPicker()
     ren = self.manager.actor_renderer
     if picker.PickProp(x, y, ren) and picker.GetViewProp() == self.actor:
         return True
     else:
         return False
Exemple #20
0
 def pickLine(self, obj, e):
     global cube1, ren, iren, cubeActor
     clickPos = self.GetInteractor().GetEventPosition()
     print clickPos
     #       print obj == self
     picker = vtk.vtkCellPicker()
     picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     print picker.GetCellId()
     picker2 = vtk.vtkPropPicker()
     picker2.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     print picker2.GetActor() == cubeActor
Exemple #21
0
    def pickLine(self, obj, e):
        global cube1, ren, iren, cubeActor
        clickPos = self.GetInteractor().GetEventPosition()
        print clickPos
 #       print obj == self
        picker = vtk.vtkCellPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        print picker.GetCellId()
        picker2 = vtk.vtkPropPicker()
        picker2.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        print picker2.GetActor() == cubeActor
Exemple #22
0
 def pickLine(self, obj, e):
     global cy1, ren, iren, actor1
     clickPos = self.GetInteractor().GetEventPosition()
     print clickPos
     picker = vtk.vtkCellPicker()
     picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     print picker.GetCellId()
     picker2 = vtk.vtkPropPicker()
     picker2.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     print picker2.GetActor() == actor1
     self.OnLeftButtonDown()
    def __init__(self, viewer):
        super().__init__(viewer)
        self.viewer = viewer
        self.state_code = const.STATE_MEASURE_DISTANCE
        self.measure_picker = vtk.vtkPropPicker()

        proj = prj.Project()
        self._radius = min(proj.spacing) * PROP_MEASURE

        self.RemoveObservers("LeftButtonPressEvent")
        self.AddObserver("LeftButtonPressEvent", self.OnInsertAngularMeasurePoint)
Exemple #24
0
    def pickLine(self, obj, e):
        global line1, ren, iren, actor1
        clickPos = self.GetInteractor().GetEventPosition()
        print clickPos
 #       print obj == self
        picker = vtk.vtkCellPicker()
        print picker.GetTolerance()
        picker.SetTolerance(1 / 80.0)
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        print picker.GetCellId()
        picker2 = vtk.vtkPropPicker()
        picker2.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
Exemple #25
0
 def pickLine(self, obj, e):
     global line1, ren, iren, actor1
     clickPos = self.GetInteractor().GetEventPosition()
     print clickPos
     #       print obj == self
     picker = vtk.vtkCellPicker()
     print picker.GetTolerance()
     picker.SetTolerance(1 / 80.0)
     picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     print picker.GetCellId()
     picker2 = vtk.vtkPropPicker()
     picker2.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
Exemple #26
0
    def mousePressEvent(self, ev):
        ctrl, shift = self._GetCtrlShift(ev)
        if ev.button() == Qt.LeftButton:
            print("left button")
            print(ev.x(), ev.y())
            picker = vtk.vtkPropPicker()
            picker.Pick(ev.x(), ev.y(), 0, self.ren)
            last_act = picker.GetActor()

            print(last_act)
        if ev.button() == Qt.RightButton:
            self.right_click = True
Exemple #27
0
    def MyLeftButtonDown(self, obj, e):
        global Choose_Mode, Delete_Mode, actors, actors_choosed_flags, ren
        click_pos = self.GetInteractor().GetEventPosition()
        click_x = click_pos[0]
        click_y = click_pos[1]
        if Choose_Mode == True:
            picker = vtk.vtkPropPicker()
            picker.Pick(click_x, click_y, 0, self.GetDefaultRenderer())
            picked_actor = picker.GetActor()
            if picked_actor is not None:
                try:
                    choosed_index = actors.index(picked_actor)
                    if actors_choosed_flags[choosed_index] == 0:
                        actors_choosed_flags[choosed_index] = 1
                        picked_actor.GetProperty().SetColor(0.0, 255.0, 0.0)
                        picked_actor.Modified()
                    elif actors_choosed_flags[choosed_index] == 1:
                        actors_choosed_flags[choosed_index] = 0
                        picked_actor.GetProperty().SetColor(255.0, 0.0, 0.0)
                        picked_actor.Modified()
                except:
                    print "Choose No Point"
        elif Delete_Mode == True:
            picker = vtk.vtkPropPicker()
            picker.Pick(click_x, click_y, 0, self.GetDefaultRenderer())
            picked_actor = picker.GetActor()
            if picked_actor is not None:
                try:
                    choosed_index = actors.index(picked_actor)
                    ren.RemoveActor(picked_actor)
                    actors.pop(choosed_index)
                    actors_choosed_flags.pop(choosed_index)


#                    ren.Modified()
                except:
                    print "Choose No Point"
        self.OnLeftButtonDown()
    def pickActors(self):
        renderer = self.GetDefaultRenderer() or self.GetCurrentRenderer()
        if renderer is None:
            return 

        self.lowlight(self.getSelectedActors())

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

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

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

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

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

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

        self.highlight(self.getSelectedActors())       

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

        self.__renderer.updateInfoText()
        self.__renderer.update()
Exemple #29
0
    def in_bounds(self, x, y):
        w, h = self.interactor.GetRenderWindow().GetSize()
        x, y = x * w, y * h
        picker = vtk.vtkPropPicker()
        for ren in vcs.vcs2vtk.vtkIterate(self.interactor.GetRenderWindow().GetRenderers()):
            if ren.HasViewProp(self.actor):
                break
        else:
            return False

        if picker.PickProp(x, y, ren) and picker.GetViewProp() == self.actor:
            return True
        else:
            return False
Exemple #30
0
        def buttonfunc(iren, event):
            """
            Mouse event
            Allows to change color map
            """
            clickPos = iren.GetEventPosition()

            picker = vtk.vtkPropPicker()
            picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
            if not picker.GetActor2D():
                return
            bu.switch()
            self.cmap_slicer = bu.status()
            self.refresh()
Exemple #31
0
    def in_bounds(self, x, y):
        w, h = self.interactor.GetRenderWindow().GetSize()
        x, y = x * w, y * h
        picker = vtk.vtkPropPicker()
        for ren in vcs.vcs2vtk.vtkIterate(
                self.interactor.GetRenderWindow().GetRenderers()):
            if ren.HasViewProp(self.actor):
                break
        else:
            return False

        if picker.PickProp(x, y, ren) and picker.GetViewProp() == self.actor:
            return True
        else:
            return False
Exemple #32
0
 def pickPoint(self, obj, e):
     if self.__pickPointMode == True:
         print self.GetInteractor().GetEventPosition()
         clicked_point = self.GetInteractor().GetEventPosition()
         picker1 = vtk.vtkPointPicker()
         picker1.Pick(clicked_point[0], clicked_point[1], 0, ren)
         
         picker2 = vtk.vtkPropPicker()
         picker2.PickProp(clicked_point[0], clicked_point[1], ren)
         picked_prop = picker2.GetActor()
         if picked_prop != None:    
             picked_prop.GetProperty().SetColor(1.0, 1.0, 0.0)
         else:
             print "None is picked!"
     self.OnLeftButtonDown()
Exemple #33
0
 def __init__(self, vtkDrawer, iren, renderer):
     """ vtkDrawer is an instance of VTKDrawer
     iren is a render window interactor."""
     self.iren = iren
     self.ren1 = renderer
     self.drawer = vtkDrawer
     
     #set the picker so props can be picked
     self.picker = vtk.vtkPropPicker()
     iren.SetPicker(self.picker)
     
     #Add my own pick function
     self.observerNum = iren.AddObserver("LeftButtonPressEvent", self.pick)
     
     self.SelectedActor = None   #used by the pick() so that only one item is
Exemple #34
0
    def MyLeftButtonDown(self, obj, e):
        global Choose_Mode, Delete_Mode, actors, actors_choosed_flags, ren
        click_pos = self.GetInteractor().GetEventPosition()
        click_x = click_pos[0]
        click_y = click_pos[1]
        if Choose_Mode == True:
            picker = vtk.vtkPropPicker()
            picker.Pick(click_x, click_y, 0, self.GetDefaultRenderer())
            picked_actor = picker.GetActor()
            if picked_actor is not None:
                try:
                    choosed_index = actors.index(picked_actor)
                    if actors_choosed_flags[choosed_index] == 0:
                        actors_choosed_flags[choosed_index] = 1
                        picked_actor.GetProperty().SetColor(0.0, 255.0, 0.0)
                        picked_actor.Modified()
                    elif actors_choosed_flags[choosed_index] == 1:
                        actors_choosed_flags[choosed_index] = 0
                        picked_actor.GetProperty().SetColor(255.0, 0.0, 0.0)
                        picked_actor.Modified()                       
                except:
                    print "Choose No Point"            
        elif Delete_Mode == True:
            picker = vtk.vtkPropPicker()
            picker.Pick(click_x, click_y, 0, self.GetDefaultRenderer())
            picked_actor = picker.GetActor()
            if picked_actor is not None:
                try:
                    choosed_index = actors.index(picked_actor)
                    ren.RemoveActor(picked_actor)
                    actors.pop(choosed_index)
                    actors_choosed_flags.pop(choosed_index)
#                    ren.Modified()                 
                except:
                    print "Choose No Point"             
        self.OnLeftButtonDown()
    def setup(self):
        self.setupUi(self)
        self.frame.setMaximumWidth(0)

        loadAct = QAction('&Open', self)
        loadAct.setShortcut('Ctrl+O')
        loadAct.setStatusTip('Load data')
        loadAct.triggered.connect(self.onLoadClicked)

        exitAct = QAction('&Exit', self)
        exitAct.setShortcut('ALT+F4')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(self.close)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(loadAct)
        fileMenu.addAction(exitAct)

        self.stack = Viewer2DStacked(self, [0, 1, 2])
        self.vtk_widgets = []

        self.viewer3D = Viewer3D(self)
        self.viewer3D.AddPlaneCornerButtons()

        # Extra picking stuff
        self.PropPicker = vtk.vtkPropPicker()
        self.PropPicker.PickFromListOn()

        self.establishCallbacks()

        self.stack.ShowWidgetHideData()

        # Layouts (to edges)
        #self.horizontalLayout.setContentsMargins(0,0,0,0)

        vert_layout0 = QVBoxLayout()
        horz_splitter0 = QSplitter(Qt.Horizontal)
        horz_splitter0.addWidget(self.stack)
        horz_splitter0.addWidget(self.viewer3D)
        vert_layout0.addWidget(horz_splitter0)
        vert_layout0.setContentsMargins(0, 0, 0, 0)
        self.vtk_panel.setLayout(vert_layout0)

        layout = QVBoxLayout()
        self.frame.setLayout(layout)
        self.centralWidget().layout().setContentsMargins(0, 0, 0, 0)
        self.statusBar().hide()
Exemple #36
0
 def leftButtonPressEvent(self, obj, event):
     clickPos = self.GetInteractor().GetEventPosition()
     picker = vtk.vtkPropPicker()
     picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
     self.NewPickedActor = picker.GetActor()
     if self.NewPickedActor:
         # If we picked something before, reset its property
         if self.LastPickedActor:
             self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)
         self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
         self.NewPickedActor.GetProperty().SetColor(0.0, 1.0, 1.0)
         self.NewPickedActor.GetProperty().SetDiffuse(1.0)
         self.NewPickedActor.GetProperty().SetSpecular(0.0)
         self.LastPickedActor = self.NewPickedActor
     self.OnLeftButtonDown()
     return
Exemple #37
0
def pickActor(obj, e):
    global iren, ren, aspath
    picker1 = vtk.vtkPropPicker()
    x, y = iren.GetEventPosition()
    picker1.Pick(x, y, 0, ren)
    print picker1.GetActor()
    i1 = vtk.vtkCollectionIterator()
    aspath.InitTraversal(i1)
    for i in xrange(aspath.GetNumberOfItems()):
        actor_i = aspath.GetNextItemAsObject()
        print id(actor_i)
    print '____________________________'
    aspath.InitTraversal()
    for i in xrange(aspath.GetNumberOfItems()):
        actor_i = aspath.GetNextItemAsObject()
        print id(actor_i)
Exemple #38
0
    def leftButtonDown(self, *arg):
        clickPos = self.GetInteractor().GetEventPosition()
        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        pos = picker.GetPickPosition()
        self.OnLeftButtonDown()
        print pos

        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetCenter(pos[0], pos[1], pos[2])
        sphereSource.SetRadius(0.1)
        sphereMapper = vtk.vtkPolyDataMapper()
        sphereMapper.SetInputConnection(sphereSource.GetOutputPort())
        sphereActor = vtk.vtkActor()
        sphereActor.SetMapper(sphereMapper)
        self.GetDefaultRenderer().AddActor(sphereActor)
Exemple #39
0
    def leftButtonDown(self, *arg):
        clickPos = self.GetInteractor().GetEventPosition()
        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        pos = picker.GetPickPosition()
        self.OnLeftButtonDown()
        print pos

        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetCenter(pos[0], pos[1], pos[2])
        sphereSource.SetRadius(0.1)
        sphereMapper = vtk.vtkPolyDataMapper()
        sphereMapper.SetInputConnection(sphereSource.GetOutputPort())
        sphereActor = vtk.vtkActor()
        sphereActor.SetMapper(sphereMapper)
        self.GetDefaultRenderer().AddActor(sphereActor)
Exemple #40
0
def pickActor(obj, e):
    global iren, ren, aspath
    picker1 = vtk.vtkPropPicker()
    x, y = iren.GetEventPosition()
    picker1.Pick(x, y, 0, ren)
    print picker1.GetActor()
    i1 = vtk.vtkCollectionIterator()
    aspath.InitTraversal(i1)
    for i in xrange(aspath.GetNumberOfItems()):
        actor_i = aspath.GetNextItemAsObject()
        print id(actor_i)
    print '____________________________'
    aspath.InitTraversal()
    for i in xrange(aspath.GetNumberOfItems()):
        actor_i = aspath.GetNextItemAsObject()
        print id(actor_i)
Exemple #41
0
    def leftButtonPressEvent(self, obj, event):
        clickPos = self.GetInteractor().GetEventPosition()
        pos = self.GetInteractor().GetPicker().GetPickPosition()
        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())
        # get the new
        self.NewPickedActor = picker.GetActor()
        """
		Idea is to compare the xyz locations with the numpy parcels to get the 
		selected Id 
		"""
        # If something was selected
        if self.NewPickedActor:
            # If we picked something before, reset its property
            if self.LastPickedActor:
                self.LastPickedActor.GetProperty().DeepCopy(
                    self.LastPickedProperty)
            # Save the property of the picked TemplateActor so that we can
            # restore it next time
            self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())

            # Highlight the picked TemplateActor by changing its properties
            # self.NewPickedActor.GetProperty().SetColor(self.selectedColor)

            bounds = self.NewPickedActor.GetBounds()
            if self.VolumneRendererWindow.setCentroidModeFlag:
                if self.VolumneRendererWindow.SphereActors:
                    index = 0
                    for actor in self.VolumneRendererWindow.SphereActors:
                        if actor == self.NewPickedActor:
                            break
                        index += 1
                    self.VolumneRendererWindow.RegionSelectedIn(index)
            else:
                if self.VolumneRendererWindow.Parcel:
                    index = 0
                    for actor in self.VolumneRendererWindow.Parcel:
                        if actor == self.NewPickedActor:
                            break
                        index += 1
                    self.VolumneRendererWindow.RegionSelectedIn(index - 1)
            # save the last picked TemplateActor
            self.LastPickedActor = self.NewPickedActor

        self.OnLeftButtonDown()
        return
Exemple #42
0
    def leftButtonPressEvent(self, obj, event):
        clickPos = self.GetInteractor().GetEventPosition()

        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())

        # get the new
        self.NewPickedActor = picker.GetActor()

        # If something was selected
        if self.NewPickedActor:
            if self.NewPickedActor == self.cube:
                print("Picked cube")
            elif self.NewPickedActor == self.sphere:
                print("Picked sphere.")
        self.OnLeftButtonDown()
        return
Exemple #43
0
 def iniVTK(self):
     self.last_added_sphere_ren1 = None
     self.newed_spheres = vtk.vtkCollection()
     self.sphere_radius_ren1 = 2.0
     self.bouttons_spheres = []
     self.slice_assembly = None
     self.image_roi = None
     self.im_importer = vtk.vtkImageImport()
     self.sphere = vtk.vtkSphereSource()
     self.sphere.SetRadius(2.0)
     self.sphere_mapper = vtk.vtkPolyDataMapper()
     self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort())
     self.sphere_actor_ren2 = vtk.vtkActor()
     self.sphere.SetCenter(show_height / 2, show_width / 2, 0)
     self.sphere_actor_ren2.SetMapper(self.sphere_mapper)
     self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0)
     self.vtk_widget.GetRenderWindow().SetSize(800, 400)
     self.image_actor = vtk.vtkImageActor()
     self.ren1 = vtk.vtkRenderer()
     self.ren2 = vtk.vtkRenderer()
     self.interactorStyle = BouttonInteractorStyle()
     self.vtk_widget.SetInteractorStyle(self.interactorStyle)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2)
     self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0)
     self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0)
     self.ren2.AddActor(self.sphere_actor_ren2)
     self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors()
     self.imageLevelFilter.SetLevel(400)
     self.imageLevelFilter.SetWindow(800)
     self.im_importer.SetNumberOfScalarComponents(1)
     self.im_importer.SetDataScalarTypeToUnsignedShort()
     self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1,
                                    0, 0)
     self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1,
                                     0, 0)
     self.imageLevelFilter.SetInputConnection(
         self.im_importer.GetOutputPort())
     self.image_actor.SetInput(self.imageLevelFilter.GetOutput())
     self.ren1_sphere_actors = vtk.vtkActorCollection()
     self.pointPicker = vtk.vtkPointPicker()
     self.actorPicker = vtk.vtkPropPicker()
     self.pickedActor = None
     self.ren1.AddActor(self.image_actor)
     self.ren2.AddActor(self.image_actor)
Exemple #44
0
    def leftButtonPressEvent(self,obj,event):
        clickPos = self.GetInteractor().GetEventPosition()
        ren = self.GetDefaultRenderer()
        cam = ren.GetActiveCamera()

        picker = vtk.vtkPropPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, ren)

        # get the new
        self.NewPickedActor = picker.GetActor()
        # picker.GetPickPosition()

        # If something was selected
        if self.NewPickedActor:
            # If we picked something before, reset its property
            if self.LastPickedActor:
                self.LastPickedActor.GetProperty().DeepCopy(self.LastPickedProperty)

            # pos = np.array(self.NewPickedActor.GetProperty().GetPosition())
            pos = np.array(self.NewPickedActor.GetCenter())

            # Save the property of the picked actor so that we can
            # restore it next time
            self.LastPickedProperty.DeepCopy(self.NewPickedActor.GetProperty())
            # Highlight the picked actor by changing its properties
            newPickColor = np.array(self.NewPickedActor.GetProperty().GetColor())
            self.NewPickedActor.GetProperty().SetColor(newPickColor * 1.25)
            self.NewPickedActor.GetProperty().SetDiffuse(1.0)
            self.NewPickedActor.GetProperty().SetSpecular(0.0)

            # save the last picked actor
            self.LastPickedActor = self.NewPickedActor

            # this could be made smoother and could probably use the vtkRenderWindowInteractor
            cam.SetPosition(pos * 10.0)
            cam.SetFocalPoint(0.0,0.0,0.0)

            up = np.array([1.0,0.0,0.0])
            if (np.dot(pos,up) != 0.0):
                up = np.array([0.0,1.0,0.0])
            
            cam.SetViewUp(up)

        self.OnLeftButtonDown()
        return
Exemple #45
0
    def __init__(self):

        # Create the Renderer, RenderWindow, etc. and set the Picker.
        self.ren = vtk.vtkRenderer()
        self.renwin = vtk.vtkRenderWindow()
        self.renwin.AddRenderer(self.ren)
        self.ren.SetViewport(0,0,1,1)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renwin)
        self.propPicker = vtk.vtkPropPicker()
        self.iren.SetPicker(self.propPicker)
        
        # blue sphere, will show four spheres when hovered on
        self.blueSphere = Sphere((0,0,0), 3.0, (0,0,1))
        self.blueSphere.sphereActor.VisibilityOn()
        self.greenSphere = Sphere((4,4,0), 1.0, (0,1,0))
        self.redSphere = Sphere((4,-4,0), 1.0, (1,0,0))
        self.yellowSphere = Sphere((-4,4,0), 1.0, (1,1,0))
        self.purpleSphere = Sphere((-4,-4,0), 1.0, (1,0,1))
        
        # Create text mappers and 2d actors to display finger position.
        self.fingerMarker1 = Marker("(1)")
        self.fingerMarker2 = Marker("(2)")
        self.fingerMarker3 = Marker("(3)")

        # Add the actors to the renderer, set the background and size
        self.ren.AddActor(self.blueSphere.sphereActor)
        self.ren.AddActor(self.greenSphere.sphereActor)
        self.ren.AddActor(self.redSphere.sphereActor)
        self.ren.AddActor(self.yellowSphere.sphereActor)
        self.ren.AddActor(self.purpleSphere.sphereActor)
        self.ren.AddActor2D(self.fingerMarker1.textActor)
        self.ren.AddActor2D(self.fingerMarker2.textActor)
        self.propPicker.AddObserver("EndPickEvent", self.Pick)
        self.ren.SetBackground(0, 0, 0)
        self.renwin.SetSize(680, 460)
        #self.renwin.FullScreenOn()
        
        '''
        TUIO STUFF
        '''
        self.tracking = tuio.Tracking('')
        self.tracker = CursorTracker(2)
        self.pickedDemo = 0
Exemple #46
0
    def __init__(self):
        # Default interactor is responsible for moving the camera.
        self.default_interactor = vtk.vtkInteractorStyleTrackballCamera()
        # The picker allows us to know which object/actor is under the mouse.
        self.picker = vtk.vtkPropPicker()
        self.chosen_element = None
        self.event = Event()

        # Define some interaction states
        self.left_button_down = False
        self.right_button_down = False
        self.middle_button_down = False
        self.active_props = set()

        self.selected_props = {
            "left_button": set(),
            "right_button": set(),
            "middle_button": set()
        }
Exemple #47
0
 def iniVTK(self):
     self.last_added_sphere_ren1 = None
     self.newed_spheres = vtk.vtkCollection()
     self.sphere_radius_ren1 = 2.0
     self.bouttons_spheres = []
     self.slice_assembly = None
     self.image_roi = None
     self.im_importer = vtk.vtkImageImport()       
     self.sphere = vtk.vtkSphereSource()
     self.sphere.SetRadius(2.0)
     self.sphere_mapper = vtk.vtkPolyDataMapper()
     self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort())
     self.sphere_actor_ren2 = vtk.vtkActor()
     self.sphere.SetCenter(show_height / 2, show_width / 2, 0)
     self.sphere_actor_ren2.SetMapper(self.sphere_mapper)
     self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0)
     self.vtk_widget.GetRenderWindow().SetSize(800, 400)
     self.image_actor = vtk.vtkImageActor()
     self.ren1 = vtk.vtkRenderer()
     self.ren2 = vtk.vtkRenderer()
     self.interactorStyle = BouttonInteractorStyle()
     self.vtk_widget.SetInteractorStyle(self.interactorStyle)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1)
     self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2)
     self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0)
     self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0)
     self.ren2.AddActor(self.sphere_actor_ren2)
     self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors()
     self.imageLevelFilter.SetLevel(400)
     self.imageLevelFilter.SetWindow(800)
     self.im_importer.SetNumberOfScalarComponents(1)
     self.im_importer.SetDataScalarTypeToUnsignedShort()
     self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1, 0, 0)
     self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1, 0, 0)
     self.imageLevelFilter.SetInputConnection(self.im_importer.GetOutputPort())
     self.image_actor.SetInput(self.imageLevelFilter.GetOutput())
     self.ren1_sphere_actors = vtk.vtkActorCollection()
     self.pointPicker = vtk.vtkPointPicker()
     self.actorPicker = vtk.vtkPropPicker()
     self.pickedActor = None
     self.ren1.AddActor(self.image_actor)
     self.ren2.AddActor(self.image_actor)
Exemple #48
0
 def __init__(self, vtkDrawer, iren, renderer):
     """ vtkDrawer is an instance of VTKDrawer
     iren is a render window interactor."""
     self.highlight_level = .8 #The ambient lighting on selected items
     
     self.iren = iren
     self.ren1 = renderer
     self.drawer = vtkDrawer
     
     #set the picker so props can be picked
     self.picker = vtk.vtkPropPicker()
     iren.SetPicker(self.picker)
     
     #Add my own pick function
     self.observerNum = iren.AddObserver("LeftButtonPressEvent", self.pick)
     
     self.SelectedActor = None   #used by the pick() so that only one item is
                                 #picked at a time and it is not repicked
                                 
     #Right clicking will popup a window with display settings
     self.right_observerNum = iren.AddObserver("RightButtonPressEvent", self.rightClick)
Exemple #49
0
  def __init__(self, parent_qt_frame, progress_bar):
    super().__init__(parent_qt_frame)
    # This one indicates the progress of computationally heavy tasks
    self.__progress_bar = progress_bar

    # The observers of this guy
    self.__observers = list()

    # The render window
    #self.renderer.SetBackground(0.4, 0.41, 0.42)
    self.renderer.SetBackground(1.0, 1.0, 1.0)
    self.enable_depthpeeling()
    
    self.__interactor_style = vtk.vtkInteractorStyleTrackballCamera()
    self.__interactor_style.AddObserver("KeyReleaseEvent", self.__on_key_released)
    self.__interactor_style.AddObserver("LeftButtonPressEvent", self.__on_left_button_pressed)
    self.__interactor_style.AddObserver("LeftButtonReleaseEvent", self.__on_left_button_released)
    self.__interactor_style.AddObserver("RightButtonPressEvent", self.__on_right_button_pressed)
    self.__interactor_style.AddObserver("RightButtonReleaseEvent", self.__on_right_button_released)
    self.__interactor_style.AddObserver("MouseMoveEvent", self.__on_mouse_moved)
    self.interactor.SetInteractorStyle(self.__interactor_style)

    # This guy is very important: it handles all the model selection in the 3D view
    self.__prop3d_picker = vtk.vtkPropPicker()
    self.interactor.SetPicker(self.__prop3d_picker)
    self.__perform_prop3d_picking = True

    # We want to see xyz axes in the lower left corner of the window
    lower_left_axes_actor = vtk.vtkAxesActor()
    lower_left_axes_actor.SetXAxisLabelText("X")
    lower_left_axes_actor.SetYAxisLabelText("Y")
    lower_left_axes_actor.SetZAxisLabelText("Z")
    lower_left_axes_actor.SetTotalLength(1.5, 1.5, 1.5)
    self.__lower_left_axes_widget = vtk.vtkOrientationMarkerWidget()
    self.__lower_left_axes_widget.SetOrientationMarker(lower_left_axes_actor)
    self.__lower_left_axes_widget.KeyPressActivationOff()
    self.__lower_left_axes_widget.SetInteractor(self.render_window_interactor)
    self.__lower_left_axes_widget.SetViewport(0.0, 0.0, 0.2, 0.2)
    self.__lower_left_axes_widget.SetEnabled(1)
    self.__lower_left_axes_widget.InteractiveOff()
    def onLeftButtonReleaseEvent(self, obj, evt):
        if not self._mouseMoved:
            clickPos = self.GetInteractor().GetEventPosition()
            #Pick from this location
            picker = vtk.vtkPropPicker()
            picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())

            #If we picked something before, reset its property
            if self.lastPickedActor():
                self.lastPickedActor().GetProperty().DeepCopy(self._lastPickedProperty)

            self._lastPickedActor = weakref.ref(picker.GetActor()) if picker.GetActor() else None
            if self.lastPickedActor():
                #Save the property of the picked actor
                self._lastPickedProperty.DeepCopy(self.lastPickedActor().GetProperty())
                #Highlight the picked actor
                self.lastPickedActor().GetProperty().SetColor(1.0, 0.0, 0.0)
                self.lastPickedActor().GetProperty().SetDiffuse(1.0)
                self.lastPickedActor().GetProperty().SetSpecular(0.0)
            else:
                print 'No actor get pickered'

        #Call parent member
        self.OnLeftButtonUp()
Exemple #51
0
    def test_style(self, style):

        # Event state to test

        buttons = ["Left", "Middle", "Right"]
        ctrls = [0, 1]
        shifts = [0, 1]

        # I do not trust timers while testing (since they trigger asynchronous
        # rendering/interaction)

        use_timers = style.GetUseTimers()
        style.UseTimersOff()
        style.AutoAdjustCameraClippingRangeOn()

        print "Testing: " + style.GetClassName()

        iren = style.GetInteractor()
        renwin = iren.GetRenderWindow()

        renwin.Render()

        # Get renwin size and center

        win_size = renwin.GetSize()
        win_center_x = win_size[0] / (2.0)
        win_center_y = win_size[1] / (2.0)

        pick = vtk.vtkPropPicker()

        radius = 5 * (1 + use_timers)

        for ctrl in ctrls:
            for shift in shifts:
                print " - ctrl: " + str(ctrl) + " shift: " + str(shift) + " " + "button: ",
                for button in buttons:
                    print button,
                    # First try to find a starting position where an actor
                    # can be picked (not mandatory for trackball modes).
                    # Search in increasingly big area, until we reach win size
                    # in that case actors might not be on screen, so reset cam

                    search = radius
                    while True:
                        start_x = self.randint(win_center_x - search, win_center_x + search)
                        start_y = self.randint(win_center_x - search, win_center_x + search)
                        if pick.PickProp(start_x, start_y, self.ren1):
                            break
                        else:
                            if search > win_center_x or search > win_center_y:
                                print "   (resetting camera)",
                                self.ren1.ResetCamera()
                                search = radius
                            else:
                                search += 5

                    # Start by pressing the button

                    iren.SetEventInformationFlipY(start_x, start_y, ctrl, shift, '', 0, '')
                    eval('iren.InvokeEvent("' + button + 'ButtonPressEvent")')
                    pos = iren.GetEventPosition()
                    #print " - Starting: " + str(pos)

                    # Now move around (alternating left and right around
                    # the window center in order to compensate somehow).

                    sign = 1
                    for i in range(0, 2 + use_timers):
                        sign *= -1
                        x = self.randint(win_center_x + radius * 2 * sign, win_center_y + radius * sign)
                        y = self.randint(win_center_y + radius * 2 * sign, win_center_y + radius * sign)
                        iren.SetEventInformationFlipY(x, y, ctrl, shift, '', 0, '')
                        #pos = iren.GetEventPosition()
                        #lastPos = iren.GetLastEventPosition()
                        #print " - Moving:   " + str(pos) + " " + str(ctrl) + " " + str(shift) + " (was " + str(lastPos) + ")"
                        iren.InvokeEvent("MouseMoveEvent")

                        # If this style uses timers, run OnTimer multiple times

                        if use_timers:
                            for j in range(0, 10):
                                iren.InvokeEvent("TimerEvent")

                        renwin.Render()


                    # End by releasing the button

                    iren.SetEventInformationFlipY(x, y, ctrl, shift, '', 0, '')
                    eval('iren.InvokeEvent("' + button + 'ButtonReleaseEvent")')

                print "."

        style.SetUseTimers(use_timers)

        renwin.Render()
  def display_and_query(self):

    # Convert images to VTK data structures
    fixedVTKImage = self.fixedCL.toVTKImage()
    movingVTKImage = self.movingCL.toVTKImage()

    # Viewing parameters
    fixedFrame = self.get_frame(self.fixedCL.clarray.get())
    movingFrame = self.get_frame(self.movingCL.clarray.get())

    N = self.panelSize

    fixedShape = self.fixedCL.shape

    XC = [0, 0, 0]
    for d in range(3):
      XC[d] = fixedShape[d] / 2.0

    #
    # Create panel of views for fixed and moving image, with likely optimal
    # orientations
    #
    fixedArray = np.zeros((N*3, N*3), np.single)
    movingArray = np.zeros((N*3, N*3), np.single)

    for r in range(3):
      for c in range(3):
        V = self.get_slicing_matrix(fixedFrame[:,r], movingFrame[:,c])

        A = np.zeros((4,4))
        A[0:3,0] = V[:,0]
        A[0:3,1] = V[:,1]
        A[0:3,2] = V[:,2]
        A[0,3] = XC[0]
        A[1,3] = XC[1]
        A[2,3] = XC[2]
        A[3,3] = 1.0

        resliceAxes = vtk.vtkMatrix4x4()
        resliceAxes.DeepCopy(A.ravel().tolist())

        reslicef = vtk.vtkImageReslice()
        reslicef.SetInput(fixedVTKImage)
        reslicef.SetInformationInput(fixedVTKImage)
        reslicef.SetOutputExtent(0, N-1, 0, N-1, 0, 0)
        reslicef.SetOutputDimensionality(2)
        reslicef.SetResliceAxes(resliceAxes)
        reslicef.SetInterpolationModeToLinear()
        reslicef.Update()

        fixedSlice = vtk.util.numpy_support.vtk_to_numpy(
          reslicef.GetOutput().GetPointData().GetScalars() ).reshape(N, N)
        fixedSlice = np.transpose(fixedSlice)

        fixedArray[r*N:(r+1)*N, c*N:(c+1)*N] = fixedSlice

        resliceAxes = vtk.vtkMatrix4x4()
        resliceAxes.DeepCopy(A.ravel().tolist())

        reslicef = vtk.vtkImageReslice()
        reslicef.SetInput(movingVTKImage)
        reslicef.SetInformationInput(movingVTKImage)
        reslicef.SetOutputExtent(0, N-1, 0, N-1, 0, 0)
        reslicef.SetOutputDimensionality(2)
        reslicef.SetResliceAxes(resliceAxes)
        reslicef.SetInterpolationModeToLinear()
        reslicef.Update()

        movingSlice = vtk.util.numpy_support.vtk_to_numpy(
          reslicef.GetOutput().GetPointData().GetScalars() ).reshape(N, N)
        movingSlice = np.transpose(movingSlice)

        movingArray[r*N:(r+1)*N, c*N:(c+1)*N] = movingSlice

    #
    # Display panel of views with blending slider
    #

    def normalize(arr):
      minv = arr.min()
      maxv = arr.max()
      rangev = maxv - minv
      if rangev <= 0.0:
        return arr
      return (arr - minv) / rangev

    fixedArray = normalize(fixedArray)
    movingArray = normalize(movingArray)

    ren = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.SetWindowName("Image Alignment Query")
    renWin.SetSize(800, 800)

    renWin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    dataImporter = vtk.vtkImageImport()
    fixedArray_vtkorder = np.asfortranarray(fixedArray)
    fixedArray_vtkorder = fixedArray.transpose()
    ##dataImporter.CopyImportVoidPointer(fixedArray_vtkorder, fixedArray_vtkorder.nbytes)
    #dataImporter.CopyImportVoidPointer(fixedArray, fixedArray.nbytes)
    displayArray = np.uint8(fixedArray * 255)
    dataImporter.CopyImportVoidPointer(displayArray, displayArray.nbytes)
    #dataImporter.SetDataScalarTypeToFloat()
    dataImporter.SetDataScalarTypeToUnsignedChar()
    dataImporter.SetNumberOfScalarComponents(1)
    dataImporter.SetDataExtent(0, N*3-1, 0, N*3-1, 0, 0)
    dataImporter.SetWholeExtent(0, N*3-1, 0, N*3-1, 0, 0)
    dataImporter.Update()

    imageActor = vtk.vtkImageActor()
    imageActor.SetInput(dataImporter.GetOutput())
    imageActor.SetPosition(100.0, 100.0, 0.0)
    imageActor.SetZSlice(0)
    imageActor.PickableOn()

    imageStyle = vtk.vtkInteractorStyleImage()
    iren.SetInteractorStyle(imageStyle)

    ren.AddActor(imageActor)

    def slider_callback(obj, event):
      # Get slider value
      alpha = obj.GetRepresentation().GetValue()

      displayArray = fixedArray * alpha + movingArray * (1.0 - alpha)

      #minI = displayArray.min()
      #maxI = displayArray.max()
      #displayArray = (displayArray - minI) / (maxI - minI) * 255
      #displayArray = np.uint8(displayArray)
      #displayArray = np.uint8(normalize(displayArray) * 255)
      displayArray = np.uint8(displayArray * 255)

      dataImporter.CopyImportVoidPointer(displayArray, displayArray.nbytes)

    sliderRep  = vtk.vtkSliderRepresentation2D()
    sliderRep.SetMinimumValue(0.0)
    sliderRep.SetMaximumValue(1.0)
    sliderRep.SetValue(1.0)
    #sliderRep.SetTitleText("Fixed vs moving")
    sliderRep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    sliderRep.GetPoint1Coordinate().SetValue(0.2, 0.1)
    sliderRep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    sliderRep.GetPoint2Coordinate().SetValue(0.8, 0.1)

    sliderWidget = vtk.vtkSliderWidget()
    sliderWidget.SetInteractor(iren)
    sliderWidget.SetRepresentation(sliderRep)
    sliderWidget.AddObserver("InteractionEvent", slider_callback)
    sliderWidget.EnabledOn()

    #ren.InteractiveOff()
    renWin.AddRenderer(ren)

    picker = vtk.vtkPropPicker()
    #picker = vtk.vtkWorldPointPicker()
    picker.PickFromListOn()
    picker.AddPickList(imageActor)

    self.queryRowColumn = (0, 0)

    def pick_callback(obj, event):
      mousePos = obj.GetEventPosition()

      picker.PickProp(mousePos[0], mousePos[1], ren)

      p = picker.GetPickPosition()
      c = round( (p[0]-100) / (3*N) * 2 )
      r = round( (p[1]-100) / (3*N) * 2 )

      if r < 0 or r >= 3 or c < 0 or c >= 3:
        print "Outside"
        return

      print "Image row", r, "col", c

      self.queryRowColumn = (r, c)

      iren.GetRenderWindow().Finalize()
      iren.TerminateApp()

    iren.SetPicker(picker)
    iren.AddObserver("LeftButtonPressEvent", pick_callback)

    renWin.Render()
    iren.Start()

    # Return selection of a view in panel
    r, c = self.queryRowColumn

    fixedSlice = fixedArray[r*N:(r+1)*N, c*N:(c+1)*N]
    movingSlice = movingArray[r*N:(r+1)*N, c*N:(c+1)*N]

    return fixedSlice, movingSlice, fixedFrame[:,r], movingFrame[:,c]
Exemple #53
0
    def __init__(self):

        ### Create our VTK Render Window and Interactor
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(1.0, 1.0, 1.0)
        self.renwin = vtk.vtkRenderWindow()
        self.renwin.AddRenderer(self.ren)
        self.renwin.SetSize(820,600)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renwin)
        self.iren.SetInteractorStyle(None)
        self.iren.LightFollowCameraOff()
        self.camera = self.ren.GetActiveCamera()
        ### gimme some point-n-click:
        self.picker = vtk.vtkPropPicker()
        self.lastPickedActor = 0

        ### Add some event handlers to the VTK Window Interactor
        #print "Adding TimerHandler."
        self.iren.AddObserver("TimerEvent", self.TimerHandler)
        self.iren.AddObserver("KeyPressEvent", self.KeyEvent)
        self.iren.AddObserver("KeyReleaseEvent", self.KeyEvent)
        self.iren.AddObserver("LeftButtonPressEvent", self.ButtonEvent)
        #self.iren.AddObserver("LeftButtonReleaseEvent", self.ButtonEvent)
        self.iren.AddObserver("MiddleButtonPressEvent", self.ButtonEvent)
        self.iren.AddObserver("MiddleButtonReleaseEvent", self.ButtonEvent)
        #self.iren.AddObserver("RightButtonPressEvent", self.ButtonEvent)
        #self.iren.AddObserver("RightButtonReleaseEvent", self.ButtonEvent)
        self.iren.AddObserver("MouseMoveEvent", self.MouseMove)
        self.iren.AddObserver("EnterEvent", self.MouseEnters)
        self.iren.AddObserver("LeaveEvent", self.MouseLeaves)

        ### These are "stateful" things that might be occuring in the Interactor
        self.XkeyRepeat = 1
        self.Wireframing = 0
        self.Headlighting = 0
        self.OutOfBodyPerspective = 0
        self.Rotating = 0
        self.translatingForward = 0
        self.translatingBackward = 0
        self.translatingUp = 0
        self.translatingDown = 0
        self.translatingLeft = 0
        self.translatingRight = 0
        self.turningLeft = 0
        self.turningRight = 0
        self.status = ""
        self.osdLines = ['', '', '', '']
        self.numberOfosdLines = len(self.osdLines)

        ##
        self.iAmMoving = 0
        self.PleaseRender = 0
        self.PleaseSendUDPpackets = 0

        ### Let's keep track of the things that we are rendering:
        self.maps = {} # collections of vtkActor's and vtkLight's
        self.characters = {} # vtkAssembly's that are connected to JIDs
        self.BoundTo = 0  # Which JID is "me"?

        self.timerCount = 0  # how long since we last rendered a frame?

        # We have a network UDP socket (jvIOSocket) to rapidly interact 
        # with other viewers.  We use UDP to send and receive MOVE commands, 
        # using a binary protocol, in case we ever want to do fast 
        # video-game-stuff on a LAN or something
        self.authorizedUDPpackets = {} # who are we receiving packets from?
        self.UDPRecipients = [] # who are we sending packets to?

        ##  The "IO" socket is for peer-to-peer communications
        self.jvIOSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            self.jvIOSocket.bind( ("localhost", 49005) )
        except socket.error, err:
            logging.critical("Failed to bind IO socket: %s" % err)
            sys.exit(1)
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, size=wx.Size(320, 320))
        self.SetBackgroundColour(wx.Colour(0, 0, 0))

        self.interaction_style = st.StyleStateManager()

        self.ball_reference = None
        self.initial_foco = None

        style =  vtk.vtkInteractorStyleTrackballCamera()
        self.style = style

        interactor = wxVTKRenderWindowInteractor(self, -1, size = self.GetSize())
        interactor.SetInteractorStyle(style)
        self.interactor = interactor

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(interactor, 1, wx.EXPAND)
        self.sizer = sizer
        self.SetSizer(sizer)
        self.Layout()

        # It would be more correct (API-wise) to call interactor.Initialize() and
        # interactor.Start() here, but Initialize() calls RenderWindow.Render().
        # That Render() call will get through before we can setup the
        # RenderWindow() to render via the wxWidgets-created context; this
        # causes flashing on some platforms and downright breaks things on
        # other platforms.  Instead, we call widget.Enable().  This means
        # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE,
        # that doesn't matter.
        interactor.Enable(1)

        ren = vtk.vtkRenderer()
        interactor.GetRenderWindow().AddRenderer(ren)
        self.ren = ren

        self.raycasting_volume = False

        self.onclick = False

        self.text = vtku.Text()
        self.text.SetValue("")
        self.ren.AddActor(self.text.actor)


        self.slice_plane = None

        self.view_angle = None

        self.__bind_events()
        self.__bind_events_wx()

        self.mouse_pressed = 0
        self.on_wl = False

        self.picker = vtk.vtkPointPicker()
        interactor.SetPicker(self.picker)
        self.seed_points = []

        self.points_reference = []

        self.measure_picker = vtk.vtkPropPicker()
        #self.measure_picker.SetTolerance(0.005)
        self.measures = []

        self._last_state = 0

        self.repositioned_axial_plan = 0
        self.repositioned_sagital_plan = 0
        self.repositioned_coronal_plan = 0
        self.added_actor = 0

        self._mode_cross = False
        self._to_show_ball = 0
        self._ball_ref_visibility = False
Exemple #55
0
    def __init__(self):

        ### Create our VTK Render Window and Interactor
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(1.0, 1.0, 1.0)
        self.renwin = vtk.vtkRenderWindow()
        self.renwin.AddRenderer(self.ren)
        self.renwin.SetSize(820,600)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renwin)
        self.iren.SetInteractorStyle(None)
        self.iren.LightFollowCameraOff()
        self.camera = self.ren.GetActiveCamera()
        ### gimme some point-n-click:
        self.picker = vtk.vtkPropPicker()
        self.lastPickedActor = 0

        ### Add some event handlers to the VTK Window Interactor
        #print "Adding TimerHandler."
        self.iren.AddObserver("TimerEvent", self.TimerHandler)
        self.iren.AddObserver("KeyPressEvent", self.KeyEvent)
        self.iren.AddObserver("KeyReleaseEvent", self.KeyEvent)
        self.iren.AddObserver("LeftButtonPressEvent", self.ButtonEvent)
        #self.iren.AddObserver("LeftButtonReleaseEvent", self.ButtonEvent)
        self.iren.AddObserver("MiddleButtonPressEvent", self.ButtonEvent)
        self.iren.AddObserver("MiddleButtonReleaseEvent", self.ButtonEvent)
        #self.iren.AddObserver("RightButtonPressEvent", self.ButtonEvent)
        #self.iren.AddObserver("RightButtonReleaseEvent", self.ButtonEvent)
        self.iren.AddObserver("MouseMoveEvent", self.MouseMove)
        self.iren.AddObserver("EnterEvent", self.MouseEnters)
        self.iren.AddObserver("LeaveEvent", self.MouseLeaves)

        ### These are "stateful" things that might be occuring in the Interactor
        self.XkeyRepeat = 1
        self.Wireframing = 0
        self.Headlighting = 0
        self.OutOfBodyPerspective = 0
        self.Rotating = 0
        self.translatingForward = 0
        self.translatingBackward = 0
        self.translatingUp = 0
        self.translatingDown = 0
        self.translatingLeft = 0
        self.translatingRight = 0
        self.turningLeft = 0
        self.turningRight = 0
        self.status = ""
        self.osdLines = ['', '', '', '']
        self.numberOfosdLines = len(self.osdLines)

        ##
        self.iAmMoving = 0
        self.PleaseRender = 0
        self.PleaseSendUDPpackets = 0

        ### Let's keep track of the things that we are rendering:
        self.maps = {} # collections of vtkActor's and vtkLight's
        self.characters = {} # vtkAssembly's that are connected to JIDs
        self.BoundTo = 0  # Which JID is "me"?

        self.timerCount = 0  # how long since we last rendered a frame?

        # We have a network UDP socket (jvIOSocket) to rapidly interact 
        # with other viewers.  We use UDP to send and receive MOVE commands, 
        # using a binary protocol, in case we ever want to do fast 
        # video-game-stuff on a LAN or something
        self.authorizedUDPpackets = {} # who are we receiving packets from?
        self.UDPRecipients = [] # who are we sending packets to?

        ##  The "IO" socket is for peer-to-peer communications
        self.jvIOSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            self.jvIOSocket.bind( ("localhost", 49005) )
        except socket.error as err:
            logging.critical("Failed to bind IO socket: %s" % (err))
            sys.exit(1)
 
        self.jvIOSocketLocalAddr = self.jvIOSocket.getsockname()
        logging.info("IO socket is bound to: %s" % str(self.jvIOSocketLocalAddr))
        print("IO_socket:      UDP: %s:%i" % (self.jvIOSocketLocalAddr[0], self.jvIOSocketLocalAddr[1]))
        self.jvIOSocket.setblocking(0)

        ##  The "MC" socket is for local master-slave communications
        try:
            os.remove(jvCommandSocketFileName)
        except:
            pass
        self.jvMCSocket = socket.socket(socket.AF_UNIX)
        try:
            self.jvMCSocket.bind(jvCommandSocketFileName)
        except socket.error as err:
            logging.critical("Failed to bind MC socket: %s" % (err))
            sys.exit(1)
        self.jvMCSocket.listen(1)
        self.MCsocketList = [self.jvMCSocket]
        print("MC_socket:     UNIX: %s" % (jvCommandSocketFileName))
 

        ###  Create the OSDs (On-Screen Displays)  ("status" and "primary")
        self.osdStatus = vtk.vtkTextActor()
        #self.osdStatus.ScaledTextOff()   #deprecated in 5.4
        self.osdStatus.SetDisplayPosition(9, 10)
        self.osdStatusBackground = primitives.create2dRectangle(0, 5, 1600, 22)
        self.ren.AddActor2D(self.osdStatusBackground.actor)
        self.ren.AddActor2D(self.osdStatus)

        tprop = self.osdStatus.GetTextProperty()
        tprop.SetFontSize(14)
        tprop.SetFontFamilyToCourier()
        tprop.SetColor(0, 0, 0)

        self.osdPrimary = vtk.vtkTextActor()
        #self.osdPrimary.ScaledTextOff()   #deprecated in 5.4
        self.osdPrimary.SetDisplayPosition(9, 32)
        self.osdStatusBackground = primitives.create2dRectangle(0, 27, 1600, self.numberOfosdLines * 17 +24)
        self.ren.AddActor2D(self.osdStatusBackground.actor)
        self.ren.AddActor2D(self.osdPrimary)

        tprop = self.osdPrimary.GetTextProperty()
        tprop.SetFontSize(14)
        tprop.SetFontFamilyToCourier()
        tprop.SetColor(0, 0, 0)
Exemple #56
0
    def keypress_handler(self, obj, event):

        key = obj.GetKeyCode()
        pos2d = obj.GetEventPosition()

        # create new sphere
        if key == "k":

            self.scene.add_articulation_sphere(pos2d)

        # mark sphere for connection if no other marker set, connect otherwise
        elif key == "c":

            selected_sphere = None # there should be at most 1
            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    selected_sphere = sphere
                    break
            if not selected_sphere: return
            picker = vtk.vtkPropPicker()
            if picker.PickProp(pos2d[0], pos2d[1], self.frame.ren):
                actor = picker.GetActor()
                if self.scene.get_active_polytube_model() and \
                  actor is self.scene.get_active_polytube_model().actor:
                    m = self.scene.get_active_polytube_model()
                    m.connect_articulation_sphere_to_closest_point(
                                                        selected_sphere, pos2d)

        # select sphere (only one at a time)
        elif key == "s":

            for sphere in self.scene.actor_to_sphere.values():
                sphere.set_selected(False)

            picker = vtk.vtkPropPicker()
            if picker.PickProp(pos2d[0], pos2d[1], self.frame.ren):
                actor = picker.GetActor()
                if actor in self.scene.actor_to_sphere:
                    self.scene.actor_to_sphere[actor].toggle_selected()

        # delete selected sphere
        elif key == "d":

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    self.scene.delete_articulation_sphere(sphere)
                    sphere.run_callbacks('delete')

        elif key == 'D':

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    n = sphere.delete_selected_points()
                    self.frame.SetStatusText('Deleted %d points' % n)
                    wiz = self.frame.mvl_wiz
                    if wiz.model is not None and wiz.curr_page == wiz.pages[0]:
                        wiz.model.P = self.scene.get_active_point_cloud().P
                        wiz.curr_page.on_run(None)

        # cut polytube model node
        elif key in 'xX':

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    if key == 'x':
                        sphere.run_callbacks('cut_above')
                    else:
                        sphere.run_callbacks('cut_branch')

        # fly-to (set camera focal point)
        elif key == "f":

            if self.scene.get_active_point_cloud():
                self.scene.get_active_point_cloud().actor.SetPickable(True)
                picker = vtk.vtkPointPicker()
                if picker.Pick(pos2d[0], pos2d[1], 0, self.frame.ren):
                    self.frame.iren.FlyTo(self.frame.ren,
                                          *picker.GetPickPosition())
                self.scene.get_active_point_cloud().actor.SetPickable(False)

        elif key == 'N':

            for sphere in self.scene.actor_to_sphere.values():
                if sphere.is_selected:
                    wiz = self.frame.mvl_wiz
                    if wiz.model is not None and wiz.curr_page == wiz.pages[0]:
                        sphere.stitch_neighborhood_graph(wiz.model.N_full)
                        wiz.model.find_nn_connected_components()
                        n_comps, n_nodes_biggest, density = \
                                            wiz.model.get_connectivity_infos()
                        self.scene.set_point_cloud_graph(wiz.model.N_full)
                        wiz.pages[0].set_nn_connected_components_color_scheme(
                                                         wiz.model.N_components)
                        wiz.pages[1].is_dirty = True
                        st = 'Found %s connected component%s (biggest has ' \
                             '%s nodes; conn. factor = %f)' % \
                             (n_comps, 's' if n_comps>1 else '',
                              n_nodes_biggest, density)
                        self.frame.SetStatusText(st)
	def selectNode(self):
		# (x0,y0) = self.interactor.GetLastEventPosition()
		(x,y) = self.interactor.GetEventPosition()
		cellPicker = vtk.vtkCellPicker()
		someCellPicked = cellPicker.Pick(x,y,0,self.renderer)
		pickedCellId = cellPicker.GetCellId()
		propPicker = vtk.vtkPropPicker()
		somePropPicked = propPicker.PickProp(x,y,self.renderer)
		pickedProp = propPicker.GetViewProp()
		navigated = False
		# NOTE: For some reason, sometimes on switching data sets
		#   we're getting to the print statement with scale_list undefined
		#   so I added this initialization...
		scale_list = []
		
		# Navigate with buttons
		if somePropPicked and (pickedProp != self.icicle_actor):
			# First, test whether there is a current selection because we can only move if
			# there was a selection to move in the first place
			if self.output_link.GetCurrentSelection().GetNumberOfNodes() > 0:
				# If so, get the current pedigree_id
				prev_ped_vtk = self.output_link.GetCurrentSelection().GetNode(0).GetSelectionList()
				# NOTE: Counting on a single ID
				prev_ped_id = prev_ped_vtk.GetValue(0)
				# Now figure out which menu item was picked
				for ii, m_actor in enumerate(self.menu.GetActorList()):
					if pickedProp == m_actor:
						# print "Menu Actor picked, index = ", ii
						# Call the proper nav routine and get back the new ped_id
						new_ped_id = self.menu_functions[ii](prev_ped_id)
						new_ped_n = N.array([new_ped_id], dtype='int64')
						new_ped_vtk = VN.numpy_to_vtkIdTypeArray(new_ped_n, deep=True)
						self.output_link.GetCurrentSelection().GetNode(0).SetSelectionList(new_ped_vtk)
						self.output_link.InvokeEvent("AnnotationChangedEvent")
						self.applycolors1.Update()
						self.renWin.Render()			
						# Set list for scale_link
						scale_list = [self.ds.Scales[new_ped_id]]
						navigated = True
					
		# Pick a cell of the icicle view
		# Cell picker doesn't work with Actor2D, so nav menu won't report any cells
		if someCellPicked and not navigated:
			print "Icicle picked cell index: ", pickedCellId
			# Assuming for now that this is a cell "Index", so getting pedigree ID
			sel = vtk.vtkSelection()
			node = vtk.vtkSelectionNode()
			node.SetFieldType(0)		# Cell
			node.SetContentType(4)		# Indices
			id_array = N.array([pickedCellId], dtype='int64')
			id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True)
			node.SetSelectionList(id_vtk)
			sel.AddNode(node)
			# Note: When selection is cleared, the current selection does NOT contain any nodes
			self.areapoly1.Update()
			cs = vtk.vtkConvertSelection()
			pedIdSelection = cs.ToPedigreeIdSelection(sel, self.areapoly1.GetOutput())
			pedIdSelection.GetNode(0).SetFieldType(3)	# convert to vertext selection
			
			# Copy converted selection to output annotation link (fires AnnotationChangedEvent)
			self.output_link.SetCurrentSelection(pedIdSelection)
			self.applycolors1.Update()
			self.renWin.Render()
			# Set list for scale_link
			scale_list = [self.ds.Scales[pickedCellId]]
			
		if not someCellPicked and not somePropPicked:
			# reset selection to blank
			print "Blank selection"
			return
			self.output_link.GetCurrentSelection().RemoveAllNodes()
			self.output_link.InvokeEvent("AnnotationChangedEvent")
			self.applycolors1.Update()
			self.renWin.Render()
			# Set list for scale_link
			scale_list = []

		print "scale picked in icicle view: ", scale_list
		
		id_array = N.array(scale_list, dtype='int64')
		id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True)
		self.scale_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_vtk)
		# For now want this event to trigger detail view, but not internal scale selection callback
		self.scale_internal_call = True
		self.scale_link.InvokeEvent("AnnotationChangedEvent")
 def button_down(*args):
     #print "button down on brain interact."
     x, y = self.GetEventPosition()
     picker = vtk.vtkPropPicker()
     picker.PickProp(x, y, self.renderer)
     actor = picker.GetActor()
Exemple #59
0
    def bimodal_mouse_handler(self, obj, event):

        # mouse wheel: camera mode only

        if event.endswith('PressEvent'):
            wx.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
        elif event.endswith('ReleaseEvent'):
            wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

        if event.startswith('MouseWheel'):
            self.frame.iren.SetInteractorStyle(self.camera_style)
            if event == 'MouseWheelForwardEvent':
                self.camera_style.OnMouseWheelForward()
            else: self.camera_style.OnMouseWheelBackward()
            return

        # detect double-click
        is_dbl_click = (event == 'LeftButtonReleaseEvent' and
                        self.frame.last_mouse_event == 'LeftButtonReleaseEvent')
        self.frame.last_mouse_event = event

        if is_dbl_click:

            pos2d = self.frame.iren.GetEventPosition()
            picker = vtk.vtkPropPicker()
            if picker.PickProp(pos2d[0], pos2d[1], self.frame.ren):
                # picked already existing sphere: select and fly-to
                if picker.GetActor() in self.scene.actor_to_sphere:
                    picked_sphere = self.scene.actor_to_sphere[picker.GetActor()]
                    self.scene.unselect_all_articulation_spheres()
                    picked_sphere.set_selected(True)
                    self.frame.iren.FlyTo(self.frame.ren,
                                          *picked_sphere.get_position())
                # add polytube articulation
                elif self.scene.get_active_polytube_model() and \
                  picker.GetActor() is \
                            self.scene.get_active_polytube_model().actor:
                    m = self.scene.get_active_polytube_model()
                    m.add_articulation_sphere_to_closest_point(pos2d)
            else:
                self.scene.add_articulation_sphere(pos2d)
            return

        # try to pick a sphere
        picker = vtk.vtkPropPicker()
        pos2d = self.frame.iren.GetEventPosition()
        if picker.PickProp(pos2d[0], pos2d[1], self.frame.ren):
            if picker.GetActor() in self.scene.actor_to_sphere and \
                   self.scene.actor_to_sphere[picker.GetActor()].is_selected:
                self.scene.picked_sphere_actor = picker.GetActor()

        # camera mode
        if not self.scene.picked_sphere_actor:

            # make sure it's reset when picked_non_movable_sphere
            self.scene.picked_sphere_actor = None
            self.frame.iren.SetInteractorStyle(self.camera_style)
            if event == 'LeftButtonPressEvent':
                self.camera_style.OnLeftButtonDown()
            elif event == 'LeftButtonReleaseEvent':
                self.camera_style.OnLeftButtonUp()
            elif event == 'MiddleButtonPressEvent':
                self.camera_style.OnMiddleButtonDown()
            elif event == 'MiddleButtonReleaseEvent':
                self.camera_style.OnMiddleButtonUp()
            elif event == 'RightButtonPressEvent':
                self.camera_style.OnRightButtonDown()
            elif event == 'RightButtonReleaseEvent':
                self.camera_style.OnRightButtonUp()

        # actor mode
        else:

            self.frame.iren.SetInteractorStyle(self.actor_style)
            psa = self.scene.picked_sphere_actor
            picked_sphere = self.scene.actor_to_sphere[psa]

            if event.endswith('ButtonReleaseEvent'):
                picked_sphere.update()
                picked_sphere.run_callbacks('moved')
                self.scene.picked_sphere_actor = None
            if event in ['LeftButtonPressEvent', 'MiddleButtonPressEvent']:
                self.actor_style.OnMiddleButtonDown()
            elif event in ['LeftButtonReleaseEvent', 'MiddleButtonReleaseEvent']:
                self.actor_style.OnMiddleButtonUp()
            elif event == 'RightButtonPressEvent':
                self.actor_style.OnRightButtonDown()
            elif event == 'RightButtonReleaseEvent':
                self.actor_style.OnRightButtonUp()