Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Java 3D joy ride

Suzy Deffeyes (suzyq@us.ibm.com), Software Engineer, EMC
Suzy Deffeyes is a 3D software engineer at IBM in Austin, Texas. She is the developer responsible for the original release of Java 3D for AIX, and represents IBM on the Java expert group for 3D Media Utilities. She is currently a member of IBM's Linux Technology Center. Her past projects included OpenGL API design and development, Direct 3D driver development, and C++ scene graph technologies. She also did the AIX ports for Quake and Quake 2, and ensured that they were thoroughly tested.

Summary:  This introduction to Java™ 3D provides Java programmers who are new to the 3D world with hands-on experience in Java 3D graphics programming.

Date:  29 Nov 2001
Level:  Introductory PDF:  A4 and Letter (800 KB | 42 pages)Get Adobe® Reader®

Activity:  14454 views
Comments:  

Appendix: The source

UglyCube.java

/*
 *
 * Copyright (c) 1996-2001 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 java.applet.Applet;
import java.awt.BorderLayout;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;


//Bare minimum really boring cube.
// Shows bare bones Universe creation

public class UglyCube extends Applet {

    private SimpleUniverse universe ;
    public UglyCube() {
        }
    public void init() {

      //canvas to draw on, ask SimpleUniverse what config to use
      Canvas3D canvas = new Canvas3D(
          SimpleUniverse.getPreferredConfiguration());
      setLayout(new BorderLayout());
      add("Center", canvas);
     
      //create top of our scene graph
      BranchGroup scene = new BranchGroup();

      //attach the cube to it
      scene.addChild(new ColorCube(0.4));
    
      //create universe, and attach our geometry to it.
      SimpleUniverse u = new SimpleUniverse(canvas);
      u.getViewingPlatform().setNominalViewingTransform();
      
        //rendering starts after BranchGroup is attached.
      u.addBranchGraph(scene);

    }

    // The following allows UglyCube to be run as an application
    // as well as an applet
    public static void main(String[] args) {
        new MainFrame(new UglyCube(), 256, 256);
    }
}


TransformOrder.java (Part 1)

/*
 *
 * Copyright (c) 1996-2001 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 java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
import java.awt.GraphicsConfiguration;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.behaviors.vp.*;



/**
   Generates a scene graph with the cylinders that 
   make up the axis, and 3 cones. 
   Add one Cone with rotate before translate, and 
   another that has translate before rotate.
   For reference, throw in a cone without translate
   or rotate

*/




public class TransformOrder extends Applet {

    public static final int X =1;
    public static final int Y =2;
    public static final int Z =3;
    public static final int ROTATE_TOP    =4;
    public static final int TRANSLATE_TOP =5;
    public static final int NO_TRANSFORM  =6;

    private SimpleUniverse universe ;
    private BranchGroup scene;
    private Canvas3D canvas;
    private BoundingSphere bounds =
            new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 1000.0);
    
    private Appearance red = new Appearance();
    private Appearance yellow = new Appearance();
    private Appearance purple = new Appearance();
    Transform3D rotate = new Transform3D();
    Transform3D translate = new Transform3D();

    
    public void setupView() {
	/** Add some view related things to view branch side 
	of scene graph */
        // add mouse interaction to the ViewingPlatform
        OrbitBehavior orbit = new OrbitBehavior(canvas,
                OrbitBehavior.REVERSE_ALL|OrbitBehavior.STOP_ZOOM);
        orbit.setSchedulingBounds(bounds);
	
	ViewingPlatform viewingPlatform = universe.getViewingPlatform();
        // This will move the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
        viewingPlatform.setNominalViewingTransform();
        viewingPlatform.setViewPlatformBehavior(orbit);

	}

    //construct each branch of the graph, changing the order children added
    // since  Group node can only have one parent, have to construct
    // new translate and rotate group nodes for each branch.
    Group rotateOnTop(){
          Group root=new Group();
          TransformGroup objRotate = new TransformGroup(rotate);
          TransformGroup objTranslate = new TransformGroup(translate);
          Cone redCone=  
              new Cone(.3f, 0.7f, Primitive.GENERATE_NORMALS, red);
          root.addChild(objRotate);
          objRotate.addChild(objTranslate);
          objTranslate.addChild(redCone); //tack on red cone
          return root;
    }
    Group translateOnTop(){
          Group root=new Group();
          TransformGroup objRotate = new TransformGroup(rotate);
          TransformGroup objTranslate = new TransformGroup(translate);
          Cone yellowCone=  
              new Cone(.3f, 0.7f, Primitive.GENERATE_NORMALS, yellow);
          root.addChild(objTranslate);
          objTranslate.addChild(objRotate);
          objRotate.addChild(yellowCone); //tack on yellow cone
          return root;
    
    }
    
    Group noTransform(){
          Cone purpleCone=  
              new Cone(.3f, 0.7f, Primitive.GENERATE_NORMALS, purple);
          return purpleCone;
    }




