/*
 * PuppetApplet.java
 *
 * (C) 2004-2005, Alex S.
 */

import java.awt.*;
import java.util.*;

/*
class BodyNode {

    public Vector children;
    public pMatrix matrix;

    public BodyNode(){
        children = new Vector();
        matrix = new pMatrix();
    }
}
*/

public class PuppetApplet extends BufferedApplet {

    pMatrix matrix = new pMatrix();
    pMatrix pmatrix = new pMatrix();

    // points/colors that are rendered.
    Vector points = new Vector();
    Vector colors = new Vector();

    // for z sorting
    double[] avgz;
    int[] polyorder;

    // pre-computed points.	
    Vector cube = new Vector();

    // current rendering color
    Color currentColor = Color.red;

    // angle, mouse state
    private double m_anglex,m_angley;
    private int m_mousex,m_mousey;

    // used for java's fillpoly thingie... (and some quick & dirty clipping)
    private int[] x;
    private int[] y;
    private int[] z;

    // clippping ...
    private int[] cx;
    private int[] cy;
    private int[] cz;

    // screen rectangle
    int minx,maxx,miny,maxy;
   
    boolean[] keys;
    
    /**
     * dumps phere to rendering pipeline
     */
    public void dumpCube(){
        int i,j;
        j=cube.size();
        for (i=0;i<j;i++) {
            double[] point = (double[])cube.elementAt(i);
            addVertex(point[0],point[1],point[2]);
        }
    }

    /**
     * initialize things
     */
    public void init(){
        super.init();

        keys = new boolean[0x1000];
        for(int i=0;i<keys.length;i++)
            keys[i] = false;

        m_mousex = m_mousey = 0;
        // m_anglex = m_angley = 0;

        x = new int[128];
        y = new int[128];
        z = new int[128];
        cx = new int[128];
        cy = new int[128];
        cz = new int[128];
        
        pmatrix.translate(bounds().width/2,bounds().height/2,0);
        pmatrix.perspective(bounds().width/2,1);

        // initialize cube
        Vector v_points = new Vector();
        Vector v_faces = new Vector();

        v_points.addElement(new double[]{1,-1,1,1});
        v_points.addElement(new double[]{1,1,1,1});
        v_points.addElement(new double[]{-1,1,1,1});
        v_points.addElement(new double[]{-1,-1,1,1});

        v_points.addElement(new double[]{1,-1,-1,1});
        v_points.addElement(new double[]{1,1,-1,1});
        v_points.addElement(new double[]{-1,1,-1,1});
        v_points.addElement(new double[]{-1,-1,-1,1});

        v_faces.addElement(new int[]{0,1,2,3});
        v_faces.addElement(new int[]{4,7,6,5});
        v_faces.addElement(new int[]{0,4,5,1});
        v_faces.addElement(new int[]{7,3,2,6});
        v_faces.addElement(new int[]{1,5,6,2});
        v_faces.addElement(new int[]{0,3,7,4});

        for (int i=0;i<v_faces.size();i++) {
            int[] face = (int[])v_faces.elementAt(i);
            for (int j=0;j<4;j++) {
                cube.addElement(v_points.elementAt(face[j]));
            }
        }
        v_points.removeAllElements();
        v_faces.removeAllElements();
    }

    /**
     * similar to glVertex
     */
    private void addVertex(double x,double y,double z){
        points.addElement(matrix.mult(new double[]{x,y,z,1}));
        colors.addElement(currentColor);
    }

    public void dumpModel(){
        double a,b,c;

        // dump something interesting...
        /*
        matrix.push();
        matrix.scale(16);
        currentColor = null;
        dumpCube();
        matrix.pop();
        */

        double s = 4;

        a = -s * 4;
        for(int i=0;i<9;i++){
            b = -s * 4;
            for(int j=0;j<9;j++){
                c = -s * 4;
                for(int k=0;k<9;k++){
                    if((i ^ j ^ k) % 2 == 0){
                        currentColor = new Color((int)(0xFF*i/9.0),(int)(0xFF*j/9.0),(int)(0xFF*k/9.0));
                        matrix.push();
                        matrix.translate(a,b,c);
                        dumpCube();
                        matrix.pop();
                    } 
                    c += s;
                }
                b += s;
            }
            a += s;
        }
    }

