Lesson #8a : Loading Wavefront Objects


Java3D has support for Wavefront Object files (.obj) built-in.

To load .obj files, first we must import 2 new packages:
	import com.sun.j3d.loaders.*;
	import com.sun.j3d.loaders.objectfile.ObjectFile;
Since object files are usually created at the origin, we should first create a TransformGroup
and a Transform3D so that we can move the objects.
	TransformGroup tg = new TransformGroup();
        Transform3D t3d = new Transform3D();
Next since we are opening up files, we should setup the try/catch code:
      	try
	{	
		// code in here

	}

      	catch (java.net.MalformedURLException ex){	
      	}
      	catch (java.io.FileNotFoundException ex){
      	}

The next setup is within the try portion:
	Scene s = null;
   	ObjectFile f = new ObjectFile ();
    	f.setFlags (ObjectFile.RESIZE | ObjectFile.TRIANGULATE | ObjectFile.STRIPIFY);
The object we will load is called airtable.obj

To load it as an applet and add to the TransformGroup:
	java.net.URL airFile = new java.net.URL (getCodeBase(), "airtable.obj");
	s = f.load (airFile);
	tg.addChild (s.getSceneGroup ());
To load as an application and add to the TransformGroup:
	String s1 = "airtable.obj";
	s = f.load (s1);
	tg.addChild (s.getSceneGroup ());
After the 2 catch codes, we should add some lighting, or the object will not show up.
This will make a gray ambient light for the scene:
      	BoundingSphere bounds = new BoundingSphere (new Point3d (0.0, 0.0, 0.0), 100.0);
      	Color3f ambientColor = new Color3f (0.5f, 0.5f, 0.5f);
      	AmbientLight ambientLightNode = new AmbientLight (ambientColor);
      	ambientLightNode.setInfluencingBounds (bounds);
      	objRoot.addChild (ambientLightNode);	
Then just move the TransformGroup of the loaded object, and add it to objRoot
      	t3d.setTranslation(new Vector3f(0f,0f,-5f));
      	tg.setTransform(t3d);
      	objRoot.addChild(tg);


Source Code for this lesson: lesson08a.java and the object