TransformOrder.java (Part 2)




    /** Represent an axis using cylinder Primitive. Cylinder is 
	aligned with Y axis, so we have to rotate it when 
	creating X and Z axis
    */
    public TransformGroup createAxis(int type) {

	//appearance and lightingProps are used in
	//lighting. Each axis a different color
	Appearance appearance = new Appearance();
	Material lightingProps = new Material();


        Transform3D t = new Transform3D();
	switch (type) {
	   case Z:
              t.rotX(Math.toRadians(90.0));
	      lightingProps.setAmbientColor(1.0f,0.0f,0.0f);
	   break;
	   case Y:
              // no rotation needed, cylinder aligned with Y already
	      lightingProps.setAmbientColor(0.0f,1.0f,0.0f);
	   break;
	   case X:
              t.rotZ(Math.toRadians(90.0));
	      lightingProps.setAmbientColor(0.0f,0.0f,1.0f);
	   break;
	   default:
	   break;
	}
	appearance.setMaterial(lightingProps);

        TransformGroup objTrans = new TransformGroup(t);
	objTrans.addChild( new Cylinder(.03f,2.5f,Primitive.GENERATE_NORMALS,appearance));
	return objTrans;
    }

    /** Create X, Y , and Z axis, and 3 cones. Throws in 
	some quick lighting to help viewing the scene
    */
    public BranchGroup createSceneGraph() {
	// Create the root of the branch graph
	BranchGroup objRoot = new BranchGroup();

	//45 degree rotation around the X axis
        rotate.rotX(Math.toRadians(45.0));

	//translation up the Y axis
	translate.setTranslation(new Vector3f(0.0f,2.0f,1.0f)); //SCD 0.0f));

        //Material objects are related to lighting, we'll cover
        //that later
        Material redProps = new Material();
        redProps.setAmbientColor(1.0f,0.0f,0.0f); //red cone
	red.setMaterial(redProps);

        Material yellowProps = new Material();
        yellowProps.setAmbientColor(1.0f,1.0f,0.0f); //yellow cone
	yellow.setMaterial(yellowProps);

        Material purpleProps = new Material();
        purpleProps.setAmbientColor(0.8f,0.0f,0.8f); //purple cone
	purple.setMaterial(purpleProps);

	// Create a x,y,z axis, and then 3 cone branches

	objRoot.addChild(createAxis(X));
	objRoot.addChild(createAxis(Y));
	objRoot.addChild(createAxis(Z));

	objRoot.addChild(noTransform());    //purple cone
	objRoot.addChild(rotateOnTop());      //red cone
	objRoot.addChild(translateOnTop());   //yellow cone

	//throw in some light so we aren't stumbling 
	//around in the dark
	Color3f lightColor = new Color3f(.3f,.3f,.3f);
        AmbientLight ambientLight= new AmbientLight(lightColor);
        ambientLight.setInfluencingBounds(bounds);
        objRoot.addChild(ambientLight);
        DirectionalLight directionalLight = new DirectionalLight();
        directionalLight.setColor(lightColor);
        directionalLight.setInfluencingBounds(bounds);
        objRoot.addChild(directionalLight);


	return objRoot;

    }

    public TransformOrder() {
    }

    public void init() {
	BranchGroup scene = createSceneGraph();

	setLayout(new BorderLayout());
        GraphicsConfiguration config =
           SimpleUniverse.getPreferredConfiguration();
	canvas = new Canvas3D(config);
	add("Center", canvas);

	// Create a simple scene and attach it to the virtual universe
	universe = new SimpleUniverse(canvas);

	setupView();

	universe.addBranchGraph(scene);
    }

    public void destroy() {
	universe.removeAllLocales();
    }

    //
    // The following allows TransformOrder to be run as an application
    // as well as an applet
    //
    public static void main(String[] args) {
	new MainFrame(new TransformOrder(), 256, 256);
    }
}


