/*
  Copyright (c) 2004, Bradley 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 org.nondot.mesh.*;

import java.awt.*;
import java.net.URL;
import java.lang.reflect.InvocationTargetException;

/**
 * An applet that draws a smooth shaded triangle to the screen
 */
public class ModelLoadingApplet
  extends JApplet
  implements Runnable, GLEventListener {

  Mesh mesh;
  GLCanvas canvas;

  //  current frame
  int frame;

  // delay in millisecs
  int delay;
  Thread animator;

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

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

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

    try {
      SMFModelLoader smfml =
        new SMFModelLoader(new SimpleTriMeshBuilder());
      URL url = new URL(getCodeBase()"dragon_slim.smf");
      mesh = smfml.load(url.openStream());
    catch (Exception e) {
      System.err.println("Error occured while loading mesh!");
    }

  }

  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.00.30.00.00.00.01.00.0);

    gl.glTranslatef(0.0f,-0.1f,0.0f);
    gl.glRotatef(3.0f (frame % 120),0.0f,1.0f,0.0f);
    mesh.render(gl);

    gl.glFinish();

  }

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

  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);
    
    // enable wireframe
    gl.glPolygonMode(GL.GL_FRONT_AND_BACK,GL.GL_LINE);
  }

  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);
  }

  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 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
            frame =
              (int) ((System.currentTimeMillis() - start)
                60.0
                1000.0);

            // 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;
      }
    }
  }
}