/* Copyright (C) 1999-2004 by Peter Eastman

   This program is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but WITHOUT ANY 
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */

package artofillusion;

import artofillusion.math.*;
import artofillusion.object.*;
import artofillusion.ui.*;
import artofillusion.object.Mesh.*;
import buoy.event.*;
import java.awt.*;
import java.util.Vector;

/** SkewMeshTool is an EditingTool used for skewing the vertices of TriangleMesh objects. */

public class SkewMeshTool extends EditingTool
{
  private boolean noSelection, notOnHandle, skewX, skewY, skewAll;
  private Point clickPoint;
  private double clickX, clickY, centerX, centerY;
  private Vec3 skewCenter, baseVertPos[];
  private BoundingBox bounds;
  private UndoRecord undo;
  
  private static Image icon, selectedIcon;
  public static final int HANDLE_SIZE = 5;

  public SkewMeshTool(EditingWindow fr)
  {
    super(fr);
    icon = loadImage("skewPoints.gif");
    selectedIcon = loadImage("selected/skewPoints.gif");
  }

  public void activate()
  {
    super.activate();
    
    MeshViewer view = (MeshViewer) theWindow.getView();
    int selected[] = view.getSelectionDistance();
    noSelection = false;
    for (int i = 0; i < selected.length; i++)
      if (selected[i] == 0)
	{
	  theWindow.setHelpText(Translate.text("skewMeshTool.helpText"));
	  return;
	}
    theWindow.setHelpText(Translate.text("skewMeshTool.errorText"));
    noSelection = true;
  }

  public int whichClicks()
  {
    return ALL_CLICKS;
  }

  public Image getIcon()
  {
    return icon;
  }

  public Image getSelectedIcon()
  {
    return selectedIcon;
  }

  public String getToolTipText()
  {
    return Translate.text("skewMeshTool.tipText");
  }

  public void drawOverlay(Graphics g, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) ((MeshViewer) view).getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Rectangle b;

