import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;

public class TstMtx_Bern extends Applet {

//  Matrix3D class test application
//  Based on example TestMatrix.class code.
//
//  Modifications by Herman Bernard Walker
//  Last revision 11-8-1998

//  This applet is designed to implement the
//  view of the selected dataset in a subwindow,
//  using various Java controls to implement
//  testing of the various transforms of the Matrix3D
//  class.  Due to my inexperience in Java preventing
//  a successful graphics window implementation, the
//  only portion of the graphics transform testing
//  coded beyond the provided rotation test are
//  placeholders for an orthogonal/perspective rendering
//  toggle.

//  The graphics viewport implementation was planned to be
//  done using the DISPlay PANel (Disppan) class, derived
//  from the Canvas class.

    final static int CHUNKSIZE = 100;
    Raster raster;
    Image screen;
    Graphics disp;
    Point3D vertList[];
    Point3D worldList[];
    Point3D tranList[];
    int vertices;
    Matrix3D view;
    Matrix3D model;
    

    float eyex, eyey, eyez;
    float lookatx, lookaty, lookatz;
    float upx, upy, upz;
    float fov;

    public void init( )
    {
//Applet view init:
        setLayout(new FlowLayout());
        
//        raster = new Raster(size().width, size().height);
        raster = new Raster(300,300);
        raster.fill(getBackground());
        screen = raster.toImage();

        eyex = 0;        eyey = 0;        eyez = -10;
        lookatx = 0;     lookaty = 0;     lookatz = 0;
        upx = 0;         upy = 1;         upz = 0;
        fov = 30;

        vertList = new Point3D[CHUNKSIZE];
        vertices = 0;

        String filename = getParameter("datafile");
        showStatus("Reading "+filename);
        InputStream is = null;
        try {
            is = new URL(getDocumentBase(), filename).openStream();
            ReadInput(is);
            is.close();
        } catch (IOException e) {
            showStatus("Error reading "+filename);
        }

        worldList = new Point3D[vertList.length];
        tranList = new Point3D[vertList.length];
        for (int i = 0; i < vertices; i++) {
            worldList[i] = new Point3D();
            tranList[i] = new Point3D();
        }

        view = new Matrix3D(raster);
        float t = (float) Math.sin(Math.PI*(fov/2)/180);
        float s = (t*300)/300;

        view.perspective(-t, t, -s, s, -1, -200);
        view.lookAt(eyex, eyey, eyez, lookatx, lookaty, lookatz, upx, upy, upz);

        model = new Matrix3D();
        long time = System.currentTimeMillis();
        model.transform(vertList, worldList, 0, vertices);
        view.transform(worldList, tranList, 0, vertices);
        DrawObject();
        time = System.currentTimeMillis() - time;
        showStatus("Time = "+time+" ms");
        screen = raster.toImage();
    		//{{INIT_CONTROLS
		setLayout(null);
		setSize(300,450);
		Group1 = new CheckboxGroup();
		radioButton1 = new java.awt.Checkbox("Orthographic", Group1, false);
		radioButton1.setBounds(0,310,96,24);
		add(radioButton1);
		radioButton2 = new java.awt.Checkbox("Perspective", Group1, true);
		radioButton2.setBounds(204,310,96,24);
		add(radioButton2);
		Disppan canvas1 = new Disppan();
		canvas1.setBounds(0,0,300,300);
		disp = canvas1.getGraphics();
		add(canvas1);
		//}}
}

    private double getNumber(StreamTokenizer st) throws IOException
    {
        if (st.nextToken() != StreamTokenizer.TT_NUMBER) {
            System.err.println("ERROR: line "+st.lineno()+": expected number");
            throw new IOException(st.toString());
        }
        return st.nval;
    }