Wallpaper.java (Part 1)

/*
 *
 * Copyright (c) 1996-2001 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 java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
import java.awt.GraphicsConfiguration;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.image.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.behaviors.vp.*;



/**
   Simple Texture Mapping example

*/




public class Wallpaper extends Applet {

    private SimpleUniverse universe ;
    private BranchGroup scene;
    private Canvas3D canvas;
    private BoundingSphere bounds =
            new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 1000.0);
    private static java.net.URL texImage = null;
    
    



    public Group  createGeometry(int filter, float y, java.net.URL texImage) {
        /** 
        Create some Texture mapped objects
        */

        Appearance appearance = new Appearance();






Wallpaper.java (Part 2)

        TextureLoader tex = new TextureLoader
          (texImage, TextureLoader.GENERATE_MIPMAP , this);
        Texture texture = tex.getTexture();
        texture.setMinFilter(filter) ;
        appearance.setTexture(texture);


        TextureAttributes texAttr = new TextureAttributes();
        texAttr.setTextureMode(TextureAttributes.MODULATE);
        appearance.setTextureAttributes(texAttr);


        Color3f black = new Color3f(0.0f, 0.0f, 0.0f);
        Color3f white = new Color3f(1.0f, 1.0f, 1.0f);

        // Set up the material properties
        appearance.setMaterial(new Material(white, black, white, black, 1.0f));

        //use to build tree hierarchy
        Group topNode = new Group();


        Transform3D translate = new Transform3D();
        translate.setTranslation(new Vector3f(.5f,y,-0.5f));
        TransformGroup gimmeSpace = new TransformGroup(translate);

        Cone cone =  new Cone
           (.4f,0.8f,Primitive.GENERATE_NORMALS|
           Primitive.GENERATE_TEXTURE_COORDS,appearance);
        gimmeSpace.addChild(cone);
        topNode.addChild(gimmeSpace); //cone at bottom

        translate = new Transform3D();
        translate.setTranslation(new Vector3f(-0.5f,y,-0.5f));
        gimmeSpace = new TransformGroup(translate);

        Sphere sphere = new Sphere
           (.4f,Primitive.GENERATE_NORMALS|Primitive.GENERATE_TEXTURE_COORDS,appearance);
        gimmeSpace.addChild(sphere);
        topNode.addChild(gimmeSpace); //cone at bottom

        return topNode;
    }

    public void setupView() {
        /** Add some view related things to view branch side 
        of scene graph */
        // add mouse interaction to the ViewingPlatform
        OrbitBehavior orbit = new OrbitBehavior(canvas,
                OrbitBehavior.REVERSE_ALL|OrbitBehavior.STOP_ZOOM);
        orbit.setSchedulingBounds(bounds);
        
        ViewingPlatform viewingPlatform = universe.getViewingPlatform();
        // This will move the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
        viewingPlatform.setNominalViewingTransform();
        viewingPlatform.setViewPlatformBehavior(orbit);

        }

    public BranchGroup createSceneGraph() {
        // Create the root of the branch graph
        BranchGroup objRoot = new BranchGroup();

        // Create a simple Shape3D node; add it to the scene graph.
        // Set up the texture map
        // the path to the image

        objRoot.addChild(createGeometry( Texture.BASE_LEVEL_POINT,1.0f,texImage));
        objRoot.addChild(createGeometry( Texture.MULTI_LEVEL_POINT,0.0f,texImage));
        objRoot.addChild(createGeometry( Texture.MULTI_LEVEL_LINEAR,-1.0f,texImage));

        //throw in some light so we aren't stumbling 
        //around in the dark
        Color3f lightColor = new Color3f(.5f,.5f,.5f);
        AmbientLight ambientLight= new AmbientLight(lightColor);
        ambientLight.setInfluencingBounds(bounds);
        objRoot.addChild(ambientLight);
        DirectionalLight directionalLight = new DirectionalLight();
        directionalLight.setColor(lightColor);
        directionalLight.setInfluencingBounds(bounds);
        objRoot.addChild(directionalLight);


        return objRoot;

    }

    public Wallpaper() {
    }

    public void init() {
        BranchGroup scene = createSceneGraph();

        setLayout(new BorderLayout());
        GraphicsConfiguration config =
           SimpleUniverse.getPreferredConfiguration();
        canvas = new Canvas3D(config);
        add("Center", canvas);

        // Create a simple scene and attach it to the virtual universe
        universe = new SimpleUniverse(canvas);

        setupView();

        universe.addBranchGraph(scene);
    }

    public void destroy() {
        universe.removeAllLocales();
    }

    //
    // The following allows Wallpaper to be run as an application
    // as well as an applet
    //
    public static void main(String[] args) {

        try{
           if (args.length == 0) {
             texImage = new java.net.URL("file:./images/speedchase.jpg");
           } else {
             texImage = new java.net.URL(args[0]);
            }
        }
        catch (java.net.MalformedURLException ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }
        new MainFrame(new Wallpaper(), 256, 256);
    }
}


