com.sun.j3d.loaders.objectfile
Class ObjectFile

java.lang.Object
  extended by com.sun.j3d.loaders.objectfile.ObjectFile
All Implemented Interfaces:
Loader

public class ObjectFile
extends java.lang.Object
implements Loader

The ObjectFile class implements the Loader interface for the Wavefront .obj file format, a standard 3D object file format created for use with Wavefront's Advanced Visualizer (tm) and available for purchase from Viewpoint DataLabs, as well as other 3D model companies. Object Files are text based files supporting both polygonal and free-form geometry (curves and surfaces). The Java 3D .obj file loader supports a subset of the file format, but it is enough to load almost all commonly available Object Files. Free-form geometry is not supported.

The Object File tokens currently supported by this loader are:

v float float float

A single vertex's geometric position in space. The first vertex listed in the file has index 1, and subsequent vertices are numbered sequentially.

vn float float float

A normal. The first normal in the file is index 1, and subsequent normals are numbered sequentially.

vt float float

A texture coordinate. The first texture coordinate in the file is index 1, and subsequent normals are numbered sequentially.

f int int int . . .

or

f int/int int/int int/int . . .

or

f int/int/int int/int/int int/int/int . . .

A polygonal face. The numbers are indexes into the arrays of vertex positions, texture coordinates, and normals respectively. There is no maximum number of vertices that a single polygon may contain. The .obj file specification says that each face must be flat and convex, but if the TRIANGULATE flag is sent to the ObjectFile constructor, each face will be triangulated by the Java 3D Triangulator, and therefore may be concave. A number may be omitted if, for example, texture coordinates are not being defined in the model. Numbers are normally positive indexes, but may also be negative. An index of -1 means the last member added to the respective array, -2 is the one before that, and so on.

g name

Faces defined after this token will be added to the named group. These geometry groups are returned as separated Shape3D objects attached to the parent SceneGroup. Each named Shape3D will also be in the Hashtable returned by Scene.getNamedObjects(). It is legal to add faces to a group, switch to another group, and then add more faces to the original group by reissuing the same name with the g token. If faces are added to the model before the g token is seen, the faces are put into the default group called "default."

s int

or

s off

If the vn token is not used in the file to specify vertex normals for the model, this token may be used to put faces into groups for normal calculation ("smoothing groups") in the same manner as the 'g' token is used to group faces geometrically. Faces in the same smoothing group will have their normals calculated as if they are part of the same smooth surface. To do this, we use the Java 3D NormalGenerator utility with the creaseAngle parameter set to PI (180 degrees - smooth shading, no creases) or to whatever the user has set the creaseAngle. Faces in group 0 or 'off' use a creaseAngle of zero, meaning there is no smoothing (the normal of the face is used at all vertices giving the surface a faceted look; there will be a crease, or "Hard Edge," between each face in group zero). There is also an implied hard edge between each smoothing group, where they meet each other.

If neither the vn nor the s token is used in the file, then normals are calculated using the creaseAngle set in the contructor. Normals are calculated on each geometry group separately, meaning there will be a hard edge between each geometry group.

usemtl name

The current (and subsequent) geometry groups (specified with the 'g' token) have applied to them the named material property. The following set of material properties are available by default:

     amber           amber_trans       aqua            aqua_filter
     archwhite       archwhite2        bflesh          black
     blondhair       blue_pure         bluegrey        bluetint
     blugrn          blutan            bluteal         bone
     bone1           bone2             brass           brnhair
     bronze          brown             brownlips       brownskn
     brzskin         chappie           charcoal        deepgreen
     default         dkblue            dkblue_pure     dkbrown
     dkdkgrey        dkgreen           dkgrey          dkorange
     dkpurple        dkred             dkteal          emerald
     fgreen          flaqua            flblack         flblonde
     flblue_pure     flbrown           fldkblue_pure   fldkdkgrey
     fldkgreen       fldkgreen2        fldkgrey        fldkolivegreen
     fldkpurple      fldkred           flesh           fleshtransparent
     flgrey          fllime            flltbrown       flltgrey
     flltolivegreen  flmintgreen       flmustard       florange
     flpinegreen     flpurple          flred           fltan
     flwhite         flwhite1          flyellow        glass
     glassblutint    glasstransparent  gold            green
     greenskn        grey              hair            iris
     jetflame        lavendar          lcdgreen        lighttan
     lighttan2       lighttan3         lighttannew     lightyellow
     lime            lips              ltbrown         ltgrey
     meh             metal             mintgrn         muscle
     navy_blue       offwhite.cool     offwhite.warm   olivegreen
     orange          pale_green        pale_pink       pale_yellow
     peach           periwinkle        pink            pinktan
     plasma          purple            red             redbrick
     redbrown        redorange         redwood         rubber
     ruby            sand_stone        sapphire        shadow
     ship2           silver            skin            sky_blue
     smoked_glass    tan               taupe           teeth
     violet          white             yellow          yellow_green
     yellowbrt       yelloworng
   