    if (noSelection)
      return;
    g.setColor(Color.red);
    b = findScreenBounds(findSelectionBounds(v, cam, (MeshViewer) view), cam, (MeshViewer) view);
    if (b != null)
      {
	g.fillRect(b.x, b.y, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x+(b.width-HANDLE_SIZE)/2, b.y, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x, b.y+(b.height-HANDLE_SIZE)/2, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x+(b.width-HANDLE_SIZE)/2, b.y+b.height-HANDLE_SIZE+1, HANDLE_SIZE, HANDLE_SIZE);
	g.fillRect(b.x+b.width-HANDLE_SIZE+1, b.y+(b.height-HANDLE_SIZE)/2, HANDLE_SIZE, HANDLE_SIZE);
      }
  }
  
  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) ((MeshViewer) view).getObject().object;
    MeshVertex v[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Rectangle b;
    int j, k;
    
    if (noSelection)
      return;
    clickPoint = e.getPoint();
    
    // Determine which handle was clicked on.
    
    bounds = findSelectionBounds(v, cam, (MeshViewer) view);
    b = findScreenBounds(bounds, cam, (MeshViewer) view);
    if (!b.contains(clickPoint))
      {
	notOnHandle = true;
	return;
      }
    if (clickPoint.x <= b.x+HANDLE_SIZE)
      j = 0;
    else if (clickPoint.x >= b.x+(b.width-HANDLE_SIZE)/2 && clickPoint.x <= b.x+(b.width-HANDLE_SIZE)/2+HANDLE_SIZE)
      j = 1;
    else if (clickPoint.x >= b.x+b.width-HANDLE_SIZE)
      j = 2;
    else j = -1;
    if (clickPoint.y <= b.y+HANDLE_SIZE)
      k = 0;
    else if (clickPoint.y >= b.y+(b.height-HANDLE_SIZE)/2 && clickPoint.y <= b.y+(b.height-HANDLE_SIZE)/2+HANDLE_SIZE)
      k = 1;
    else if (clickPoint.y >= b.y+b.height-HANDLE_SIZE)
       k = 2;
    else k = -1;
    if (j == -1 || k == -1 || (j == 1 && k == 1))
      {
	notOnHandle = true;
	return;
      }
    notOnHandle = false;
    clickX = (double) clickPoint.x;
    clickY = (double) clickPoint.y;
    skewCenter = new Vec3(0.0, 0.0, (bounds.minz+bounds.maxz)/2.0);
    if (j == 0)
      {
        skewY = true;
	centerX = (double) (b.x + b.width);
	skewCenter.x = bounds.minx;
      }
    else if (j == 2)
      {
        skewY = true;
	centerX = (double) b.x;
	skewCenter.x = bounds.maxx;
      }
    else
      {
	skewY = false;
	skewCenter.x = (bounds.minx+bounds.maxx);
      }
    if (k == 0)
      {
        skewX = true;
	centerY = (double) (b.y + b.height);
	skewCenter.y = bounds.miny;
      }
    else if (k == 2)
      {
        skewX = true;
	centerY = (double) b.y;
	skewCenter.y = bounds.maxy;
      }
    else
      {
	skewX = false;
	skewCenter.y = (bounds.miny+bounds.maxy);
      }
    if (e.isControlDown())
      {
	centerX = (double) (b.x + (b.width/2));
	centerY = (double) (b.y + (b.height/2));
	skewCenter.x = (bounds.minx+bounds.maxx)/2.0;
	skewCenter.y = (bounds.miny+bounds.maxy)/2.0;
      }
    skewAll = skewX && skewY && e.isShiftDown();
    baseVertPos = mesh.getVertexPositions();
  }
  
  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) ((MeshViewer) view).getObject().object;
    MeshVertex vert[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Point dragPoint = e.getPoint();
    Vec3 v[];
    Vec2 p;
    int i, vertSize = MeshViewer.HANDLE_SIZE;
    int selectDist[] = ((MeshViewer) view).getSelectionDistance();
    double max, xskew, yskew;
    
    if (noSelection || notOnHandle)
      return;
    if (undo == null)
      undo = new UndoRecord(theWindow, false, UndoRecord.COPY_VERTEX_POSITIONS, new Object [] {mesh, mesh.getVertexPositions()});
    xskew = yskew = 0.0;
    if (skewX)
      xskew = (dragPoint.x-clickX)/(dragPoint.y-centerY);
    if (skewY)
      yskew = (dragPoint.y-clickY)/(dragPoint.x-centerX);
    if (skewAll)
      {
	max = Math.max(Math.abs(xskew), Math.abs(yskew));
	if (xskew != 0.0)
	  xskew *= max/Math.abs(xskew);
	if (yskew != 0.0)
	  yskew *= max/Math.abs(yskew);
      }
    v = findSkewedPositions(baseVertPos, xskew, yskew, (MeshViewer) view);
    mesh.setVertexPositions(v);
    ((ObjectViewer) view).objectChanged();
    theWindow.updateImage();
  }

  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)
  {
    Mesh mesh = (Mesh) ((MeshViewer) view).getObject().object;
    MeshVertex vert[] = mesh.getVertices();
    Camera cam = view.getCamera();
    Point dragPoint = e.getPoint();
    Vec3 v[];
    double max, xskew, yskew;

    if (noSelection || notOnHandle)
      return;
    xskew = yskew = 0.0;
    if (skewX)
      xskew = (dragPoint.x-clickX)/(dragPoint.y-centerY);
    if (skewY)
      yskew = (dragPoint.y-clickY)/(dragPoint.x-centerX);
    if (skewAll)
      {
	max = Math.max(Math.abs(xskew), Math.abs(yskew));
	if (xskew != 0.0)
	  xskew *= max/Math.abs(xskew);
	if (yskew != 0.0)
	  yskew *= max/Math.abs(yskew);
      }
    if (undo != null)
      theWindow.setUndoRecord(undo);
    v = findSkewedPositions(baseVertPos, xskew, yskew, (MeshViewer) view);
    mesh.setVertexPositions(v);
    undo = null;
    baseVertPos = null;
    mesh.informChanged(this, ModelEvent.CHANGEDUR_OBJECTEDITOR);
  }

  /* This method returns a bounding box for the selected vertices in view coordinates. */
  
  BoundingBox findSelectionBounds(MeshVertex vert[], Camera cam, MeshViewer view)
  {
    int selected[] = view.getSelectionDistance();
    double minx, miny, minz, maxx, maxy, maxz;
    Vec3 v;
    int i;
    
    minx = miny = minz = Double.MAX_VALUE;
    maxx = maxy = maxz = -Double.MAX_VALUE;
    for (i = 0; i < vert.length; i++)
      {
	if (selected[i] == 0)
	  {
	    v = cam.getObjectToView().times(vert[i].r);
	    if (v.x < minx) minx = v.x;
	    if (v.x > maxx) maxx = v.x;
	    if (v.y < miny) miny = v.y;
	    if (v.y > maxy) maxy = v.y;
	    if (v.z < minz) minz = v.z;
	    if (v.z > maxz) maxz = v.z;
	  }
      }
    return new BoundingBox(minx, maxx, miny, maxy, minz, maxz);
  }
  
  /* Given a bounding box in view coordinates, find the corresponding rectangle in
     screen coordinates. */
  
  Rectangle findScreenBounds(BoundingBox b, Camera cam, MeshViewer view)
  {
    CoordinateSystem coords = view.getObject().coords;
    Mat4 m = cam.getObjectToWorld();
    Rectangle r;
    
    cam.setObjectTransform(cam.getViewToWorld());
    r = cam.findScreenBounds(b);
    cam.setObjectTransform(m);
    if (r != null)
      r.setBounds(r.x-10, r.y-10, r.width+20, r.height+20);
    return r;
  }

  /* Find the new positions of the vertices after scaling. */

  Vec3 [] findSkewedPositions(Vec3 vert[], double xskew, double yskew, MeshViewer view)
  {
    Vec3 v[] = new Vec3 [vert.length];
    int selected[] = view.getSelectionDistance();
    Camera cam = view.getCamera();
    Mat4 m, s;
    int i;
    
    // Find the transformation matrix.
    
    m = cam.getObjectToView();
    m = Mat4.translation(-skewCenter.x, -skewCenter.y, -skewCenter.z).times(m);
    s = new Mat4(1.0, xskew, 0.0, 0.0,
		yskew, 1.0, 0.0, 0.0,
		0.0, 0.0, 1.0, 0.0,
		0.0, 0.0, 0.0, 1.0);
    m = s.times(m);
    m = Mat4.translation(skewCenter.x, skewCenter.y, skewCenter.z).times(m);
    m = cam.getViewToWorld().times(m);
    m = view.getDisplayCoordinates().toLocal().times(m);
    
    // Determine the deltas.
    
    for (i = 0; i < vert.length; i++)
      {
	if (selected[i] == 0)
	  v[i] = m.times(vert[i]).minus(vert[i]);
	else
	  v[i] = new Vec3();
      }
    if (theFrame instanceof MeshEditorWindow)
      ((MeshEditorWindow) theFrame).adjustDeltas(v);
    for (i = 0; i < vert.length; i++)
      v[i].add(vert[i]);
    return v;
  }
}