#!/usr/bin/python
#dv3d_data_PolyDataClipper.py
#Adds a polydata clipper to loaded surfaces
#DV3D refactor 2
#AG 31/07/2013


import vtk
from dv3d_data_updateAllViews import *


def AddPolyDataClipper(the_parent_window, theVTKSurfaceActor):
    
    tpw = the_parent_window #for brevity

    #reverse engineer the input back to basic polydata
    thePolyData = theVTKSurfaceActor.GetMapper().GetInput() 

    thePolyData.Update()

    #set up the vtk classes we need    
    clipPlanes = vtk.vtkPlanes()

    clipper = vtk.vtkClipPolyData()
    clipper.SetInput(thePolyData)
    clipper.SetClipFunction(clipPlanes)
    clipper.InsideOutOn()

    clipMapper = vtk.vtkPolyDataMapper()
    clipMapper.SetInput(clipper.GetOutput())
    clipMapper.ScalarVisibilityOff()

    clipActor = vtk.vtkActor()
    clipActor.SetMapper(clipMapper)

    #inherit the colors and transparency assigned to the original actor
    clipActor.GetProperty().SetColor(theVTKSurfaceActor.GetProperty().GetColor())
    clipActor.GetProperty().SetOpacity(theVTKSurfaceActor.GetProperty().GetOpacity())

    
    # This callback funciton does the actual work: updates the vtkPlanes
    # implicit function.  This in turn causes the pipeline to update.
    def SelectPolygons(object, event):
        # object will be the boxWidget
        object.GetPlanes(clipPlanes)
        clipActor.VisibilityOn()
        
    def RefreshMe(object, event):
        object.GetPlanes(clipPlanes)
        clipActor.VisibilityOn()
        clipActor.ClipperBoxWidget.Modified()
        dv3d_data_updateAllViews(tpw)
        
   
    boxWidget = vtk.vtkBoxWidget()
    boxWidget.SetPriority(1.0)
    boxWidget.SetInteractor(tpw.iwidget_3d.interactor)
    boxWidget.KeyPressActivationOff()
    boxWidget.SetPlaceFactor(1.25)
    
    clipActor.Clipper = clipper
    
    clipActor.ClipperBoxWidget = boxWidget
    clipActor.ClipperBoxWidget.SetInput(thePolyData)
            
    clipActor.ClipperBoxWidget.PlaceWidget()
    clipActor.ClipperBoxWidget.AddObserver("StartInteractionEvent", SelectPolygons)
    clipActor.ClipperBoxWidget.AddObserver("EndInteractionEvent", RefreshMe)
    clipActor.ClipperBoxWidget.AddObserver("WidgetModifiedEvent", RefreshMe)
        
    clipActor.VisibilityOn()

    #CRUCIAL: invoke an event to draw the surface and generate the Plane properties
    SelectPolygons(boxWidget,None)

    return clipActor, clipPlanes, clipper



