// adapted from animation example by Mike Hall www.brainjar.com

import java.awt.*;
import java.applet.*;

public class animation extends Applet implements Runnable {

  static final int    frame_rate    = 10; 
  static final double rev_per_sec1  = -0.5;  
  static final double rev_per_sec2  =  0.82342342212;  
  static final double two_pi        = 2*Math.PI; 
  Thread              anim_thread;  
  Polygon             s1,s2;
  double              angle1 = 0.0,angle2=0.0;
  int                 w1 = 80, w2=30;
  double              delta1 = rev_per_sec1*two_pi*frame_rate/1000;
  double              delta2 = rev_per_sec2*two_pi*frame_rate/1000;
  Dimension           off_dim;
  Image               off_img;
  Graphics            gr;

  public void init() {
    s1=new Polygon(); s1.addPoint(w1,w1); s1.addPoint(-w1,w1); s1.addPoint(-w1,-w1); s1.addPoint(w1,-w1);
    s2=new Polygon(); s2.addPoint(w2,w2); s2.addPoint(-w2,w2); s2.addPoint(-w2,-w2); s2.addPoint(w2,-w2);
  } 

  public void start() {if (anim_thread == null) {anim_thread = new Thread(this); anim_thread.start(); }}
  public void stop()  {if (anim_thread != null) {anim_thread.stop(); anim_thread = null; } }
  public void update(Graphics g) { paint(g); }

  public void run() {
    while (Thread.currentThread() == anim_thread) {
      angle1 += delta1; angle2 += delta2;
      if (angle1<0) angle1 += two_pi; if (angle1>two_pi) angle1 -= two_pi;
      if (angle2<0) angle2 += two_pi; if (angle2>two_pi) angle2 -= two_pi;
      repaint();
      try { Thread.currentThread().sleep(frame_rate); }
      catch (InterruptedException e) {}
    }
  }

  public Polygon rotate(Polygon poly, double theta) {
    Polygon newPoly;
    int i;
    double x,y;
    double cos_t=Math.cos(theta);
    double sin_t=Math.sin(theta);  
    newPoly = new Polygon();
    for (i=0; i<poly.npoints; i++) {
      x =  poly.xpoints[i]*cos_t  + poly.ypoints[i]*sin_t;
      y = -poly.xpoints[i]*sin_t  + poly.ypoints[i]*cos_t;
      newPoly.addPoint((int) x,(int) y);
    }
    return newPoly;
  }

  public void paint(Graphics g) {
    Dimension d = getSize();
    Polygon poly1,poly2;
    if (gr == null || d.width != off_dim.width || d.height != off_dim.height) {
      off_dim = d;
      off_img = createImage(d.width, d.height);
      gr = off_img.getGraphics();
    }
    gr.setColor(Color.black);
    gr.fillRect(0,0,d.width,d.height);
    poly1 = rotate(s1, angle1);
    poly2 = rotate(s2, angle2);
    gr.translate(d.width/2,d.height/2);
    gr.setColor(Color.yellow);
    gr.fillPolygon(poly1);
    gr.setColor(Color.blue);
    gr.fillPolygon(poly2);
    gr.setColor(Color.red);
    gr.drawPolygon(poly1);
    gr.setColor(Color.green);
    gr.drawPolygon(poly2);
    gr.translate(-d.width/2,-d.height/2);
    g.drawImage(off_img,0,0,this);
  }
}
