/*
 *      @(#)ObjLoad.java 1.10 00/02/10 13:14:23
 *
 * Copyright (c) 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import com.sun.j3d.loaders.objectfile.ObjectFile;
import com.sun.j3d.loaders.ParsingErrorException;
import com.sun.j3d.loaders.IncorrectFormatException;
import com.sun.j3d.loaders.Scene;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import java.io.*;
import com.sun.j3d.utils.behaviors.mouse.*;

import javax.swing.*;

// for the picking behaviours: john snavely
import com.sun.j3d.utils.picking.behaviors.*;
import com.sun.j3d.utils.picking.*;


import com.sun.j3d.loaders.vrml97.impl.TreePrinter;
import java.util.Hashtable;


public class ObjLoad extends JPanel implements ActionListener{

   
    private String filename = null;
    TreePrinter         tp = new TreePrinter();
    Canvas3D canvas;
    BoundingSphere bounds;
    BoundingSphere  sceneBounds;
    String Location;
    JTextField textField;
    Scene s = null;
    BranchGroup sceneGroup = new BranchGroup();
    BranchGroup objRoot;
    SimpleUniverse u;
    TransformGroup      vpTransGroup;
    TransformGroup objTrans;
    

    public void createSceneGraph(String args) {
            
        if (sceneGroup != null) {
            sceneGroup.detach();
            sceneGroup = new BranchGroup();
            sceneGroup.setCapability(BranchGroup.ALLOW_DETACH);
            sceneGroup.setCapability(BranchGroup.ALLOW_BOUNDS_READ);
            sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
            sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
            sceneGroup.setCapability(BranchGroup.ENABLE_PICK_REPORTING);
            sceneGroup.setCapability(BranchGroup.ALLOW_AUTO_COMPUTE_BOUNDS_READ);
            sceneGroup.setCapability(BranchGroup.ALLOW_AUTO_COMPUTE_BOUNDS_WRITE);
        }
        
        
        

        
        //int j = ObjectFile.RESIZE;
        ObjectFile f = new ObjectFile();
        
        
        
      
        
        //this was in the objectfile constructor
         /* (float)(60 * Math.PI / 180.0)*/
        
        File rootDir = new File(Location);
        //if the user does not give us a directory don't even load
        // maybe later a user message telling them to enter a dir
        if (!rootDir.isDirectory()){
            return;}
            
        String files[]= rootDir.list(); 
        for (int i=0; i < files.length; i++) { 
            if (files[i].endsWith(".obj")) { 
                
        
           // This is a wavefront file 
                try {
                     s = f.load(rootDir.getPath() + rootDir.separator + files[i]);
                   
                   
                }
                catch (FileNotFoundException e) {
                System.err.println(e);
                System.exit(1);
                }
                catch (ParsingErrorException e) {
                System.err.println(e);
                System.exit(1);
                }
                catch (IncorrectFormatException e) {
                System.err.println(e);
                System.exit(1);
            }
            
            Shape3D shape;
            Hashtable namesofShapes = s.getNamedObjects();
            //System.out.println( namesofShapes.toString());
        
            
            shape = (Shape3D)(s.getSceneGroup()).getChild(0);
            (s.getSceneGroup()).removeChild(0);
            shape.setCapability(Geometry.ALLOW_INTERSECT);
            shape.setCapability(Shape3D.ENABLE_PICK_REPORTING);
            shape.setCapability(Shape3D.ALLOW_GEOMETRY_READ);
            PickTool.setCapabilities(shape, PickTool.INTERSECT_FULL);
                    
            TransformGroup spinTg2 = new TransformGroup();
            spinTg2.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
            spinTg2.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
            spinTg2.setCapability(TransformGroup.ENABLE_PICK_REPORTING);
            
            spinTg2.addChild(shape);
            sceneGroup.addChild(spinTg2);
        
          
           
        }
    }
    
        
            
        objTrans.addChild(sceneGroup);
      //  sceneGroup.setBoundsAutoCompute(true);
        sceneBounds = (BoundingSphere)sceneGroup.getBounds();
        setViewpoint();
        
    }

   
    public ObjLoad(String InitLoc) {
        
        Location = InitLoc;
        setLayout(new BorderLayout());
        GraphicsConfiguration config =
           SimpleUniverse.getPreferredConfiguration();

        canvas = new Canvas3D(config);
        add("Center", canvas);

          //add the text panel from which we will read the directory
        // to find the obj files
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT));
        textField = new JTextField(Location,60);      
        textField.addActionListener(this);
        textField.setActionCommand("GetUserDir");
        JLabel label = new JLabel("Location:");
        panel.add(label);
        panel.add(textField);
        add("North",panel);
        
        
        
        
        
        u = new SimpleUniverse(canvas);
        ViewingPlatform viewingPlatform = u.getViewingPlatform();
        vpTransGroup = viewingPlatform.getViewPlatformTransform();
        // This will move the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
       // u.getViewingPlatform().setNominalViewingTransform();
        
        setupBehavior();
        
        // Create a simple scene and attach it to the virtual universe
        createSceneGraph(Location);
    }

      void setViewpoint() {
        Viewer viewer = u.getViewer();
        View view = viewer.getView();
        
        // this is new. hope it works. I'd like to transform the center of the 
        // object bounding sphere to be the center of the canvas...
       
        
        // point the view at the center of the object
        Point3d c = new Point3d();
        sceneBounds.getCenter(c);
        
        System.out.println(sceneBounds.toString());
        
        Vector3d temp2 = new Vector3d(0,0,0);
        
        Transform3D centerTrans = new Transform3D();
       //Transform3D temp3 = new Transform3D();
        //temp2.normalize();
       // temp2.negate();
        centerTrans.set(0.7, temp2);
       // objTrans.getTransform(temp3);
      //  temp3.sub(centerTrans);
         
       // Transform3D t = new Transform3D();
      // t.set(0.7, new Vector3d(0, 0, 0));
       //TransformGroup objTrans = new TransformGroup(t);
        
        objTrans.setTransform(centerTrans);
        sceneBounds.setCenter(new Point3d(0,0,0));
        
         System.out.println(sceneBounds.toString());
        //objTrans.setTransform(t);
        
        
        Point3d center = new Point3d();
        sceneBounds.getCenter(center);
        double radius = sceneBounds.getRadius();
        Vector3d temp = new Vector3d(center);
        
        Transform3D viewTrans = new Transform3D();
        Transform3D eyeTrans = new Transform3D();

        
        
        viewTrans.set(temp);

        // pull the eye back far enough to see the whole object
        double eyeDist = 1.4*radius / Math.tan(view.getFieldOfView() / 2.0);
        temp.x = 0.0;
        temp.y = 0.0;
        temp.z = eyeDist;
        eyeTrans.set(temp);
        viewTrans.mul(eyeTrans);

        // set the view transform 
        vpTransGroup.setTransform(viewTrans);
        
       
    }
    

    private void setupBehavior() {
        // Create the root of the branch graph
        objRoot = new BranchGroup();

        sceneGroup.setCapability(BranchGroup.ALLOW_DETACH);
        sceneGroup.setCapability(BranchGroup.ALLOW_BOUNDS_READ);
        sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
        sceneGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
        sceneGroup.setCapability(BranchGroup.ENABLE_PICK_REPORTING);
        sceneGroup.setCapability(BranchGroup.ALLOW_AUTO_COMPUTE_BOUNDS_READ);
        sceneGroup.setCapability(BranchGroup.ALLOW_AUTO_COMPUTE_BOUNDS_WRITE);
            
        // Create a Transformgroup to scale all objects so they
        // appear in the scene.
        TransformGroup objScale = new TransformGroup();
        Transform3D t3d = new Transform3D();
        
        t3d.setScale(0.5);
        
        objScale.setTransform(t3d);
        objRoot.addChild(objScale);

        // Create the transform group node and initialize it to the
        // identity.  Enable the TRANSFORM_WRITE capability so that
        // our behavior code can modify it at runtime.  Add it to the
        // root of the subgraph.
        objTrans = new TransformGroup();
        objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
        objTrans.setCapability(TransformGroup.ALLOW_CHILDREN_EXTEND);
        objTrans.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
        objTrans.setCapability(TransformGroup.ALLOW_CHILDREN_WRITE);
        objTrans.setCapability(TransformGroup.ENABLE_PICK_REPORTING);
        
        objScale.addChild(objTrans);
        
        bounds = new BoundingSphere(new Point3d(), Double.MAX_VALUE);

      
          // Create the rotate behavior node
          MouseRotate mr = new MouseRotate();
          mr.setTransformGroup(objTrans);
          objTrans.addChild(mr);
          mr.setSchedulingBounds(bounds);

          // Create the zoom behavior node
          MouseZoom mz = new MouseZoom();
          mz.setTransformGroup(objTrans);
          objTrans.addChild(mz);
          mz.setSchedulingBounds(bounds);

          // Create the translate behavior node
          MouseTranslate mt = new MouseTranslate();
          mt.setTransformGroup(objTrans);
          objTrans.addChild(mt);
          mt.setSchedulingBounds(bounds);
        

          PickRotateBehavior behavior1 =
          new PickRotateBehavior(objRoot, canvas, bounds);
          behavior1.setMode(PickTool.GEOMETRY);
          objRoot.addChild(behavior1);

          PickZoomBehavior behavior2 =
          new PickZoomBehavior(objRoot, canvas, bounds);
          behavior2.setMode(PickTool.GEOMETRY);
          objRoot.addChild(behavior2);

          PickTranslateBehavior behavior3 =
          new PickTranslateBehavior(objRoot, canvas, bounds);
          behavior3.setMode(PickTool.GEOMETRY);
          objRoot.addChild(behavior3);
                
        
        // Set up the background
       /* Color3f bgColor = new Color3f(0.05f, 0.05f, 0.5f);
        Background bgNode = new Background(bgColor);
        bgNode.setApplicationBounds(bounds);
        objRoot.addChild(bgNode);*/

        // Set up the ambient light
        Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f);
        AmbientLight ambientLightNode = new AmbientLight(ambientColor);
        ambientLightNode.setInfluencingBounds(bounds);
        objRoot.addChild(ambientLightNode);

        // Set up the directional lights
        Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f);
        Vector3f light1Direction  = new Vector3f(4.0f, -7.0f, -12.0f);
        Color3f light2Color = new Color3f(0.3f, 0.3f, 0.4f);
        Vector3f light2Direction  = new Vector3f(-6.0f, -2.0f, -1.0f);
        
        
        DirectionalLight        headLight;
        AmbientLight    ambLight;
    
        BoundingSphere lightBounds =
        new BoundingSphere(new Point3d(), Double.MAX_VALUE);
        ambLight = new AmbientLight(true, new Color3f(1.0f, 1.0f, 1.0f));
        ambLight.setInfluencingBounds(lightBounds);
        ambLight.setCapability(Light.ALLOW_STATE_WRITE);
        objRoot.addChild(ambLight);
        headLight = new DirectionalLight();
        headLight.setCapability(Light.ALLOW_STATE_WRITE);
        headLight.setInfluencingBounds(lightBounds);
        objRoot.addChild(headLight);
        
        

        DirectionalLight light1
            = new DirectionalLight(light1Color, light1Direction);
        light1.setInfluencingBounds(bounds);
        objRoot.addChild(light1);

        DirectionalLight light2
            = new DirectionalLight(light2Color, light2Direction);
        light2.setInfluencingBounds(bounds);
        objRoot.addChild(light2);
        
        u.addBranchGraph(objRoot);
    }
    
     public void actionPerformed(ActionEvent ae) {
    
         
        Location = textField.getText();
        createSceneGraph(Location);
        
        
    }
    
    

  
    public static void main(String[] args) {
        
          String InitLoc = System.getProperties().getProperty("user.dir") +
                "/objfiles/";
        //a temporary frame to store our ObjLoad object... this
        // will later be put into an actual compass frame
        JFrame j = new JFrame();
       
        ObjLoad OB = new ObjLoad(InitLoc); 
        
        j.getContentPane().add("Center", OB);
        
        j.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

        
        j.setVisible(true);
        j.setSize(500,500);
       j.show();
    
        
    }
    
}