SupermanInterp.java (Part 1)

/*
 *
 * Copyright (c) 1996-2001 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 java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
import java.awt.GraphicsConfiguration;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.image.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.behaviors.vp.*;



/**
   Rotation Interpolator example

   Very similar to texture mapping example, but 
   attaches an Interpolator above geometry that
   keeps the world spinning. Play with Alpha timing,
   you can have it slowly ease to a halt by using
   some of the other parameters that aren't in this
   simple example. It will also reverse direction.


*/


public class SupermanInterp extends Applet {

    private SimpleUniverse universe ;
    private BranchGroup scene;
    private Canvas3D canvas;
    private BoundingSphere bounds =
            new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 1000.0);
    
    

    public Primitive  createGeometry
        (int filter,  java.net.URL texImage, Appearance appearance) {
        /** 
        Create Sphere and texture it
        */


        TextureLoader tex = 
            new TextureLoader(texImage, TextureLoader.GENERATE_MIPMAP , this);
        Texture texture = tex.getTexture();
        texture.setMinFilter(filter) ;
        appearance.setTexture(texture);


        TextureAttributes texAttr = new TextureAttributes();
        texAttr.setTextureMode(TextureAttributes.MODULATE);
        appearance.setTextureAttributes(texAttr);


        Color3f black = new Color3f(0.0f, 0.0f, 0.0f);
        Color3f white = new Color3f(1.0f, 1.0f, 1.0f);

        // Set up the material properties
        appearance.setMaterial(new Material(white, black, white, black, 1.0f));

        Sphere sphere = 
            new Sphere(.4f,Primitive.GENERATE_NORMALS|
                           Primitive.GENERATE_TEXTURE_COORDS,appearance);

        return sphere;
    }

  