    /**
     * sort via average z 
     */
    public void sort(){
        int i,j;
        int e1;
        double e2;
        for (i=1;i<polyorder.length;i++) {
            e1 = polyorder[i];
            e2 = avgz[i];

            for (j=i-1;j>=0 && avgz[j] > e2;j--) {
                avgz[j+1] = avgz[j];
                polyorder[j+1] = polyorder[j];
            }
            polyorder[j+1] = e1;
            avgz[j+1] = e2;
        }
    }

    pMatrix camera = new pMatrix();
    //double[] ploc = {0,0,144,1};

    double acceleration = 0;
    double friction = 0;
    double force = 0;
    double speed = 0;
    double frametime = 0;
    long lastframe = System.currentTimeMillis();

    public void handleMotion(){

        long currentframe = System.currentTimeMillis();
        frametime = (currentframe - lastframe) / 1000.0;
        lastframe = currentframe;


        if(m_anglex != 0.0 || m_angley != 0.0){
            pMatrix nm = new pMatrix();
            nm.rotatex(m_anglex);
            nm.rotatey(m_angley);
            nm.mult(camera);
            camera = nm;
            m_anglex = m_angley = 0.0;
            damage = true;
        }
       
        if(keys[127] || keys['q']){            // del key
            pMatrix nm = new pMatrix();
            nm.rotatez(Math.PI/100);
            nm.mult(camera);
            camera = nm;            
            damage = true;
        }
        if(keys[1025] || keys['e']){            // ins key
            pMatrix nm = new pMatrix();
            nm.rotatez(-Math.PI/100);
            nm.mult(camera);
            camera = nm;
            damage = true;
        }
        
        if(keys[1006] || keys['a']){            // left key
            pMatrix nm = new pMatrix();
            nm.rotatey(-Math.PI/100);
            nm.mult(camera);
            camera = nm;
            damage = true;
        }

        if(keys[1007] || keys['d']){            // right key
            pMatrix nm = new pMatrix();
            nm.rotatey(Math.PI/100);
            nm.mult(camera);
            camera = nm;
            damage = true;
        }

        if(keys[1004] || keys['w']){            // up key
            pMatrix nm = new pMatrix();
            nm.rotatex(Math.PI/100);
            nm.mult(camera);
            camera = nm;
            damage = true;
        }

        if(keys[1005] || keys['s']){            // down key
            pMatrix nm = new pMatrix();
            nm.rotatex(-Math.PI/100);
            nm.mult(camera);
            camera = nm;
            damage = true;
        }

        if(keys['<'] || keys[','] || keys['z']){
            //System.out.println("< is pressed");
            force = 100;
        }else if(keys['>'] || keys['.'] || keys['x']){
            force = -70;
        }else{
            force = 0;
        }
            
        friction = 0.1;
        acceleration = acceleration + friction * (0 - acceleration);
        acceleration = Math.min(1000,acceleration + force); // should be force * direction vector
        speed = speed + friction * (0 - speed);
        speed = Math.min(200,speed + acceleration * frametime);
        speed = Math.max(speed,-100);
        double distance = Math.round(speed * frametime);
        
        if(distance != 0){
            pMatrix nm = new pMatrix();
            nm.translate(0,0,distance);
            nm.mult(camera);

            /* // todo: collision detection
            pMatrix inverse = camera.inverse();
            double[] vec = {0,0,0,1};
            vec = inverse.mult(vec);
            */

            camera = nm;
            damage = true;
        }

    }


