You can define new node types for SceneJS via plugins. This extension mechanism lets you
create your own higher-level scene components that just slot straight into your scene graphs as nodes which
you can create and update as usual via the API, in the same way as for the core node types.
In this article I’ll show you how to define a new node type and how to use it within a scene graph. The examples page also
has several examples that show how to define and use node types.
Creating a new node type
You provide a class definition for a new node type as a plugin, which SceneJS will automatically load on-demand
the first time you try to instantiate it within your scene graph.
Our trivial example plugin shows how these custom node types are often a kind of actor/facade that creates additional
scene nodes within its subgraph, while providing nice abstract accessor methods which update the state of those nodes
in some way:
Using the new node type
Let’s assume that you’ve downloaded the SceneJS plugins bundle as described in the Quick Start tutorial,
which means that we
We have the SceneJS library, the SceneJS plugins bundle, and an example HTML page which renders our teapot.
that you’ve pointed SceneJS at where you unzipped them:
We’ll also assume that our new node type is saved as color.js within the directory structure below:
Now that SceneJS will be able to load the plugin listed above, you can create a scene that includes an instance of it (along with a teapot, which comes from another plugin):
As mentioned, when SceneJS parses that instance of our demos/color node type, it’s going to dynamically load our plugin script,
which will install the plugin type, which SceneJS will then instantiate to create the node.
See how in the scene we are providing a child geometry for our node. Within its constructor (the init method in
the node type definition plugin above) the custom node type is responsible for inserting specified child node(s) into
the subgraph it creates under itself. That’s because only the node type knows exactly where the child nodes should be located within its subgraph.
Now lets get the node instance and use one of its accessor methods to periodically switch its color property.
Note that since our node originates from a plugin that will be loaded on-demand, we need to get the node asynchronously
using a callback (instead of synchronously, like we can with instances of core node types):
See that setColor method, which is defined by our node type?
Sometimes our nodes will run tasks that we’ll want to monitor progress on.
Here’s a defintion for that growing teapot node again, this time using taskStarted, taskFinished
and taskFailed methods to notify SceneJS of its progress while it grows. SceneJS can relay those
notifications to us as a count of tasks in progress, as we’ll see further down.
Now create a scene that contains an instance of our node type:
Periodically query and log scene busyness status to the console: