Thursday, January 27, 2011

Computer Graphics: 3D Bouncing Ball

I have promised that I will share my final tasks in the last semester to this blog. OK, firstly I will share my Computer Graphics final task. I created 3D Bouncing Ball using Java Programming Language. Ups sorry, I didn't create it by myself. I just modified it. Greg Hopkins is the real creator of this program. Originally, this program was too simple. You could just see a ball bouncing up and down. So, I modified this program till it becomes more interesting. :D


The image above is the screenshoot of modified program. I added some property: stop button, x speed, y speed, z speed. Ah yeah, this program could interact against user. So you can control each property, including control the scale of ball. Well, here the instructions:


a : decrease x property
d : increase x property
s : decrease y property
w : increase y property
f : decrease z property
r : increase z property

i : increase y speed
k : decrease y speed
l : increase x speed
j : decrease x speed
y : increase z speed
h : decrease z speed

[ : increase ball size
] : decrease ball size
 Want to try this program? Here the source code:

/**
 *
 * @editedby ilham hasymi effendi
 * @homepage http://hamzcraze.blogspot.com
 *
/*

 
The Joy of Java 3D

by Greg Hopkins

Copyright Copyright 2001


 */
/*

To create animation you need to move the objects between each frame of animation. You can
use a timer and move the 3D objects by a small amount each time. Also, you can modify the
objects in other ways, the next example scales the ball so that it looks squashed at the
bottom of each bounce.

For interaction with the user, you can process keystrokes or clicks on buttons or other
components.

One thing to notice is that you have to tell Java3D you are going to move something by
setting a capability. Otherwise, you will not be able to move anything once it has been
drawn.

objTrans = new TransformGroup();
objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);

The following example combines these techniques. You start it by clicking on the button,
then the ball bounces up and down, and you can press a or s to move the ball left or
right.


 */
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.GraphicsConfiguration;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.media.j3d.AmbientLight;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.swing.Timer;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;