    public void ReadInput(InputStream is) throws IOException
    {
	    StreamTokenizer st = new StreamTokenizer(is);
    	st.commentChar('#');
        scan: while (true) {
	        switch (st.nextToken()) {
	          default:
		        break scan;
	          case StreamTokenizer.TT_WORD:
		        if (st.sval.equals("v")) {
		            float x = (float) getNumber(st);
		            float y = (float) getNumber(st);
		            float z = (float) getNumber(st);
		            if (vertices == vertList.length) {
		                Point3D newList[] = new Point3D[vertList.length+CHUNKSIZE];
                        System.arraycopy(vertList, 0, newList, 0, vertList.length);
		                vertList = newList;
		            }
		            vertList[vertices++] = new Point3D(x, y, z);
		        } else
			    if (st.sval.equals("eye")) {
                    eyex = (float) getNumber(st);
                    eyey = (float) getNumber(st);
		            eyez = (float) getNumber(st);
			    } else
			    if (st.sval.equals("look")) {
                    lookatx = (float) getNumber(st);
                    lookaty = (float) getNumber(st);
		            lookatz = (float) getNumber(st);
			    } else
			    if (st.sval.equals("up")) {
                    upx = (float) getNumber(st);
                    upy = (float) getNumber(st);
		            upz = (float) getNumber(st);
			    } else
			    if (st.sval.equals("fov")) {
                    fov = (float) getNumber(st);
			    } else {
                    System.err.println("ERROR: line "+st.lineno()+": unexpected token :"+st.sval);
                    break scan;
			    }
			    break;
	        }
	        if (vertices % 100 == 0) showStatus("vertices = " + vertices);
	    }
        is.close();
	    if (st.ttype != StreamTokenizer.TT_EOF) {
	        throw new IOException(st.toString());
	    }
	}

    public void paint(Graphics g)
    {
//          g.drawImage(screen, 0, 0, this);
        canvas1.paint(disp,screen);
    }

    public void update(Graphics g)
    {
        paint(g);
    }

    float v0x, v0y, v0z;

    public boolean mouseDown(Event e, int x, int y)
    {
        if (e.metaDown()) {
            showStatus("Resetting model matrix");
            model.loadIdentity();
        }
        v0x = (float) (x - (size().width / 2));
        v0y = (float) ((size().height / 2) - y);
        v0z = (float) size().width;
        float l0 = (float) (1 / Math.sqrt(v0x*v0x + v0y*v0y + v0z*v0z));
        v0x *= l0;
        v0y *= l0;
        v0z *= l0;
	    return true;
    }

    public boolean mouseDrag(Event e, int x, int y)
    {
        if (e.metaDown()) {
            showStatus("Resetting model matrix");
        } else {
            float v1x = (float) (x - (size().width / 2));
            float v1y = (float) ((size().height / 2) - y);
            float v1z = (float) size().width;
            float l = (float) (1 / Math.sqrt(v1x*v1x + v1y*v1y + v1z*v1z));
            v1x *= l;
            v1y *= l;
            v1z *= l;

            float ax = v0y*v1z - v0z*v1y;
            float ay = v0z*v1x - v0x*v1z;
            float az = v0x*v1y - v0y*v1x;
            l = (float) Math.sqrt(ax*ax + ay*ay + az*az);
            float theta = (float) Math.asin(l);
            if (v0x*v1x + v0y*v1y + v0z*v1z < 0)
                theta += (float) Math.PI / 2;
            model.rotate(ax, ay, az, theta);
            v0x = v1x;
            v0y = v1y;
            v0z = v1z;
            model.transform(vertList, worldList, 0, vertices);
            view.transform(worldList, tranList, 0, vertices);
            DrawObject();
        }
        screen = raster.toImage();
        repaint();
        return true;
    }

 
    void DrawObject()
    {
        int ix, iy;
        int w, h;
        w = raster.width;
        h = raster.height;
        raster.fill(getBackground());
        for (int i = 0; i < vertices; i++) {
            ix = (int) tranList[i].x;
            iy = (int) tranList[i].y;
            if (ix >= 0 && iy >= 0 && ix < w && iy < h)
                raster.setPixel(0xffa000a0, ix, iy);
        }
    }

	//{{DECLARE_CONTROLS
	java.awt.Checkbox radioButton1;
	CheckboxGroup Group1;
	java.awt.Checkbox radioButton2;
	Disppan canvas1;
	//}}
}
