instantreality 1.0

Direct scene manipulations with Java

Keywords:
script, java, dynamic
Author(s): Michael Zoellner
Date: 2007-06-21

Summary: This tutorial shows you how to use Java in script nodes for making your scene dynamic.

Introduction

Java is an alternative language next to Javascript for creating dynamic X3D scenes. It's main benefits compared to Javascript are the better performance and the higher flexibility of development. With Java script nodes it is possible to expand X3D's and instantplayer's capabilities by using Java functions and libraries to create custom interfaces and features.

Setting up the Scene and the Script

Java script nodes are exactly looking like Javascript nodes in X3D. Only the "url" field is linking to a .class file instead of a .js file.

Code: The Script Node

<Script DEF='javanode' directOutput='true' url='InstantJava.class'>
	<field name='set_touchtime' type='SFTime' accessType='inputOnly'/>
	<field name='get_newcolor' type='SFColor' accessType='outputOnly'/>
</Script>
        

The two fields of the script node are defining the incoming and outgoing values. set_touchtime will route an SFTime value into Java. get_newcolor's value will get filled by Java and routed on a Material node in the Scene.

Setting up a Java Class

Java Classes extend vrml.node.Script. Just like JavaScript Java Scripts have the common initialize(), shutdown() and processEvent() functions. This is an example how a basic Java Class looks like:

Code: Basic Java Class

import vrml.*;
import vrml.field.*;
import vrml.node.*;
import vrml.Event;

public class InstantJava extends Script
{	
	public void initialize()
	{
		System.out.println("initializing java..");
	}
	
	public void processEvent( Event e )
	{
	
	}
	
	public void shutdown()
	{
		System.out.println("bye!");
	}
}
		

Getting Values from the Scene

Incoming events are processed in the processEvent() function. In this example the touchTime field of a TouchSensor is routed on the script and catched by an if condition. The event has to be casted into the right type.

Code: processEvent

public void processEvent( Event e )
{
	if (e.getName().equals("set_touchtime"))
	{
		ConstSFTime time = (ConstSFTime)e.getValue();
		System.out.println( "touched at " + time.getValue());
	}
}
		

Writing back Values to the Scene

In order to send values to the scene we have to get the eventOut in the initialize() function and cast it into the right type. With the function setValue(value) we are sending the values to the script node's field in the scene.

Code: processEvent

public SFColor get_newcolor;
	
public void initialize()
{
	get_newcolor = (SFColor)getEventOut("get_newcolor");
	get_newcolor.setValue(1, 0.5, 0);
}
		
Image: random color box
Files: