8.7. Searching for a Node

SoSearchAction( C++ | Java | .NET ) searches through the scene graph for paths to specific nodes, types of nodes, or nodes with a given name. First, you initialize the action. Then, you specify the node, node type, or name to search for (or a combination of these elements). If you specify a node type, you can also specify whether to search for an exact type match, or to search for subclasses of the specified type as well.

First, specify what you are searching for, whether you want to find all matches, and how to traverse the scene graph.

Rather than searching for a specific node, you may want to search for a type of node (see Chapter 3, Nodes and Groups). When searching for a node type, you then have the choice of searching for all nodes of a particular type, or for derivations of the given type (the default). The syntax for setType() is as follows:

setType (SoType t , int derivedIsOk = TRUE);

SoSearchAction( C++ | Java | .NET ) is applied in the same manner as any other action.

To obtain the results of the search, use one of the following methods:

See the Open Inventor C++ Reference Manual for a complete description of all methods available for SoSearchAction( C++ | Java | .NET ).

The following example searches a scene graph for any node derived from SoLight( C++ | Java | .NET ). If it does not find one, it creates and adds an SoDirectionalLight( C++ | Java | .NET ). This example searches for only the first match by calling setInterest- (SoSearchAction::FIRST).


C++
SoSearchAction mySearchAction;

// Look for first existing light derived from class SoLight
mySearchAction.setType(SoLight::getClassTypeId());
mySearchAction.setInterest(SoSearchAction::FIRST);
    
mySearchAction.apply(root);
if (mySearchAction.getPath() == NULL) { // No lights found

   // Add a default directional light to the scene
   SoDirectionalLight *myLight = new SoDirectionalLight;
   root->insertChild(myLight, 0);
}
  

.NET
SoSearchAction mySearchAction = new SoSearchAction();

// Look for first existing light derived from class SoLight
mySearchAction.SetType(Type.GetType("SoLight"));
mySearchAction.SetInterest(SoSearchAction.Interests.FIRST);
    
mySearchAction.Apply(root);
if (mySearchAction.GetPath() == null) // No lights found
{
   // Add a default directional light to the scene
   SoDirectionalLight myLight = new SoDirectionalLight();
   root.InsertChild(myLight, 0);
}

Java
SoSearchAction mySearchAction = new SoSearchAction();

// Look for first existing light derived from class SoLight
mySearchAction.setNodeClass(SoLight.class);
mySearchAction.setInterest(SoSearchAction.Interests.FIRST);
    
mySearchAction.apply(root);
if (mySearchAction.getPath() == null) // No lights found
{
   // Add a default directional light to the scene
   SoDirectionalLight myLight = new SoDirectionalLight();
   root.insertChild(myLight, 0);
}