VRML : DEF and USE

One useful feature of the VRML is that you can DEFine a particular object or function and then reUSE the exact same method at any point later in the file. For example, you may want to define a Carbon atom, so that instead of having to type out


Sphere {
	radius 0.4
}
time and time again, you just have to type

USE Carbon
each time you want to draw the atom. You can also do the same with materials, lights, so this is extremely powerful.


DEFining

DEF defines a node for use later on, but it also executes the statements in that node. This technique is sometimes called "instancing", because more than one instance if a node may be used. In this respect, DEF creates a single instance of the node, and each time you USE the node, another instance is created. The DEF syntax is simple :


DEF given_name node_name {
	#the parameters come here
}
where given_name is the name the author wants to give to the instance (e.g. "carbon_atom"), and node_name is the type of node (e.g. "Cube"). The given_name must NOT contain spaces, control characters, either single or double quotes, backslashes, curly braces, the plus "+" character, or the period "." character. In addition, the name must not begin with a digit.

Once an object has been DEF'd, it can be USEd anywhere below in the file. DEF is not affected by separator nodes, and if an object is re-DEF'd, then the old object is completely replaced, regardless of separator nodes. You can't use objects that are DEF'd in other files. The DEF'd object is lost once the end of the file is reached.


USEing

USE creates a new instance of a previously DEF'd object. The syntax is again very simple:


USE given_name
There is no limit to the number of instances of a node.


Examples of DEF and USE

Example 1: create three spheres at x = 0, x = 3, and x = 6.


Translation { translation -3 0 0 }
DEF move Translation { translation 3 0 0 }

DEF mySphere Sphere { radius 0.6 }

USE move
USE mySphere
USE move
USE mySphere
Example 2: Prove that Separator nodes are ignored.


DEF myCube Cube{
	width 4
	height 4
	depth 4
}

Translation { translation 0 10 0 }

Separator {
	DEF myCube Sphere{ radius 0.5 }
}

Translation { translation 5 -5 0 }

USE myCube   #<<<<---A Sphere, not a Cube will be drawn here.


Next Topic (Miscellaneous)
Previous Topic (Transformations)
Back to the VRML Reference
Back to the Main Page

©Tom Thurston, 1997
Please feel free to use and redistribute this NONcommercially!