SupermanInterp.java (Part 2)

  public void setupView() {
        /** Add some view related things to view branch side 
        of scene graph */
        // add mouse interaction to the ViewingPlatform
        OrbitBehavior orbit = new OrbitBehavior(canvas,
                OrbitBehavior.REVERSE_ALL|OrbitBehavior.STOP_ZOOM);
        orbit.setSchedulingBounds(bounds);
        
        ViewingPlatform viewingPlatform = universe.getViewingPlatform();
        // This will move the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
        viewingPlatform.setNominalViewingTransform();
        viewingPlatform.setViewPlatformBehavior(orbit);

        }

    public BranchGroup createSceneGraph() {
        // Create the root of the branch graph
        BranchGroup objRoot = new BranchGroup();

        // Create a simple Shape3D node; add it to the scene graph.
        // Set up the texture map
        java.net.URL texImage = null;
        // the path to the image
        try {
            texImage = new java.net.URL("file:../images/earth.jpg");
        }
        catch (java.net.MalformedURLException ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }

        Appearance app= new Appearance();
        Primitive geo = createGeometry( Texture.MULTI_LEVEL_LINEAR,texImage,app);
        
        //spinGroup will be hooked into the interpolator
        TransformGroup spinGroup = new TransformGroup();
        spinGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        spinGroup.addChild(geo);

        // Create a new Behavior object that will perform the
        // desired operation on the specified transform and add
        // it into the scene graph.

        //OLD:  straight constant spin 
        //      Alpha rotationAlpha = new Alpha(-1, 4000);
        //NEW:  accelerate one direction, stop, rotate opposite direction
        Alpha rotationAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE |
                                        Alpha.DECREASING_ENABLE,
                                        0, 0,
                                        5000, 2500, 200,
                                        5000, 2500, 200);

        RotationInterpolator rotator =
            new RotationInterpolator(rotationAlpha, spinGroup);
        rotator.setSchedulingBounds(bounds);

        //throw in some light so we aren't stumbling 
        //around in the dark
        Color3f lightColor = new Color3f(.5f,.5f,.5f);
        AmbientLight ambientLight= new AmbientLight(lightColor);
        ambientLight.setInfluencingBounds(bounds);
        DirectionalLight directionalLight = new DirectionalLight();
        directionalLight.setColor(lightColor);
        directionalLight.setInfluencingBounds(bounds);

        objRoot.addChild(rotator); //behavior gets attached at the top
        objRoot.addChild(spinGroup); //TransformGroup and sphere
        objRoot.addChild(directionalLight);
        objRoot.addChild(ambientLight);

        return objRoot;

    }

    public SupermanInterp() {
    }

    public void init() {
        BranchGroup scene = createSceneGraph();

        setLayout(new BorderLayout());
        GraphicsConfiguration config =
           SimpleUniverse.getPreferredConfiguration();
        canvas = new Canvas3D(config);
        add("Center", canvas);

        // Create a simple scene and attach it to the virtual universe
        universe = new SimpleUniverse(canvas);
        setupView();

        universe.addBranchGraph(scene);
    }

    public void destroy() {
        universe.removeAllLocales();
    }

    //
    // The following allows SupermanInterp to be run as an application
    // as well as an applet
    //
    public static void main(String[] args) {
        new MainFrame(new SupermanInterp(), 256, 256);
    }
}


ColorInterp.java (Part 1)

/*
 *
 * Copyright (c) 1996-2001 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 java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
import java.awt.GraphicsConfiguration;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.image.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.behaviors.vp.*;



/**
   Color Interpolator example

   Very similar to texture mapping example, 
   will interpolate the color values of the
   earth.

*/




public class ColorInterp extends Applet {

    private SimpleUniverse universe ;
    private BranchGroup scene;
    private Canvas3D canvas;
    private BoundingSphere bounds =
            new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 1000.0);
    
    



 


