|
This Java tip illustrates the use of light scope groups in Java 3D scenes.
Three DirectionalLight nodes are added to illuminate a scene, selecting
one of them to use at a time. Each light has a different scope
group list, and thus illuminates different parts of the scene.
import java.applet.Applet;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.CheckboxMenuItem;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.Enumeration;
import java.util.EventListener;
import javax.media.j3d.AmbientLight;
import javax.media.j3d.Appearance;
import javax.media.j3d.Behavior;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Group;
import javax.media.j3d.Light;
import javax.media.j3d.Material;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.WakeupCriterion;
import javax.media.j3d.WakeupOnAWTEvent;
import javax.media.j3d.WakeupOnElapsedFrames;
import javax.media.j3d.WakeupOr;
import javax.vecmath.Color3f;
import javax.vecmath.Matrix4d;
import javax.vecmath.Point3d;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3d;
import javax.vecmath.Vector3f;
import com.sun.j3d.utils.geometry.Primitive;
import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.universe.PlatformGeometry;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.Viewer;
import com.sun.j3d.utils.universe.ViewingPlatform;
public class ExLightScope extends Java3DFrame {
//--------------------------------------------------------------
// SCENE CONTENT
//--------------------------------------------------------------
//
// Nodes (updated via menu)
//
private DirectionalLight light1 = null;
private DirectionalLight light2 = null;
private DirectionalLight light3 = null;
private Group content1 = null;
private Group content2 = null;
//
// Build scene
//
public Group buildScene() {
// Turn off the example headlight
setHeadlightEnable(false);
// Build the scene group
Group scene = new Group();
// Build foreground geometry into two groups. We'll
// create three directional lights below, one each with
// scope to cover the first geometry group only, the
// second geometry group only, or both geometry groups.
content1 = new SphereGroup(0.25f, // radius of spheres
1.5f, // x spacing
0.75f, // y spacing
3, // number of spheres in X
5, // number of spheres in Y
null); // appearance
scene.addChild(content1);
content2 = new SphereGroup(0.25f, // radius of spheres
1.5f, // x spacing
0.75f, // y spacing
2, // number of spheres in X
5, // number of spheres in Y
null); // appearance
scene.addChild(content2);
// BEGIN EXAMPLE TOPIC
// Create influencing bounds
BoundingSphere worldBounds = new BoundingSphere(new Point3d(0.0, 0.0,
0.0), // Center
1000.0); // Extent
// Add three directional lights whose scopes are set
// to cover one, the other, or both of the shape groups
// above. Also set the lights' color and aim direction.
// Light #1 with content1 scope
light1 = new DirectionalLight();
light1.setEnable(light1OnOff);
light1.setColor(Red);
light1.setDirection(new Vector3f(1.0f, 0.0f, -1.0f));
light1.setInfluencingBounds(worldBounds);
light1.addScope(content1);
light1.setCapability(Light.ALLOW_STATE_WRITE);
scene.addChild(light1);
// Light #2 with content2 scope
light2 = new DirectionalLight();
light2.setEnable(light2OnOff);
light2.setColor(Blue);
light2.setDirection(new Vector3f(1.0f, 0.0f, -1.0f));
light2.setInfluencingBounds(worldBounds);
light2.addScope(content2);
light2.setCapability(Light.ALLOW_STATE_WRITE);
scene.addChild(light2);
// Light #3 with universal scope (the default)
light3 = new DirectionalLight();
light3.setEnable(light3OnOff);
light3.setColor(White);
light3.setDirection(new Vector3f(1.0f, 0.0f, -1.0f));
light3.setInfluencingBounds(worldBounds);
light3.setCapability(Light.ALLOW_STATE_WRITE);
scene.addChild(light3);
// Add an ambient light to dimly illuminate the rest of
// the shapes in the scene to help illustrate that the
// directional lights are being scoped... otherwise it looks
// like we're just removing shapes from the scene
AmbientLight ambient = new AmbientLight();
ambient.setEnable(true);
ambient.setColor(White);
ambient.setInfluencingBounds(worldBounds);
scene.addChild(ambient);
// END EXAMPLE TOPIC
return scene;
}
//--------------------------------------------------------------
// USER INTERFACE
//--------------------------------------------------------------
//
// Main
//
public static void main(String[] args) {
ExLightScope ex = new ExLightScope();
ex.initialize(args);
ex.buildUniverse();
ex.showFrame();
}
// Menu choices
private boolean light1OnOff = true;
private CheckboxMenuItem light1OnOffMenu;
private boolean light2OnOff = true;
private CheckboxMenuItem light2OnOffMenu;
private boolean light3OnOff = false;
private CheckboxMenuItem light3OnOffMenu;
//
// Initialize the GUI (application and applet)
//
public void initialize(String[] args) {
// Initialize the window, menubar, etc.
super.initialize(args);
exampleFrame.setTitle("Java 3D Light Scoping Example");
//
// Add a menubar menu to change node parameters
// Use bounding leaf
//
Menu m = new Menu("DirectionalLights");
light1OnOffMenu = new CheckboxMenuItem(
"Red light with sphere set 1 scope", light1OnOff);
light1OnOffMenu.addItemListener(this);
m.add(light1OnOffMenu);
light2OnOffMenu = new CheckboxMenuItem(
"Blue light with sphere set 2 scope", light2OnOff);
light2OnOffMenu.addItemListener(this);
m.add(light2OnOffMenu);
light3OnOffMenu = new CheckboxMenuItem(
"White light with universal scope", light3OnOff);
light3OnOffMenu.addItemListener(this);
m.add(light3OnOffMenu);
exampleMenuBar.add(m);
}
//
// Handle checkboxes and menu choices
//
public void itemStateChanged(ItemEvent event) {
Object src = event.getSource();
if (src == light1OnOffMenu) {
light1OnOff = light1OnOffMenu.getState();
light1.setEnable(light1OnOff);
return;
}
if (src == light2OnOffMenu) {
light2OnOff = light2OnOffMenu.getState();
light2.setEnable(light2OnOff);
return;
}
if (src == light3OnOffMenu) {
light3OnOff = light3OnOffMenu.getState();
light3.setEnable(light3OnOff);
return;
}
// Handle all other checkboxes
super.itemStateChanged(event);
}
}
//
//CLASS
//SphereGroup - create a group of spheres on the XY plane
//
//DESCRIPTION
//An XY grid of spheres is created. The number of spheres in X and Y,
//the spacing in X and Y, the sphere radius, and the appearance can
//all be set.
//
//This grid of spheres is used by several of the examples as a generic
//bit of foreground geometry.
//
//SEE ALSO
//Ex*Light
//ExBackground*
//
//AUTHOR
//David R. Nadeau / San Diego Supercomputer Center
//
class SphereGroup extends Group {
// Constructors
public SphereGroup() {
// radius x,y spacing x,y count appearance
this(0.25f, 0.75f, 0.75f, 5, 5, null);
}
public SphereGroup(Appearance app) {
// radius x,y spacing x,y count appearance
this(0.25f, 0.75f, 0.75f, 5, 5, app);
}
public SphereGroup(float radius, float xSpacing, float ySpacing,
int xCount, int yCount) {
this(radius, xSpacing, ySpacing, xCount, yCount, null);
}
public SphereGroup(float radius, float xSpacing, float ySpacing,
int xCount, int yCount, Appearance app) {
if (app == null) {
app = new Appearance();
Material material = new Material();
material.setDiffuseColor(new Color3f(0.8f, 0.8f, 0.8f));
material.setSpecularColor(new Color3f(0.0f, 0.0f, 0.0f));
material.setShininess(0.0f);
app.setMaterial(material);
}
double xStart = -xSpacing * (double) (xCount - 1) / 2.0;
double yStart = -ySpacing * (double) (yCount - 1) / 2.0;
Sphere sphere = null;
TransformGroup trans = null;
Transform3D t3d = new Transform3D();
Vector3d vec = new Vector3d();
double x, y = yStart, z = 0.0;
for (int i = 0; i < yCount; i++) {
x = xStart;
for (int j = 0; j < xCount; j++) {
vec.set(x, y, z);
t3d.setTranslation(vec);
trans = new TransformGroup(t3d);
addChild(trans);
sphere = new Sphere(radius, // sphere radius
Primitive.GENERATE_NORMALS, // generate normals
16, // 16 divisions radially
app); // it's appearance
trans.addChild(sphere);
x += xSpacing;
}
y += ySpacing;
}
}
}
/**
* The Example class is a base class extended by example applications. The class
* provides basic features to create a top-level frame, add a menubar and
* Canvas3D, build the universe, set up "examine" and "walk" style navigation
* behaviors, and provide hooks so that subclasses can add 3D content to the
* example's universe.
* <P>
* Using this Example class simplifies the construction of example applications,
* enabling the author to focus upon 3D content and not the busywork of creating
* windows, menus, and universes.
*
* @version 1.0, 98/04/16
* @author David R. Nadeau, San Diego Supercomputer Center
*/
class Java3DFrame extends Applet implements WindowListener, ActionListener,
ItemListener, CheckboxMenuListener {
// Navigation types
public final static int Walk = 0;
public final static int Examine = 1;
// Should the scene be compiled?
private boolean shouldCompile = true;
// GUI objects for our subclasses
protected Java3DFrame example = null;
protected Frame exampleFrame = null;
protected MenuBar exampleMenuBar = null;
protected Canvas3D exampleCanvas = null;
protected TransformGroup exampleViewTransform = null;
protected TransformGroup exampleSceneTransform = null;
protected boolean debug = false;
// Private GUI objects and state
private boolean headlightOnOff = true;
private int navigationType = Examine;
private CheckboxMenuItem headlightMenuItem = null;
private CheckboxMenuItem walkMenuItem = null;
private CheckboxMenuItem examineMenuItem = null;
private DirectionalLight headlight = null;
private ExamineViewerBehavior examineBehavior = null;
private WalkViewerBehavior walkBehavior = null;
//--------------------------------------------------------------
// ADMINISTRATION
//--------------------------------------------------------------
/**
* The main program entry point when invoked as an application. Each example
* application that extends this class must define their own main.
*
* @param args
* a String array of command-line arguments
*/
public static void main(String[] args) {
Java3DFrame ex = new Java3DFrame();
ex.initialize(args);
ex.buildUniverse();
ex.showFrame();
}
/**
* Constructs a new Example object.
*
* @return a new Example that draws no 3D content
*/
public Java3DFrame() {
// Do nothing
}
/**
* Initializes the application when invoked as an applet.
*/
public void init() {
// Collect properties into String array
String[] args = new String[2];
// NOTE: to be done still...
this.initialize(args);
this.buildUniverse();
this.showFrame();
// NOTE: add something to the browser page?
}
/**
* Initializes the Example by parsing command-line arguments, building an
* AWT Frame, constructing a menubar, and creating the 3D canvas.
*
* @param args
* a String array of command-line arguments
*/
protected void initialize(String[] args) {
example = this;
// Parse incoming arguments
parseArgs(args);
// Build the frame
if (debug)
System.err.println("Building GUI...");
exampleFrame = new Frame();
exampleFrame.setSize(640, 480);
exampleFrame.setTitle("Java 3D Example");
exampleFrame.setLayout(new BorderLayout());
// Set up a close behavior
exampleFrame.addWindowListener(this);
// Create a canvas
exampleCanvas = new Canvas3D(null);
exampleCanvas.setSize(630, 460);
exampleFrame.add("Center", exampleCanvas);
// Build the menubar
exampleMenuBar = this.buildMenuBar();
exampleFrame.setMenuBar(exampleMenuBar);
// Pack
exampleFrame.pack();
exampleFrame.validate();
// exampleFrame.setVisible( true );
}
/**
* Parses incoming command-line arguments. Applications that subclass this
* class may override this method to support their own command-line
* arguments.
*
* @param args
* a String array of command-line arguments
*/
protected void parseArgs(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-d"))
debug = true;
}
}
//--------------------------------------------------------------
// SCENE CONTENT
//--------------------------------------------------------------
/**
* Builds the 3D universe by constructing a virtual universe (via
* SimpleUniverse), a view platform (via SimpleUniverse), and a view (via
* SimpleUniverse). A headlight is added and a set of behaviors initialized
* to handle navigation types.
*/
protected void buildUniverse() {
//
// Create a SimpleUniverse object, which builds:
//
// - a Locale using the given hi-res coordinate origin
//
// - a ViewingPlatform which in turn builds:
// - a MultiTransformGroup with which to move the
// the ViewPlatform about
//
// - a ViewPlatform to hold the view
//
// - a BranchGroup to hold avatar geometry (if any)
//
// - a BranchGroup to hold view platform
// geometry (if any)
//
// - a Viewer which in turn builds:
// - a PhysicalBody which characterizes the user's
// viewing preferences and abilities
//
// - a PhysicalEnvironment which characterizes the
// user's rendering hardware and software
//
// - a JavaSoundMixer which initializes sound
// support within the 3D environment
//
// - a View which renders the scene into a Canvas3D
//
// All of these actions could be done explicitly, but
// using the SimpleUniverse utilities simplifies the code.
//
if (debug)
System.err.println("Building scene graph...");
SimpleUniverse universe = new SimpleUniverse(null, // Hi-res coordinate
// for the origin -
// use default
1, // Number of transforms in MultiTransformGroup
exampleCanvas, // Canvas3D into which to draw
null); // URL for user configuration file - use defaults
//
// Get the viewer and create an audio device so that
// sound will be enabled in this content.
//
Viewer viewer = universe.getViewer();
viewer.createAudioDevice();
//
// Get the viewing platform created by SimpleUniverse.
// From that platform, get the inner-most TransformGroup
// in the MultiTransformGroup. That inner-most group
// contains the ViewPlatform. It is this inner-most
// TransformGroup we need in order to:
//
// - add a "headlight" that always aims forward from
// the viewer
//
// - change the viewing direction in a "walk" style
//
// The inner-most TransformGroup's transform will be
// changed by the walk behavior (when enabled).
//
ViewingPlatform viewingPlatform = universe.getViewingPlatform();
exampleViewTransform = viewingPlatform.getViewPlatformTransform();
//
// Create a "headlight" as a forward-facing directional light.
// Set the light's bounds to huge. Since we want the light
// on the viewer's "head", we need the light within the
// TransformGroup containing the ViewPlatform. The
// ViewingPlatform class creates a handy hook to do this
// called "platform geometry". The PlatformGeometry class is
// subclassed off of BranchGroup, and is intended to contain
// a description of the 3D platform itself... PLUS a headlight!
// So, to add the headlight, create a new PlatformGeometry group,
// add the light to it, then add that platform geometry to the
// ViewingPlatform.
//
BoundingSphere allBounds = new BoundingSphere(
new Point3d(0.0, 0.0, 0.0), 100000.0);
PlatformGeometry pg = new PlatformGeometry();
headlight = new DirectionalLight();
headlight.setColor(White);
headlight.setDirection(new Vector3f(0.0f, 0.0f, -1.0f));
headlight.setInfluencingBounds(allBounds);
headlight.setCapability(Light.ALLOW_STATE_WRITE);
pg.addChild(headlight);
viewingPlatform.setPlatformGeometry(pg);
//
// Create the 3D content BranchGroup, containing:
//
// - a TransformGroup who's transform the examine behavior
// will change (when enabled).
//
// - 3D geometry to view
//
// Build the scene root
BranchGroup sceneRoot = new BranchGroup();
// Build a transform that we can modify
exampleSceneTransform = new TransformGroup();
exampleSceneTransform
.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
exampleSceneTransform
.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
exampleSceneTransform.setCapability(Group.ALLOW_CHILDREN_EXTEND);
//
// Build the scene, add it to the transform, and add
// the transform to the scene root
//
if (debug)
System.err.println(" scene...");
Group scene = this.buildScene();
exampleSceneTransform.addChild(scene);
sceneRoot.addChild(exampleSceneTransform);
//
// Create a pair of behaviors to implement two navigation
// types:
//
// - "examine": a style where mouse drags rotate about
// the scene's origin as if it is an object under
// examination. This is similar to the "Examine"
// navigation type used by VRML browsers.
//
// - "walk": a style where mouse drags rotate about
// the viewer's center as if the viewer is turning
// about to look at a scene they are in. This is
// similar to the "Walk" navigation type used by
// VRML browsers.
//
// Aim the examine behavior at the scene's TransformGroup
// and add the behavior to the scene root.
//
// Aim the walk behavior at the viewing platform's
// TransformGroup and add the behavior to the scene root.
//
// Enable one (and only one!) of the two behaviors
// depending upon the current navigation type.
//
examineBehavior = new ExamineViewerBehavior(exampleSceneTransform, // Transform
// gorup
// to
// modify
exampleFrame); // Parent frame for cusor changes
examineBehavior.setSchedulingBounds(allBounds);
sceneRoot.addChild(examineBehavior);
walkBehavior = new WalkViewerBehavior(exampleViewTransform, // Transform
// group to
// modify
exampleFrame); // Parent frame for cusor changes
walkBehavior.setSchedulingBounds(allBounds);
sceneRoot.addChild(walkBehavior);
if (navigationType == Walk) {
examineBehavior.setEnable(false);
walkBehavior.setEnable(true);
} else {
examineBehavior.setEnable(true);
walkBehavior.setEnable(false);
}
//
// Compile the scene branch group and add it to the
// SimpleUniverse.
//
if (shouldCompile)
sceneRoot.compile();
universe.addBranchGraph(sceneRoot);
reset();
}
/**
* Builds the scene. Example application subclasses should replace this
* method with their own method to build 3D content.
*
* @return a Group containing 3D content to display
*/
public Group buildScene() {
// Build the scene group containing nothing
Group scene = new Group();
return scene;
}
//--------------------------------------------------------------
// SET/GET METHODS
//--------------------------------------------------------------
/**
* Sets the headlight on/off state. The headlight faces forward in the
* direction the viewer is facing. Example applications that add their own
* lights will typically turn the headlight off. A standard menu item
* enables the headlight to be turned on and off via user control.
*
* @param onOff
* a boolean turning the light on (true) or off (false)
*/
public void setHeadlightEnable(boolean onOff) {
headlightOnOff = onOff;
if (headlight != null)
headlight.setEnable(headlightOnOff);
if (headlightMenuItem != null)
headlightMenuItem.setState(headlightOnOff);
}
/**
| |