    /**
     * function that gets called whenever something needs to be
     * rendered.
     */
    public void render(Graphics g) {

        handleMotion();

        if (damage) {

            // screen rectangle
            minx = 0; // 10;
            maxx = bounds().width; // bounds().width-10;
            miny = 0; // 10;
            maxy = bounds().height; // bounds().height-10;

            g.setColor(Color.lightGray);
            g.fillRect(0, 0, bounds().width, bounds().height);

            matrix.push();

            matrix.mult(camera);
            //matrix.translate(-ploc[0],-ploc[1],-ploc[2]);

            matrix.scale(64);
            
            /*
            g.setColor(Color.black);
            g.drawString("sin: "+m_angley+"; cos: "+(m_anglex)+"; ang: "+ Math.atan2(m_anglex,m_angley),10,10);
            */

            /*
            if(m_angley != 0 || m_anglex != 0){ 
                pMatrix nm = new pMatrix();
                nm.rotatex(m_anglex);
                nm.rotatey(m_angley);
                nm.mult(camera);
                camera = nm;
                m_anglex = m_angley = 0;
            }
            */

            //matrix.mult(camera);

            dumpModel();

            // calculate average z for all points.
            avgz = new double[points.size() / 4];
            polyorder = new int[points.size() / 4];


            int k,i=0,j=points.size();
            double[] plane = new double[4];

            for (i=0;i<j;i+=4) {
                double sum = 0;
                for (k=0;k<4;k++) {
                    double[] point = (double[])points.elementAt(i+k);
                    sum += point[2];
                }
                avgz[i/4] = sum / 4;
                polyorder[i/4] = i/4;
            }
            sort(); // sort polyorder by avgz

            j = polyorder.length;
            for (i=0;i<j;i++) {
                int poly = polyorder[i] * 4;

                double[] p0 = (double[])points.elementAt(poly+0);
                double[] p1 = (double[])points.elementAt(poly+1);
                double[] p2 = (double[])points.elementAt(poly+2);
                double[] p3 = (double[])points.elementAt(poly+3);

                Color c = (Color)colors.elementAt(poly);

                if(c != null){

                    planeFromPoints(plane,p0,p1,p2,p3);
                    double d = plane[3];
                    boolean allnegative = true,allpositive = true;

                    if (d > 0) {
                        int clipz,n = 4;
                        for (k=0; k < n; k++) {

                            double[] point = (double[])points.elementAt(poly+k);
                            //point = pmatrix.mult(point);
                            x[k] = (int)(point[0]); // / point[3]);
                            y[k] = (int)(point[1]); // / point[3]);
                            z[k] = clipz = (int)(point[2]); // / point[3]);
                            
                            // clipping
                            // trivial cases, all points have positive or all negative z
                            if (clipz > 0)
                                allnegative = false;
                            else
                                allpositive = false;
                        }
                        // trivial rejection
                        if (allpositive)
                            continue;
                        if (!allnegative)
                            n = clipToZ(n);
                        if (n == 0)
                            continue;

                       /* 
                        allnegative = allpositive = true;
                        // test
                        for (k=0; k < n; k++) {
                            clipz = z[k];
                            
                            if (clipz > 0){                            
                                allnegative = false;
                            }else{
                                allpositive = false;
                            }
                        }                        
                        // trivial rejection
                        if (allpositive){
                            System.out.println("Aha, all positive!!!!");
                        }
                        if (!allnegative){
                            System.out.println("Aha... Not all negative!!!");
                        }
                        */


                        // project face coordinates
                        for(k=0;k<n;k++){
                            double[] point = {x[k],y[k],z[k],1}; 
                            point = pmatrix.mult(point);
                            if(point[3] < 0.001){
                                System.out.println("Point3 is almost 0!");                                
                            }
                            x[k] = (int)(point[0] / point[3]);
                            y[k] = (int)(point[1] / point[3]);
                        } 

                        n = clipToScreen(n);
                        if (n == 0)
                            continue;
                                                
                        // render                        
                        // g.fillPolygon(x,y,n);
                        
/*
                        for (k=0;k<4;k++) {
                            double[] point = (double[])points.elementAt(poly+k);
                            point = pmatrix.mult(point);
                            x[k] = (int)(point[0] / point[3]);
                            y[k] = (int)(point[1] / point[3]);
                        }
*/
                        //double color1 = Math.max(0,dotProduct(plane,new double[]{0,0,-1}));
/*
                        g.setColor(
                            new Color(
                                (float)Math.min( ((c.getRed()+50) * color1)/255.0, 1.0  ),
                                (float)Math.min( ((c.getGreen()+50) * color1)/255.0, 1.0 ),
                                (float)Math.min( ((c.getBlue()+50) * color1)/255.0, 1.0 )
                            )
                        );
*/
                        g.setColor(c);
                        g.fillPolygon(x,y,n);
                        g.setColor(Color.black);
                        g.drawPolygon(x,y,n);


                    }
                }else{
                   /* 
                    for (k=0;k<4;k++) {
                        double[] point = (double[])points.elementAt(poly+k);
                        point = pmatrix.mult(point);
                        x[k] = (int)(point[0] / point[3]);
                        y[k] = (int)(point[1] / point[3]);
                    }
                    g.setColor(Color.black);
                    g.drawPolygon(x,y,x.length);
                    */
                }

            }

            avgz = null;
            polyorder = null;
            matrix.pop();
            points.removeAllElements();
            colors.removeAllElements();
        }
    }