mtllib filename

Load material properties from the named file. Materials with the same name as the predefined materials above will override the default value. Any directory path information in (filename) is ignored. The .mtl files are assumed to be in the same directory as the .obj file. If they are in a different directory, use Loader.setBasePath() (or Loader.setBaseUrl() ). The format of the material properties files are as follows:

newmtl name

Start the definition of a new named material property.

Ka float float float

Ambient color.

Kd float float float

Diffuse color.

Ks float float float

Specular color.

illum (0, 1, or 2)

0 to disable lighting, 1 for ambient & diffuse only (specular color set to black), 2 for full lighting.

Ns float

Shininess (clamped to 1.0 - 128.0).

map_Kd filename

Texture map. Supports .rgb, .rgba, .int, .inta, .sgi, and .bw files in addition to those supported by TextureLoader.


Field Summary
private static char BACKSLASH
           
private  java.lang.String basePath
           
private  java.net.URL baseUrl
           
private  Point3f[] coordArray
           
private  java.util.ArrayList coordIdxList
           
private  java.util.ArrayList coordList
           
private  java.lang.String curGroup
           
private  java.lang.String curSgroup
           
private  java.util.ArrayList curTriGroup
           
private  java.util.ArrayList curTriSgroup
           
private static int DEBUG
           
private  int flags
           
private  boolean fromUrl
           
private  java.util.HashMap groupMaterials
           
private  java.util.HashMap groups
           
private  ObjectFileMaterials materials
           
private  Vector3f[] normArray
           
private  java.util.ArrayList normIdxList
           
private  java.util.ArrayList normList
           
private  float radians
           
static int RESIZE
          Flag sent to constructor.
static int REVERSE
          Flag sent to constructor.
private  java.util.HashMap sGroups
           
private  java.util.ArrayList stripCounts
           
static int STRIPIFY
          Flag sent to contructor.
private  TexCoord2f[] texArray
           
private  java.util.ArrayList texIdxList
           
private  java.util.ArrayList texList
           
private  long time
           
static int TRIANGULATE
          Flag sent to constructor.
private  java.util.HashMap triGroups
           
private  java.util.HashMap triSgroups
           
 
Fields inherited from interface com.sun.j3d.loaders.Loader
LOAD_ALL, LOAD_BACKGROUND_NODES, LOAD_BEHAVIOR_NODES, LOAD_FOG_NODES, LOAD_LIGHT_NODES, LOAD_SOUND_NODES, LOAD_VIEW_GROUPS
 
Constructor Summary
ObjectFile()
          Default constructor.
ObjectFile(int flags)
          Constructor.
ObjectFile(int flags, float radians)
          Constructor.
 
Method Summary
private  void convertToTriangles()
          Each face is converted to triangles.
 java.lang.String getBasePath()
          Return the path where files associated with this .obj file (like material files) are located.
 java.net.URL getBaseUrl()
          Return the URL where files associated with this .obj file (like material properties files) will be found.
 int getFlags()
          Get the parameters currently defined for loading the model.
private  Point3f[] getLimits()
          getLimits Returns an array of Point3f which form a bounding box around the object.
