/*=========================================================================

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/VolViewCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME vtkSplineSurfaceWidget - 3D widget for manipulating a spline surface patch.
// .SECTION Description
//
// This class was created as a variation of the vtkSplineWidget.
//
// This 3D widget defines a spline that can be interactively placed in a
// scene. The spline has handles, the number of which can be changed, plus it
// can be picked on the spline itself to translate or rotate it in the scene.
// A nice feature of the object is that the vtkSplineSurfaceWidget, like any 3D
// widget, will work with the current interactor style. That is, if
// vtkSplineSurfaceWidget does not handle an event, then all other registered
// observers (including the interactor style) have an opportunity to process
// the event. Otherwise, the vtkSplineSurfaceWidget will terminate the processing of
// the event that it handles.
//
// To use this object, just invoke SetInteractor() with the argument of the
// method a vtkRenderWindowInteractor.  You may also wish to invoke
// "PlaceWidget()" to initially position the widget. The interactor will act
// normally until the "i" key (for "interactor") is pressed, at which point the
// vtkSplineSurfaceWidget will appear. (See superclass documentation for information
// about changing this behavior.) By grabbing one of the spherical
// handles (use the left mouse button), the spline can be oriented and
// stretched (the other handles remain fixed). By grabbing the spline
// itself (left or middle mouse button), the entire spline can be translated.
// (Translation can also be employed by using the "shift-left-mouse-button"
// combination inside of the widget.) Scaling (about the center of the spline)
// is achieved by using the right mouse button. By moving the mouse "up" the
// render window the spline will be made bigger; by moving "down" the render
// window the widget will be made smaller.  Finally, holding the ctrl key down
// and then grabbing either a handle or the spline itself with the middle mouse
// button enalbles spinning of the widget about its center. Events that occur
// outside of the widget (i.e., no part of the widget is picked) are propagated
// to any other registered obsevers (such as the interaction style).  Turn off
// the widget by pressing the "i" key again (or invoke the Off() method).
//
// The vtkSplineSurfaceWidget has several methods that can be used in conjunction with
// other VTK objects. The Set/GetResolutionU() methods control the number of
// subdivisions of the spline; the GetPolyData() method can be used to get the
// polygonal representation and can be used for things like seeding
// streamlines or probing other data sets. Typical usage of the widget is to
// make use of the StartInteractionEvent, InteractionEvent, and
// EndInteractionEvent events. The InteractionEvent is called on mouse motion;
// the other two events are called on button down and button up (either left or
// right button).
//
// Some additional features of this class include the ability to control the
// properties of the widget. You can set the properties of the selected and
// unselected representations of the spline. For example, you can set the
// property for the handles and spline. In addition there are methods to
// constrain the spline so that it is aligned with a plane.  

// .SECTION Thanks
// Thanks to Dean Inglis for developing and contributing this class.

// .SECTION Caveats
// Note that handles and line can be picked even when they are "behind" other
// actors.  This is an intended feature and not a bug.

// .SECTION See Also
// vtk3DWidget vtkBoxWidget vtkLineWidget vtkPointWidget vtkSphereWidget
// vtkImagePlaneWidget vtkImplicitPlaneWidget vtkPlaneWidget


#ifndef __vtkSplineSurfaceWidget_h
#define __vtkSplineSurfaceWidget_h

#include "vtk3DWidget.h"

class vtkActor;
class vtkCellPicker;
class vtkPlaneSource;
class vtkPoints;
class vtkPolyData;
class vtkPolyDataMapper;
class vtkProp;
class vtkProperty;
class vtkCylinderSource;
class vtkCardinalSplinePatch;
class vtkTransform;

#define VTK_PROJECTION_YZ 0
#define VTK_PROJECTION_XZ 1
#define VTK_PROJECTION_XY 2
#define VTK_PROJECTION_OBLIQUE 3

class VTK_EXPORT vtkSplineSurfaceWidget : public vtk3DWidget
{
public:
  // Description:
  // Instantiate the object.
  static vtkSplineSurfaceWidget *New();

  vtkTypeRevisionMacro(vtkSplineSurfaceWidget,vtk3DWidget);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Methods that satisfy the superclass' API.
  virtual void SetEnabled(int);
  virtual void PlaceWidget(double bounds[6]);
  void PlaceWidget()
    {this->Superclass::PlaceWidget();}
  void PlaceWidget(double xmin, double xmax, double ymin, double ymax, 
                   double zmin, double zmax)
    {this->Superclass::PlaceWidget(xmin,xmax,ymin,ymax,zmin,zmax);}

  // Description:
  // Set up a reference to a vtkPlaneSource that could be from another widget
  // object, e.g. a vtkPolyDataSourceWidget.
  void SetPlaneSource(vtkPlaneSource* plane);

  // Description:
  // Grab the polydata (including points) that defines the spline.  The
  // polydata consists of the NumberOfSplinePoints points. These point values
  // are guaranteed to be up-to-date when either the InteractionEvent or
  // EndInteraction events are invoked. The user provides the vtkPolyData and
  // the points and polyline are added to it.
  virtual void GetPolyData(vtkPolyData *pd);
  virtual vtkPolyData * GetSurfaceData();
  virtual unsigned int  GetNumberOfSurfacePoints();

  // Description:
  // Set/Get the handle properties (the little balls are the handles). The
  // properties of the handles when selected and normal can be manipulated.
  virtual void SetHandleProperty(vtkProperty*);
  vtkGetObjectMacro(HandleProperty, vtkProperty);
  virtual void SetSelectedHandleProperty(vtkProperty*);
  vtkGetObjectMacro(SelectedHandleProperty, vtkProperty);

  // Description:
  // Set/Get the line properties. The properties of the line when selected
  // and unselected can be manipulated.
  virtual void SetSurfaceProperty(vtkProperty*);
  vtkGetObjectMacro(SurfaceProperty, vtkProperty);
  virtual void SetSelectedSurfaceProperty(vtkProperty*);
  vtkGetObjectMacro(SelectedSurfaceProperty, vtkProperty);


  // Description:
  // Get the Visibility property of the surface actor
  virtual int GetSurfaceVisibility();
  
  // Description:
  // Set/Get the number of handles for this widget.
  vtkGetMacro(NumberOfHandles, int);
  virtual void SetNumberOfHandles(int numberOfHandles);

  // Description:
  // Set/Get the number of line segments representing the spline for
  // this widget.
  virtual void GenerateSurfacePoints();

  // Description:
  // Set/Get the position of the spline handles. Call GetNumberOfHandles
  // to determine the valid range of handle indices.  Set/Get the positions of
  // all the handles. They expect the user to pass an array already allocated
  // for 3xNumberofHandles.
  void SetHandlePosition(int handle, double x, double y, double z);
  void SetHandlePosition(int handle, double xyz[3]);
  void GetHandlePosition(int handle, double xyz[3]);
  double* GetHandlePosition(int handle);
  void SetHandlePositions(float * xyz);
  int  GetHandlePositions(float * xyz);

  // Description:
  // Set/Get the flag indicating whether the widget is used in Remote mode or
  // not. In this mode, whenever a handle is modified, instead of recomputing
  // the surface directly with the BuildRepresentation() method, the spline
  // invokes an event. Another class in the application must listen to those
  // events and invoke the local BuildRepresentation() method in all the
  // remotely controlled splines. If the controlling class does not invoke the
  // BuildRepresentation() method in this spline, then its state will be
  // inconsistent. This may be risky but seems to be better that having to keep
  // track of what changes actually occurred and figure out whether the spline
  // surface should be  recomputed or not.
  vtkSetMacro(RemoteMode,int);
  vtkGetMacro(RemoteMode,int);

  // Description:
  // Insert and Remove Handles. Note that not all derived classes will respond
  // to this invokations. By default these methods are a null operation.
  virtual void InsertHandle();
  virtual void InsertHandle(double position[3]);
  virtual void RemoveHandle();
  virtual void RemoveHandle(int handleIndex);

  // Description:
  // Events. 
  //BTX
  enum
  {
    SplineSurfaceHandlePositionChangedEvent = 10000,
    SplineSurfaceHandleChangedEvent,
    SplineSurface2DHandlePositionChangedEvent,
    SplineSurface2DHandleChangedEvent,
    SplineSurfaceNumberOfHandlesChangedEvent
  };
  //ETX

protected:
  vtkSplineSurfaceWidget();
  ~vtkSplineSurfaceWidget();

  //BTX - manage the state of the widget
  int State;
  enum WidgetState
  {
    Start=0,
    Moving,
    Scaling,
    Spinning,
    Outside
  };
  //ETX

  //handles the events
  static void ProcessEvents(vtkObject* object,
                            unsigned long event,
                            void* clientdata,
                            void* calldata);

  // ProcessEvents() dispatches to these methods.
  void OnLeftButtonDown();
  void OnLeftButtonUp();
  void OnMiddleButtonDown();
  void OnMiddleButtonUp();
  void OnRightButtonDown();
  void OnRightButtonUp();
  void OnMouseMove();
  void OnStartRender();

  vtkPlaneSource* PlaneSource;

  int NumberOfHandles;

  // The line segments
  vtkActor          *SurfaceActor;
  vtkPolyDataMapper *SurfaceMapper;
  vtkPolyData       *SurfaceData;
  void HighlightSurface(int highlight);

  // Glyphs representing hot spots (e.g., handles)
  vtkActor          **Handle;
  vtkPolyDataMapper  *HandleMapper;
  vtkCylinderSource  *HandleGeometry;
  int  HighlightHandle(vtkProp *prop); //returns handle index or -1 on fail
  virtual void Initialize();
  virtual void BuildRepresentation();

  // Do the picking
  vtkCellPicker *HandlePicker;
  vtkCellPicker *SurfacePicker;
  vtkActor *CurrentHandle;
  int CurrentHandleIndex;

  // Methods to manipulate the spline.
  void MovePoint(double *p1, double *p2);
  void Scale(double *p1, double *p2, int X, int Y);
  void Translate(double *p1, double *p2);
  void Spin(double *pp, double *vv);

  // Transform the control points (used for spinning)
  vtkTransform *Transform;

  // Properties used to control the appearance of selected objects and
  // the manipulator in general.
  vtkProperty *HandleProperty;
  vtkProperty *SelectedHandleProperty;
  vtkProperty *SurfaceProperty;
  vtkProperty *SelectedSurfaceProperty;
  void CreateDefaultProperties();

  // For efficient spinning
  double Centroid[3];
  void CalculateCentroid();
  double GrabbingPoint[3];

  // Flag indicating wheter the spline is being used in remote mode.   
  int RemoteMode;

private:
  vtkSplineSurfaceWidget(const vtkSplineSurfaceWidget&);  //Not implemented
  void operator=(const vtkSplineSurfaceWidget&);  //Not implemented
};

#endif
