import java.awt.*;
import java.awt.event.*;
import java.applet.*;

// This class demonstrates mouse events, redrawing, and the
// drawPoly method.

// It implemnts a simple "virtual reality" applet. The user
// can rotate the drawing around the X or Y axis by clicking
// areas of the image.

public class VR extends Applet implements MouseListener {

  // These arrays define the X and Y cooridinates of the drawing.

  private int[] oldX={160, 100, 60, 60, 40, 40, 60, 60, 100, 160};
  private int[] oldY={100, 90, 40, 90, 90, 110, 110, 160, 110, 100};

  // Those coordinates will be transformed based on the current
  // rotation, and stored in this array (which will be used for
  // the actual drawing).

  private int[] X={160, 100, 60, 60, 40, 40, 60, 60, 100, 160};
  private int[] Y={100, 90, 40, 90, 90, 110, 110, 160, 110, 100};
  private int num = 10;

  private int pitch = 0; // Current rotation around the Y axis
  private int yaw = 0;   // Current rotation around the X axis

  public void init() {
    addMouseListener(this);
    }

  // Since we have already represented the drawing as a pair of arrays
  // containing the X and Y coordinates of each point, we just pass them
  // to the drawPolygon method to do the drawing.

  public void paint(Graphics g) {
    g.drawPolygon(X, Y, num);
    }

  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}

  // When the mouse is clicked, we check whether it is    \ top /
  // in the top, bottom, left, or right area of the        \   /
  // applet. If it is in the top or bottom, we rotate   left\ / right
  // + or - 15 degrees around the X axis. If it is in       / \
  // the left or right, we rotate + or - 15 degrees        /   \
  // around the Y axis.                                   /bottom\

  public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();

    if (x < y && x < 200-y) { // left
      yaw = yaw + 15;
      }
    if (x > y && x > 200-y) { // right
      yaw = yaw - 15;
      }
    if (x > y && x < 200-y) { // top
      pitch = pitch + 15;
      }
    if (x < y && x > 200-y) { // bottom
      pitch = pitch - 15;
      }

    // Recompute the contents of the X and Y array from the contents of
    // the oldX and oldY arrays (which store the original point coordinates)
    // using a simple trig transform.

    for (int i = 0; i < num; i++) {
      X[i] = 100 + (int)((oldX[i] - 100) * Math.cos(yaw * Math.PI / 180));
      Y[i] = 100 + (int)((oldY[i] - 100) * Math.cos(pitch * Math.PI / 180));
      }

    // Repaint the drawing from those arrays.

    repaint();
    }

  }