private  int[] groupIndices(java.util.ArrayList sourceList, java.util.ArrayList group)
          Each group is a list of indices into the model's index lists, indicating the starting index of each triangle in the group.
 Scene load(java.io.Reader reader)
          The Object File is loaded from the already opened file.
 Scene load(java.lang.String filename)
          The Object File is loaded from the .obj file specified by the filename.
 Scene load(java.net.URL url)
          The object file is loaded off of the web.
(package private)  void loadMaterialFile(ObjectFileParser st)
          loadMaterialFile Both types of slashes are returned as tokens from our parser, so we go through the line token by token and keep just the last token on the line.
private  SceneBase makeScene()
           
private  int[] objectToIntArray(java.util.ArrayList inList)
           
private  Point3f[] objectToPoint3Array(java.util.ArrayList inList)
           
private  TexCoord2f[] objectToTexCoord2Array(java.util.ArrayList inList)
           
private  Vector3f[] objectToVectorArray(java.util.ArrayList inList)
           
(package private)  void readFace(ObjectFileParser st)
          readFace Adds the indices of the current face to the arrays.
(package private)  void readFile(ObjectFileParser st)
          readFile Read the model data from the file.
(package private)  void readMaterialName(ObjectFileParser st)
          readMaterialName
(package private)  void readNormal(ObjectFileParser st)
          readNormal
(package private)  void readPartName(ObjectFileParser st)
          readPartName
(package private)  void readSmoothingGroup(ObjectFileParser st)
          readSmoothingGroup
(package private)  void readTexture(ObjectFileParser st)
          readTexture
(package private)  void readVertex(ObjectFileParser st)
           
private  void resize()
          Center the object and make it (-1,-1,-1) to (1,1,1).
 void setBasePath(java.lang.String pathName)
          Set the path where files associated with this .obj file are located.
private  void setBasePathFromFilename(java.lang.String fileName)
          Takes a file name and sets the base path to the directory containing that file.
 void setBaseUrl(java.net.URL url)
          For an .obj file loaded from a URL, set the URL where associated files (like material properties files) will be found.
private  void setBaseUrlFromUrl(java.net.URL url)
           
 void setFlags(int flags)
          Set parameters for loading the model.
private  void smoothingGroupNormals()
          smoothingGroupNormals Smoothing groups are groups of faces who should be grouped together for normal calculation purposes.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEBUG

private static final int DEBUG
See Also:
Constant Field Values

RESIZE

public static final int RESIZE
Flag sent to constructor. The object's vertices will be changed so that the object is centered at (0,0,0) and the coordinate positions are all in the range of (-1,-1,-1) to (1,1,1).

See Also:
Constant Field Values

TRIANGULATE

public static final int TRIANGULATE
Flag sent to constructor. The Shape3D object will be created by using the GeometryInfo POLYGON_ARRAY primitive, causing them to be Triangulated by GeometryInfo. Use this if you suspect concave or other non-behaving polygons in your model.

See Also:
Constant Field Values

REVERSE

public static final int REVERSE
Flag sent to constructor. Use if the vertices in your .obj file were specified with clockwise winding (Java 3D wants counter-clockwise) so you see the back of the polygons and not the front. Calls GeometryInfo.reverse().

See Also:
Constant Field Values

STRIPIFY

public static final int STRIPIFY
Flag sent to contructor. After normals are generated the data will be analyzed to find triangle strips. Use this if your hardware supports accelerated rendering of strips.

See Also:
Constant Field Values

BACKSLASH

private static final char BACKSLASH
See Also:
Constant Field Values

flags

private int flags

basePath

private java.lang.String basePath

baseUrl

private java.net.URL baseUrl

fromUrl

private boolean fromUrl

radians

private float radians

coordList

private java.util.ArrayList coordList

texList

private java.util.ArrayList texList

normList

private java.util.ArrayList normList

coordIdxList

private java.util.ArrayList coordIdxList

texIdxList

private java.util.ArrayList texIdxList

normIdxList

private java.util.ArrayList normIdxList

stripCounts

private java.util.ArrayList stripCounts

groups

private java.util.HashMap groups

curGroup

private java.lang.String curGroup

sGroups

private java.util.HashMap sGroups

curSgroup

private java.lang.String curSgroup

groupMaterials

private java.util.HashMap groupMaterials

triGroups

