/*****************************************************************
** DemoRotate - demonstrate rotating a graphic object
**
** 'Rotation' is one of the three basic affine transformations
** (the other two being 'scaling' and 'translating').  This program
** uses the standard transformation matrix for rotation to rotate
** the points in a polygon by 45 degrees (about the origin).
**
** Note: the y-axis coordinates in Java's graphics windows are
** 'negative' above the origin, 'positive' below the origin.
** Thus, the direction of rotation is clockwise, given the
** transformation shown here.
**
** (c) Scott MacKenzie, 2000
******************************************************************/
import java.awt.*;
import java.applet.*;

public class DemoRotate extends Applet
{
   private static final int SIZE = 200;    
   private static final double ROTATE = 45.0;  // degrees cw

   public void paint(Graphics g)
   {
      // points for the house polygon
      int[] houseX = {  30,  30,  50,  70,  70 };
      int[] houseY = { -40, -60, -70, -60, -40 };

      // compute rotation angle in radians
      double theta = Math.toRadians(ROTATE);

      // transformation matrix for rotation
      double[][] r = {
         { Math.cos(theta), -Math.sin(theta), 0.0 },
         { Math.sin(theta),  Math.cos(theta), 0.0 },
         {             0.0,              0.0, 1.0 },
      };

      // draw a rectangle around the graphics window
      g.drawRect(0, 0, SIZE - 1, SIZE - 1);

      // set a new origin in the middle of the graphics window
      g.translate(SIZE / 2, SIZE / 2);

      // draw the x axis and y axis (in light gray)
      g.setColor(Color.lightGray);
      g.drawLine(0, -(SIZE - 1), 0, +(SIZE - 1));
      g.drawLine(-(SIZE - 1), 0, +(SIZE - 1), 0);

      // draw outline of the original house (in black)
      g.setColor(Color.black);
      g.drawPolygon(houseX, houseY, houseX.length);

      // transform points (use 'rotate' matrix)
      double[] p = new double[3];
      for (int i = 0; i < houseX.length; i++)
      {
         p[0] = houseX[i];
         p[1] = houseY[i];
         p[2] = 1.0;
         p = vmProduct(p, r); 
         houseX[i] = (int)Math.round(p[0]);
         houseY[i] = (int)Math.round(p[1]);
      }

      // draw the transformed house
      g.drawPolygon(houseX, houseY, houseX.length);
   }

   // calculate product of vector 'v' and matrix 'm' (return a new vector)
   public static double[] vmProduct(double[] v, double[][] m)
   {
      double[] temp = new double[v.length];
      for (int i = 0; i < v.length; i++)
         temp[i] = v[0] * m[i][0] + v[1] * m[i][1] + v[2] * m[i][2];
      return temp;
   }
}