ColorInterp.java (Part 2)

   public Primitive  createGeometry
        (int filter,  java.net.URL texImage, Appearance appearance) {
        /** 
        Create Sphere and texture it
        */


        TextureLoader tex = 
            new TextureLoader(texImage, TextureLoader.GENERATE_MIPMAP , this);
        Texture texture = tex.getTexture();
        texture.setMinFilter(filter) ;
        appearance.setTexture(texture);


        TextureAttributes texAttr = new TextureAttributes();
        texAttr.setTextureMode(TextureAttributes.MODULATE);
        appearance.setTextureAttributes(texAttr);


        Color3f black = new Color3f(0.0f, 0.0f, 0.0f);
        Color3f white = new Color3f(1.0f, 1.0f, 1.0f);
        Color3f gray = new Color3f(0.3f, 0.3f, 0.3f);
        Color3f ltgray = new Color3f(0.6f, 0.6f, 0.6f);

        // Set up the material properties
        appearance.setMaterial(new Material(white, black, ltgray, ltgray, 32.0f));

        Sphere sphere = 
            new Sphere(.4f,Primitive.GENERATE_NORMALS|
                           Primitive.GENERATE_TEXTURE_COORDS,appearance);

        return sphere;
    }

    public void setupView() {
        /** Add some view related things to view branch side 
        of scene graph */
        // add mouse interaction to the ViewingPlatform
        OrbitBehavior orbit = new OrbitBehavior(canvas,
                OrbitBehavior.REVERSE_ALL|OrbitBehavior.STOP_ZOOM);
        orbit.setSchedulingBounds(bounds);
        
        ViewingPlatform viewingPlatform = universe.getViewingPlatform();
        // This will move the ViewPlatform back a bit so the
        // objects in the scene can be viewed.
        viewingPlatform.setNominalViewingTransform();
        viewingPlatform.setViewPlatformBehavior(orbit);

        }

    public BranchGroup createSceneGraph() {
        // Create the root of the branch graph
        BranchGroup objRoot = new BranchGroup();

        // Create a simple Shape3D node; add it to the scene graph.
        // Set up the texture map
        java.net.URL texImage = null;
        // the path to the image
        try {
            texImage = new java.net.URL("file:../images/earth.jpg");
        }
        catch (java.net.MalformedURLException ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }

        Appearance app= new Appearance();
        Primitive geo = createGeometry( Texture.MULTI_LEVEL_LINEAR,texImage,app);
        
        //spinGroup will be hooked into the interpolator
        TransformGroup spinGroup = new TransformGroup();
        spinGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        spinGroup.addChild(geo);

        // Create a new Behavior object that will perform the
        // desired operation on the specified transform and add
        // it into the scene graph.
        Alpha rotationAlpha = new Alpha(-1, 4000);

        RotationInterpolator rotator =
            new RotationInterpolator(rotationAlpha, spinGroup);
        rotator.setSchedulingBounds(bounds);


        //we'll need the Material to Interpolate the diffuse color
        //set capability bit to allow interpolator to change at render time
        Material mat = app.getMaterial();
        mat.setCapability(Material.ALLOW_COMPONENT_WRITE);
        Alpha colorAlpha = new Alpha(-1, 2000);

        //We interpolate from black to white, looping indefinitely
        Color3f endColor = new Color3f(1.0f,1.0f,1.0f);
        Color3f startColor = new Color3f(0.0f,0.0f,0.0f);
        ColorInterpolator colorInterp =
            new ColorInterpolator(colorAlpha, mat,startColor,endColor);
        colorInterp.setSchedulingBounds(bounds);

        //throw in some light so we aren't stumbling 
        //around in the dark
        Color3f lightColor = new Color3f(.5f,.5f,.5f);
        AmbientLight ambientLight= new AmbientLight(lightColor);
        ambientLight.setInfluencingBounds(bounds);
        DirectionalLight directionalLight = new DirectionalLight();
        directionalLight.setColor(lightColor);
        directionalLight.setInfluencingBounds(bounds);

        objRoot.addChild(rotator); //behavior gets attached at the top
        objRoot.addChild(colorInterp); //behavior gets attached at the top
        objRoot.addChild(spinGroup); //TransformGroup and sphere
        objRoot.addChild(directionalLight);
        objRoot.addChild(ambientLight);

        return objRoot;

    }

    public ColorInterp() {
    }

    public void init() {
        BranchGroup scene = createSceneGraph();

        setLayout(new BorderLayout());
        GraphicsConfiguration config =
           SimpleUniverse.getPreferredConfiguration();
        canvas = new Canvas3D(config);
        add("Center", canvas);

        // Create a simple scene and attach it to the virtual universe
        universe = new SimpleUniverse(canvas);
        setupView();

        universe.addBranchGraph(scene);
    }

    public void destroy() {
        universe.removeAllLocales();
    }

    //
    // The following allows ColorInterp to be run as an application
    // as well as an applet
    //
    public static void main(String[] args) {
        new MainFrame(new ColorInterp(), 256, 256);
    }
}

10 of 12 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=131764
TutorialTitle=Java 3D joy ride
publish-date=11292001
author1-email=suzyq@us.ibm.com
author1-email-cc=jaloi@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).