BS Contact J : Java-EAI : Manipulating fields

Here's a little example to demonstrate Field manipulation: We have a simple sphere whose material node we want to manipulate. The diffuseColor of the sphere is to change every 1/3 second.

First, get an instance of the BS Contact J applet. Then connect to the material node of the sphere (which has to be DEFed already), and to its diffuseColor field. Then place a call in the main method of the applet which changes the value of the sphere's diffuseColor field every 1/3 second.

Sorry, your browser doesn't support Java.

 

 

 

view complete source

 

The start method could look like this:

public void start(){

// connect to blaxxun3d
while (browser==null) {
browser=blaxxun3d.getBrowser("browser");
hesitate();
}
System.out.println("Got browser.");

// wait till everything is loaded
while (browser.getWorld()==null) {
hesitate();
}
System.out.println("World loaded.");

// connect to nodes
try {
sphereMaterial=browser.getNode("sphereMaterial");
diffuseCol=sphereMaterial.getField("diffuseColor");
}
catch (X3DException notfound) {
System.out.println("Can't find nodes. Aborting.");
stop();
}

System.out.println("Got nodes.");

// main loop
float[] col=new float[3];
while (true) {
// get current color values
col=diffuseCol.getValueFloatArray(0,-1);

// calculate new values
for (int i=0;i<3;i++) col[i]=(float)Math.random();

// sync renderer
browser.beginUpdate();

// send them to the sphere
diffuseCol.setValueFloatArray(0,-1,col);

// continue rendering
browser.endUpdate();

// wait some time
hesitate();
}
}

The most important line of code here is the one that sets the diffuseColor field:

diffuseCol.setValueFloatArray(0,-1,col)

The first two arguments contain the start and stop indices of the array to be filled; 0 means that the array should be filled starting at the first index, and -1 means that all of the elements in col should be put in ascending order into the diffuseCol value array. Afterwards, col finally contains all new values to be set. In this particular example,
diffuseCol.setValueFloatArray(0,2,col)
would lead to the same result since the loop will be repeated three times.

All other fields can be manipulated in the same way; only the method differs: use


nodeArrayField.setValue(startIndex, endIndex, sourceArrayOfNodes)


to manipulate a nodeArray field, for example.