9. Scripting

There are a lot of actions that are too complex for sensors and interpolators. You can write program scripts in Java or JavaScript that can accept event inputs, generate event outputs and read and write (exposed)fields.

Show the lightswitching with JavaScript example
#VRML V2.0 utf8
#PointLight example

Group {
children[
	DEF switchinglight PointLight { 
		location 	-1.0 0.0 1.0#the light is 1 units left on the X axis 
		color       0 1 0 	#the color is green
		on 		FALSE
			}

	Transform {
	translation -2 0 0 
	children [
		DEF ball Shape{
			appearance Appearance{
				material Material { }
					}
			geometry Sphere {
				radius  0.5  #radius in units  				}
				}
			}
		]
	}
	Transform {
	translation 2 0 0
	children [ USE ball ]
	}
	
	DEF Clicked TouchSensor {}
	]
}

Transform {
	translation 0 2 0
  	   children   [ USE 3balls ]
 	   }

Transform {
	translation 0 -2 0
  	   children   [ USE 3balls ]
 	   }
 ]
}

DEF switcher Script {
	eventIn SFBool turnOn
	eventOut SFBool lightOn
	url "javascript:
		function turnOn(val){
			if(!val) {
				if(lightOn) {
					lightOn = 0;
					}
				else {
					lightOn = 1;
					}
				}
			}"
}

ROUTE Clicked.isActive TO switcher.turnOn
ROUTE switcher.lightOn TO switchinglight.on
Show the animated texture with JavaScript example
#VRML V2.0 utf8
#Animated Texture with javascript

Viewpoint {
  position   0 0 5
  fieldOfView      0.785
}
Group {
  children   [
    DEF Square Shape {
      appearance   Appearance {
        material   Material {
          ambientIntensity      0.25
          diffuseColor    0 1 0
        }
        texture    ImageTexture {
          url      "../images/smalltexture.gif"
        }
        textureTransform  DEF Trans TextureTransform {
          translation     0 0
        }
      }
      geometry     IndexedFaceSet {
        coord      Coordinate {
          point    [ -1 1 0, -1 -1 0, 1 1 0, 1 -1 0 ]
        }
        coordIndex [ 0, 1, 3, 2, -1 ]
        texCoord   TextureCoordinate {
          point    [ 0 1, 0 0, 1 1, 1 0 ]
        }
        texCoordIndex     [ 0, 1, 3, 2, -1 ]
      }
    }
    DEF Time TimeSensor {
      cycleInterval	1.5
      loop   TRUE
      startTime    0
    }
    DEF XInterp ScalarInterpolator {
      key    [ 0, 1 ]
      keyValue     [ 0, 1 ]
    }

    DEF Move_it Script {
      eventOut     SFVec2f      vec
      eventIn      SFFloat      xIn
      field        SFFloat      xBuf  0
      url   "javascript:
      function xIn(value) {
        xBuf = value;
        vec[0] = xBuf;
        vec[1] = yBuf;
      }"
    }
  ]
}
ROUTE Time.fraction_changed TO XInterp.set_fraction
ROUTE XInterp.value_changed TO Move_it.xIn
ROUTE Move_it.vec TO Trans.set_translation
Generating VRML on the client side with JavaScript example