    /**
     * given 2 points, find their difference
     */
    void vectorSubtract (double[] va, double[] vb, double[] out){
        out[0] = va[0]-vb[0];
        out[1] = va[1]-vb[1];
        out[2] = va[2]-vb[2];
    }

    /**
     * cross product of two vectors
     */
    void crossProduct(double[] v1, double[] v2, double[] cross ) {
        cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
        cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
        cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
    }

    /**
     * normalize
     */
    double vectorNormalize(double[] in, double[] out ) {
        double  length, ilength;
        length = Math.sqrt(in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);
        if (length == 0) {
            return 0;
        }
        ilength = 1.0/length;
        out[0] = in[0]*ilength;
        out[1] = in[1]*ilength;
        out[2] = in[2]*ilength;
        return length;
    }   

    /**
     * dot product
     */
    double dotProduct (double[] v1, double[] v2){
        return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
    }

    /**
     * gets plane equation from three points on plane
     */
    boolean planeFromPoints(double[] plane, 
                            double[] a, double[] b,double[] c,double[] d ){

        double[] d1 = new double[4];
        double[] d2 = new double[4];
        vectorSubtract( b, a, d1 );
        if (dotProduct(d1,d1) < 0.02) {
            vectorSubtract( c, a, d1 );
            vectorSubtract( d, a, d2 );
        } else {
            vectorSubtract( c, a, d2 );
            if (dotProduct(d2,d2) < 0.02) {
                vectorSubtract( d, a, d2 );
            }
        }
        crossProduct( d2, d1, plane );
        if ( vectorNormalize( plane, plane ) == 0 ) {
            return false;
        }
        plane[3] = dotProduct( a, plane );
        return true;
    }


    /**
     * mouse event handler: let the user move things
     */
    public boolean mouseDown(Event evt, int x, int y){
        m_mousex = x;
        m_mousey = y;
        return true;
    }
    public boolean mouseUp(Event evt, int x, int y){
        return true;
    }

    /**
     * mouse event handler: let the user move things
     */
    public boolean mouseDrag(Event evt, int x, int y){
        m_angley += .015 * (double)(x - m_mousex);
        m_anglex += .015 * (double)(y - m_mousey);
        m_mousex = x;
        m_mousey = y;
        return true;
    }

    public boolean keyDown(Event evt,int key){
        //System.out.println("keyDown: "+key);
        if(key < 0x1000)
            keys[key] = true;
        return true;
    }

    public boolean keyUp(Event evt,int key){
        //System.out.println("keyUp: "+key);
        if(key < 0x1000)
            keys[key] = false;
        return true;
    }