private java.util.HashMap triGroups

curTriGroup

private java.util.ArrayList curTriGroup

triSgroups

private java.util.HashMap triSgroups

curTriSgroup

private java.util.ArrayList curTriSgroup

coordArray

private Point3f[] coordArray

normArray

private Vector3f[] normArray

texArray

private TexCoord2f[] texArray

time

private long time

materials

private ObjectFileMaterials materials
Constructor Detail

ObjectFile

public ObjectFile(int flags,
                  float radians)
Constructor.

Parameters:
flags - The constants from above or from com.sun.j3d.loaders.Loader, possibly "or'ed" (|) together.
radians - Ignored if the vn token is present in the model (user normals supplied). Otherwise, crease angle to use within smoothing groups, or within geometry groups if the s token isn't present either.

ObjectFile

public ObjectFile(int flags)
Constructor. Crease Angle set to default of 44 degrees (see NormalGenerator utility for details).

Parameters:
flags - The constants from above or from com.sun.j3d.loaders.Loader, possibly "or'ed" (|) together.

ObjectFile

public ObjectFile()
Default constructor. Crease Angle set to default of 44 degrees (see NormalGenerator utility for details). Flags set to zero (0).

Method Detail

readVertex

void readVertex(ObjectFileParser st)
          throws ParsingErrorException
Throws:
ParsingErrorException

readNormal

void readNormal(ObjectFileParser st)
          throws ParsingErrorException
readNormal

Throws:
ParsingErrorException

readTexture

void readTexture(ObjectFileParser st)
           throws ParsingErrorException
readTexture

Throws:
ParsingErrorException

readFace

void readFace(ObjectFileParser st)
        throws ParsingErrorException
readFace Adds the indices of the current face to the arrays. ViewPoint files can have up to three arrays: Vertex Positions, Texture Coordinates, and Vertex Normals. Each vertex can contain indices into all three arrays.

Throws:
ParsingErrorException

readPartName

void readPartName(ObjectFileParser st)
readPartName


readMaterialName

void readMaterialName(ObjectFileParser st)
                throws ParsingErrorException
readMaterialName

Throws:
ParsingErrorException

loadMaterialFile

void loadMaterialFile(ObjectFileParser st)
                throws ParsingErrorException
loadMaterialFile Both types of slashes are returned as tokens from our parser, so we go through the line token by token and keep just the last token on the line. This should be the filename without any directory info.

Throws:
ParsingErrorException

readSmoothingGroup

void readSmoothingGroup(ObjectFileParser st)
                  throws ParsingErrorException
readSmoothingGroup

Throws:
ParsingErrorException

readFile

void readFile(ObjectFileParser st)
        throws ParsingErrorException
readFile Read the model data from the file.

Throws:
ParsingErrorException

setBasePathFromFilename

private void setBasePathFromFilename(java.lang.String fileName)
Takes a file name and sets the base path to the directory containing that file.


load

public Scene load(java.lang.String filename)
           throws java.io.FileNotFoundException,
                  IncorrectFormatException,
                  ParsingErrorException
The Object File is loaded from the .obj file specified by the filename. To attach the model to your scene, call getSceneGroup() on the Scene object passed back, and attach the returned BranchGroup to your scene graph. For an example, see j3d-examples/ObjLoad/ObjLoad.java.

Specified by:
load in interface Loader
Throws:
java.io.FileNotFoundException
IncorrectFormatException
ParsingErrorException

setBaseUrlFromUrl

private void setBaseUrlFromUrl(java.net.URL url)
                        throws java.io.FileNotFoundException
Throws:
java.io.FileNotFoundException

load

public Scene load(java.net.URL url)
           throws java.io.FileNotFoundException,
                  IncorrectFormatException,
                  ParsingErrorException
The object file is loaded off of the web. To attach the model to your scene, call getSceneGroup() on the Scene object passed back, and attach the returned BranchGroup to your scene graph. For an example, see j3d-examples/ObjLoad/ObjLoad.java.

Specified by:
load in interface Loader
Throws:
java.io.FileNotFoundException
IncorrectFormatException
ParsingErrorException

getLimits