import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.universe.SimpleUniverse;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class BouncingBallModification extends Applet implements ActionListener, KeyListener {

    private Button go = new Button("Go");
    private Button stop = new Button("Stop");
    private JLabel xspeedL = new JLabel("xspeed: ");
    private JTextField xspeedTF = new JTextField(5);
    private JLabel yspeedL = new JLabel("yspeed: ");
    private JTextField yspeedTF = new JTextField(5);
    private JLabel zspeedL = new JLabel("zspeed: ");
    private JTextField zspeedTF = new JTextField(5);
    private TransformGroup objTrans;
    private Transform3D trans = new Transform3D();
    private float yloc = 0.0f;
    private float sign = 1.0f; // going up or down
    private float sign2 = 1.0f; // going left or right //edited
    private float sign3 = 1.0f; // going left or right //edited
    private float xspeed = 0.05f; // going left or right //edited
    private float yspeed = 0.05f; // going left or right //edited
    private float zspeed = 0.00f; // going left or right //edited
    private float scale = 1.0f; //scale //edited
    private Timer timer;
    private float xloc = 0.0f;
    private float zloc = 0.0f;

    public BranchGroup createSceneGraph() {
        // Create the root of the branch graph
        BranchGroup objRoot = new BranchGroup();
        objTrans = new TransformGroup();
        objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        objRoot.addChild(objTrans);

        // Create a simple shape leaf node, add it to the scene graph.
        Sphere sphere = new Sphere(0.1f); //edited
        objTrans = new TransformGroup();
        objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        Transform3D pos1 = new Transform3D();
        pos1.setTranslation(new Vector3f(0.0f, 0.0f, 0.0f));
        objTrans.setTransform(pos1);
        objTrans.addChild(sphere);
        objRoot.addChild(objTrans);
        BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
                100.0);

        Color3f light1Color = new Color3f(1.0f, 1.0f, 1.2f); //edited
        Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
        DirectionalLight light1 = new DirectionalLight(light1Color,
                light1Direction);
        light1.setInfluencingBounds(bounds);
        objRoot.addChild(light1);

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

        return objRoot;
    }

    public BouncingBallModification() {
        setLayout(new BorderLayout());
        GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
        Canvas3D c = new Canvas3D(config);
        add("Center", c);
        c.addKeyListener(this);
        timer = new Timer(100, this);
        //timer.start();
        Panel p = new Panel();
        p.add(go);
        p.add(stop);
        p.add(xspeedL);
        p.add(xspeedTF);
        p.add(yspeedL);
        p.add(yspeedTF);
        p.add(zspeedL);
        p.add(zspeedTF);
        add("North", p);
        go.addActionListener(this);
        go.addKeyListener(this);
        stop.addActionListener(this);
        // Create a simple scene and attach it to the virtual universe
        BranchGroup scene = createSceneGraph();

        SimpleUniverse u = new SimpleUniverse(c);
        u.getViewingPlatform().setNominalViewingTransform();
        u.addBranchGraph(scene);
    }

    public void keyPressed(KeyEvent e) {
        //Invoked when a key has been pressed.

        //edited
        if (e.getKeyChar() == 'd') {
            xloc = xloc + .1f;
        }
        //edited
        if (e.getKeyChar() == 'a') {
            xloc = xloc - .1f;
        }

        //edited
        if (e.getKeyChar() == 'w') {
            yloc = yloc + .1f;
        }
        //edited
        if (e.getKeyChar() == 's') {
            yloc = yloc - .1f;
        }

        //edited
        if (e.getKeyChar() == 'r') {
            zloc = zloc - .1f;
        }
        //edited
        if (e.getKeyChar() == 'f') {
            zloc = zloc + .1f;
        }

        //edited
        if (e.getKeyChar() == 'i') {
            yspeed += 0.01f;
        }
        //edited
        if (e.getKeyChar() == 'k') {
            yspeed -= 0.01f;
        }

        //edited
        if (e.getKeyChar() == 'l') {
            xspeed += 0.01f;
        }
        //edited
        if (e.getKeyChar() == 'j') {
            xspeed -= 0.01f;
        }

        //edited
        if (e.getKeyChar() == 'y') {
            zspeed -= 0.01f;
        }
        //edited
        if (e.getKeyChar() == 'h') {
            zspeed += 0.01f;
        }

        //edited
        if (e.getKeyChar() == '[') {
            scale+= 0.1f;
            trans.setScale(new Vector3d(scale, scale, scale));
        }
        //edited
        if (e.getKeyChar() == ']') {
            scale-= 0.1f;
            trans.setScale(new Vector3d(scale, scale, scale));
        }
    }

    public void keyReleased(KeyEvent e) {
        // Invoked when a key has been released.
    }

    public void keyTyped(KeyEvent e) {
        //Invoked when a key has been typed.
    }

    public void actionPerformed(ActionEvent e) {
        // start timer when button is pressed
        xspeedTF.setText(String.valueOf(xspeed));
        yspeedTF.setText(String.valueOf(yspeed));
        zspeedTF.setText(String.valueOf(zspeed));
        if (e.getSource() == stop) {
            timer.stop();
        }
        if (e.getSource() == go) {
            if (!timer.isRunning()) {
                timer.start();
            }
        } else {
            yloc += yspeed * sign; //edited
            xloc += xspeed * sign2; //edited
            zloc += zspeed * sign3; //edited
            if (Math.abs(yloc * 2) >= 2) //edited
            {
                sign = -1.0f * sign;
            }
            if (Math.abs(xloc * 2) >= 2) //edited
            {
                sign2 = -1.0f * sign2;
            }
            if (Math.abs(zloc * 2) >= 2) //edited
            {
                sign3 = -1.0f * sign3;
            }
//            if (yloc < -0.4f) {
//                trans.setScale(new Vector3d(1.0, .8, 1.0));
//            } else {
//                trans.setScale(new Vector3d(1.0, 1.0, 1.0));
//            }
            trans.setTranslation(new Vector3f(xloc, yloc, zloc));
            objTrans.setTransform(trans);
        }
    }

    public static void main(String[] args) {
        System.out.println("Program Started");
        BouncingBallModification bb = new BouncingBallModification();
        bb.addKeyListener(bb);
        MainFrame mf = new MainFrame(bb, 512, 512); //edited
        mf.setVisible(true);
    }
}


Well, that's all guys. Hope you enjoy it. :D

5 comment(s):

Unknown said...

Mantav gan ...
Created by 'ur self kah ??

Aeeizz masolang klo gtu
^___^

Unknown said...

ogak gan. cm ngedit punya orang. :D

indra said...

itu pake program java ya..klu ada tulisan java/lang/nullpointer exception maksudnya apaya..

indra said...

http://www.4shared.com/file/JSez2wEK/uji_coba_aplikasi.html
tolong kirim via email muhienj90@gmail.com

Unknown said...

@indra: uda ak kirim mas, silakan emailnya dicek.. :)

Post a Comment

feel free to write your comment here.. :)