    /**
     * crude clipping... x,y points to screen.
     * (very inefficient)
     */
    private int clipToScreen(int n){

        float d;
        int i,next,prev,dist,c;
        int[] tmp;
        int abs;

        // minx clip
        c = 0;
        for (i=0;i<n;i++) {
            if (x[i] >= minx) { // point is on right side
                cx[c] = x[i];
                cy[c++] = y[i];
                continue;
            }
            next = (i+1) % n;
            prev = (i+n-1) % n;
            dist = x[i] - minx;
            if (dist < 0)
                dist = -dist;
            if (x[prev] >= minx) {
                abs = x[prev]-minx;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = minx;
                cy[c++] = y[i]+(int)(d*(y[prev]-y[i]));
            }
            if (x[next] >= minx) {
                abs = x[next]-minx;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = minx;
                cy[c++] = y[i]+(int)(d*(y[next]-y[i]));
            }
        }
        if (c == 0)
            return c;
        n = c;

        tmp = x;
        x = cx;
        cx = tmp;
        tmp = y;
        y = cy;
        cy = tmp;

        // miny clip
        c = 0;
        for (i=0;i<n;i++) {
            if (y[i] >= miny) { // point is on right side
                cx[c] = x[i];
                cy[c++] = y[i];
                continue;
            }
            next = (i+1) % n;
            prev = (i+n-1) % n;
            dist = y[i] - miny;
            if (dist < 0)
                dist = -dist;
            if (y[prev] >= miny) {
                abs = y[prev]-miny;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = x[i]+(int)(d*(x[prev]-x[i]));
                cy[c++] = miny;
            }
            if (y[next] >= miny) {
                abs = y[next]-miny;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = x[i]+(int)(d*(x[next]-x[i]));
                cy[c++] = miny;
            }
        }
        if (c == 0)
            return c;
        n = c;

        tmp = x;
        x = cx;
        cx = tmp;
        tmp = y;
        y = cy;
        cy = tmp;

        // maxx clip
        c = 0;
        for (i=0;i<n;i++) {
            if (x[i] < maxx) { // point is on right side
                cx[c] = x[i];
                cy[c++] = y[i];
                continue;
            }
            next = (i+1) % n;
            prev = (i+n-1) % n;
            dist = x[i] - maxx;
            if (dist < 0)
                dist = -dist;
            if (x[prev] < maxx) {
                abs = x[prev]-maxx;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = maxx;
                cy[c++] = y[i]+(int)(d*(y[prev]-y[i]));
            }
            if (x[next] < maxx) {
                abs = x[next]-maxx;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = maxx;
                cy[c++] = y[i]+(int)(d*(y[next]-y[i]));
            }
        }
        if (c == 0)
            return c;
        n = c;

        tmp = x;
        x = cx;
        cx = tmp;
        tmp = y;
        y = cy;
        cy = tmp;

        // maxy clip
        c = 0;
        for (i=0;i<n;i++) {
            if (y[i] < maxy) { // point is on right side
                cx[c] = x[i];
                cy[c++] = y[i];
                continue;
            }
            next = (i+1) % n;
            prev = (i+n-1) % n;
            dist = y[i] - maxy;
            if (dist < 0)
                dist = -dist;
            if (y[prev] < maxy) {
                abs = y[prev]-maxy;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = x[i]+(int)(d*(x[prev]-x[i]));
                cy[c++] = maxy;
            }
            if (y[next] < maxy) {
                abs = y[next]-maxy;
                if (abs < 0)
                    abs = -abs;
                d = (float)dist / (float)(dist + abs);
                cx[c] = x[i]+(int)(d*(x[next]-x[i]));
                cy[c++] = maxy;
            }
        }
        if (c == 0)
            return c;

        tmp = x;
        x = cx;
        cx = tmp;
        tmp = y;
        y = cy;
        cy = tmp;

        return c;
    }


    /**
     * very very crude clipping...
     * clips the x,y,z points to the z-axis (only negative z stays)
     */
    private int clipToZ(int n){
        // clip to Z
        float d;
        int i,next,prev, c = 0;  // good point count
        for (i=0;i<n;i++) {
            if (z[i] <= 0) {  // point is on right side
                cx[c] = x[i];
                cy[c] = y[i];
                cz[c] = z[i];
                c++;
                continue;
            }
            next = (i+1) % n;
            prev = (i+n-1) % n;
            if (z[prev] <= 0) {
                // this is first point outside, create a split point
                d = (float)(z[i]) / (float)(z[i] - z[prev]);  // d is positive.
                cx[c] = x[i]+(int)(d*(x[prev]-x[i]));
                cy[c] = y[i]+(int)(d*(y[prev]-y[i]));
                cz[c] = 0;
                c++;
            }
            if (z[next] <= 0) {
                // next point is ok, we'll handle it now
                // z[i] is positive, z[next] is negative (or 0).
                d = (float)(z[i]) / (float)(z[i] - z[next]);  // d is positive.
                cx[c] = x[i]+(int)(d*(x[next]-x[i]));
                cy[c] = y[i]+(int)(d*(y[next]-y[i]));
                cz[c] = 0;
                c++;
            }
        }
        int[] tmp;
        tmp = x;
        x = cx;
        cx = tmp;
        tmp = y;
        y = cy;
        cy = tmp;
        tmp = z;
        z = cz;
        cz = tmp;
        return c;
    }

}