private Point3f[] getLimits()
getLimits Returns an array of Point3f which form a bounding box around the object. Element 0 is the low value, element 1 is the high value. See normalize() below for an example of how to use this method.


resize

private void resize()
Center the object and make it (-1,-1,-1) to (1,1,1).


objectToIntArray

private int[] objectToIntArray(java.util.ArrayList inList)

objectToPoint3Array

private Point3f[] objectToPoint3Array(java.util.ArrayList inList)

objectToTexCoord2Array

private TexCoord2f[] objectToTexCoord2Array(java.util.ArrayList inList)

objectToVectorArray

private Vector3f[] objectToVectorArray(java.util.ArrayList inList)

groupIndices

private int[] groupIndices(java.util.ArrayList sourceList,
                           java.util.ArrayList group)
Each group is a list of indices into the model's index lists, indicating the starting index of each triangle in the group. This method converts those data structures into an integer array to use with GeometryInfo.


smoothingGroupNormals

private void smoothingGroupNormals()
smoothingGroupNormals Smoothing groups are groups of faces who should be grouped together for normal calculation purposes. The faces are put into a GeometryInfo object and normals are calculated with a 180 degree creaseAngle (no creases) or whatever the user has specified. The normals are then copied out of the GeometryInfo and back into ObjectFile data structures.


convertToTriangles

private void convertToTriangles()
Each face is converted to triangles. As each face is converted, we look up which geometry group and smoothing group the face belongs to. The generated triangles are added to each of these groups, which are also being converted to a new triangle based format. We need to convert to triangles before normals are generated because of smoothing groups. The faces in a smoothing group are copied into a GeometryInfo to have their normals calculated, and then the normals are copied out of the GeometryInfo using GeometryInfo.getNormalIndices. As part of Normal generation, the geometry gets converted to Triangles. So we need to convert to triangles *before* Normal generation so that the normals we read out of the GeometryInfo match up with the vertex data that we sent in. If we sent in TRIANGLE_FAN data, the normal generator would convert it to triangles and we'd read out normals formatted for Triangle data. This would not match up with our original Fan data, so we couldn't tell which normals go with which vertices.


makeScene

private SceneBase makeScene()

load

public Scene load(java.io.Reader reader)
           throws java.io.FileNotFoundException,
                  IncorrectFormatException,
                  ParsingErrorException
The Object File is loaded from the already opened file. To attach the model to your scene, call getSceneGroup() on the Scene object passed back, and attach the returned BranchGroup to your scene graph. For an example, see j3d-examples/ObjLoad/ObjLoad.java.

Specified by:
load in interface Loader
Throws:
java.io.FileNotFoundException
IncorrectFormatException
ParsingErrorException

setBaseUrl

public void setBaseUrl(java.net.URL url)
For an .obj file loaded from a URL, set the URL where associated files (like material properties files) will be found. Only needs to be called to set it to a different URL from that containing the .obj file.

Specified by:
setBaseUrl in interface Loader

getBaseUrl

public java.net.URL getBaseUrl()
Return the URL where files associated with this .obj file (like material properties files) will be found.

Specified by:
getBaseUrl in interface Loader

setBasePath

public void setBasePath(java.lang.String pathName)
Set the path where files associated with this .obj file are located. Only needs to be called to set it to a different directory from that containing the .obj file.

Specified by:
setBasePath in interface Loader

getBasePath

public java.lang.String getBasePath()
Return the path where files associated with this .obj file (like material files) are located.

Specified by:
getBasePath in interface Loader

setFlags

public void setFlags(int flags)
Set parameters for loading the model. Flags defined in Loader.java are ignored by the ObjectFile Loader because the .obj file format doesn't include lights, fog, background, behaviors, views, or sounds. However, several flags are defined specifically for use with the ObjectFile Loader (see above).

Specified by:
setFlags in interface Loader

getFlags

public int getFlags()
Get the parameters currently defined for loading the model. Flags defined in Loader.java are ignored by the ObjectFile Loader because the .obj file format doesn't include lights, fog, background, behaviors, views, or sounds. However, several flags are defined specifically for use with the ObjectFile Loader (see above).

Specified by:
getFlags in interface Loader


Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. Use is subject to license terms.