/*
  Copyright (c) 2004, Bradley L. Jones
  All rights reserved.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
  * Neither the name of the nondot.org nor the names of its contributors may 
    be used to endorse or promote products derived from this software without
    specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  POSSIBILITY OF SUCH DAMAGE.
*/
package org.nondot.applets;

import javax.swing.*;
import net.java.games.jogl.*;
import java.nio.*;
import java.awt.BorderLayout;
import java.lang.reflect.InvocationTargetException;
import org.nondot.particlesystem.*;

/**
 * An applet that draws a textured square to the screen
 */
public class ParticleSystemApplet
  extends JApplet
  implements GLEventListener, Runnable {
  final int imageHeight = 32;
  final int imageWidth = 32;

  ParticleSystem ps;

  //  current frame
  int frame;

  // delay in millisecs
  int delay;
  Thread animator;

  GLCanvas canvas;

  public void init() {
    GLCapabilities glc = new GLCapabilities();

    canvas = GLDrawableFactory.getFactory().createGLCanvas(glc);

    getContentPane().add(canvas, BorderLayout.CENTER);
    canvas.addGLEventListener(this);

    ps = new SimpleParticleSystem(1000);

    // shoot for 60 frames/sec
    delay = 1000 60;
  }

  public void display(GLDrawable gld) {
    // the drawing code
    GL gl = gld.getGL();
    GLU glu = gld.getGLU();
    gl.glClear(GL.GL_COLOR_BUFFER_BIT);

    // setup the camera
    gl.glMatrixMode(GL.GL_MODELVIEW);
    gl.glLoadIdentity();
    glu.gluLookAt(0.00.030.00.00.00.00.01.00.0);

    // send down the geometry
    gl.glPointSize(5.0f);
    ps.render(gl);

    gl.glFlush();
  }

  public void displayChanged(GLDrawable gld, boolean arg1, boolean arg2) {
  }

  public void start() {
    // start a new animation thread
    animator = new Thread(this);
    animator.start();
  }

  public void stop() {
    // stop an animation thread that is currently running around
    animator = null;
  }

  public void init(GLDrawable gld) {
    // make sure we don't do anything wrong with OpenGL
    gld.setGL(new DebugGL(gld.getGL()));
    GL gl = gld.getGL();
    // set the clear color, this only needs to be done once at the beginning
    // of the program after the GL context has been created
    gl.glClearColor(0.0f0.0f0.75f1.0f);

    // set up smooth shading
    gl.glShadeModel(GL.GL_SMOOTH);

    // create the checkerboard image
    Buffer image = createSpriteImage();
    gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);

    // generate the texture name
    int[] texName = new int[1];
    gl.glGenTextures(1, texName);

    gl.glBindTexture(GL.GL_TEXTURE_2D, texName[0]);

    // set some texture parameters
    gl.glTexParameteri(
      GL.GL_TEXTURE_2D,
      GL.GL_TEXTURE_WRAP_S,
      GL.GL_REPEAT);
    gl.glTexParameteri(
      GL.GL_TEXTURE_2D,
      GL.GL_TEXTURE_WRAP_T,
      GL.GL_REPEAT);
    gl.glTexParameteri(
      GL.GL_TEXTURE_2D,
      GL.GL_TEXTURE_MAG_FILTER,
      GL.GL_LINEAR);
    gl.glTexParameteri(
      GL.GL_TEXTURE_2D,
      GL.GL_TEXTURE_MIN_FILTER,
      GL.GL_LINEAR);

    // load the image into the graphics card
    gl.glTexImage2D(
      GL.GL_TEXTURE_2D,
      0,
      GL.GL_RGBA,
      imageWidth,
      imageHeight,
      0,
      GL.GL_RGBA,
      GL.GL_UNSIGNED_BYTE,
      image);
  }

  public void reshape(GLDrawable gld, int x, int y, int w, int h) {
    // setup the projection matrix
    GL gl = gld.getGL();
    GLU glu = gld.getGLU();
    gl.glMatrixMode(GL.GL_PROJECTION);
    gl.glLoadIdentity();
    glu.gluPerspective(90.0(doublew / h, .1100);

    gl.glMatrixMode(GL.GL_MODELVIEW);
  }

  private Buffer createSpriteImage() {
    ByteBuffer image =
      ByteBuffer.allocateDirect(imageWidth * imageHeight * 4);
    for (int y = 0; y < imageHeight; ++y) {
      float yr = ((floaty(imageHeight - 12.0f;
      for (int x = 0; x < imageWidth; ++x) {
        float xr = ((floatx(imageWidth - 12.0f;
        if (((yr * yr(xr * xr)) 4.0f) {
          image.put((byte0xFF);
          image.put((byte0xFF);
          image.put((byte0xFF);
          image.put((byte0xFF);
        else {
          image.put((byte0x00);
          image.put((byte0x00);
          image.put((byte0x00);
          image.put((byte0x00);
        }
      }
    }
    return image;
  }

  public void run() {

    final long start = System.currentTimeMillis();
    long tm = System.currentTimeMillis();

    while (Thread.currentThread() == animator) {
      try {

        // do stuff on the event dispatch thread
        SwingUtilities.invokeAndWait(new Runnable() {
          public void run() {
            // calculate the current frame based on the current time
            int lastFrame = frame;

            frame =
              (int) ((System.currentTimeMillis() - start)
                60.0
                1000.0);

            ps.update(delay / 1000.0f (frame - lastFrame));
            // tell the applet to redraw itself
            canvas.repaint();
          }
        });

        // put this thread a sleep for a period of time so we don't busy wait
        // although this can also interrupt our animation if we sleep too long
        tm += delay;
        Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
      }
      // cause this thread to die if there is some unexpected error, it will just
      // mean that the animation will stop working 
      catch (InterruptedException ie) {
        break;
      catch (InvocationTargetException ite) {
        break;
      }
    }
  }
}