Together CL_SceneManager, CL_SceneLayer, and CL_SceneObject provide the core functionality to create a layered scene manager for 2D games. This means you can create layered effects just like those in GIMP or Photoshop in your computer games, in real time. The full code for this chapter, as always, can be found in the companion files.
Now let's look at how to use the scene manager class to create a scene manually.
The intention is to create a scene featuring two sprites that are composited onto one layer. This means a single layer needs to be created, and two sprite objects must be added to the layer. The overall position, color, and transparency of the sprites can be set collectively by setting the properties of the layer. The first stages involved in doing this are creating a resource manager to hold the sprite objects, and then creating a scene manager class to manage the layers. A pixel buffer is also created to ensure the layers are set to the correct pixel mode. Take a look at the following code:
//Create scene manager and associate with a resource manager CL_ResourceManager *m_Manager = new CL_ResourceManager("resources.xml"); CL_PixelBuffer Buffer = CL_PixelBuffer(512, 512, 512*4, CL_PixelFormat::rgba8888, NULL); CL_SceneManager *m_SceneManager = new CL_SceneManager(Buffer, m_Manager);
Once the resource manager, pixel buffer, and scene manager objects are created, a layer must then be created using the createLayer method, as shown earlier. This creates a new layer object, though it is not immediately added to the scene manager itself. For now, it's just a layer that exists in memory. The idea is to first add scene objects to this layer, and then attach the layer to the scene manager. The following code demonstrates this.
CL_SceneLayer *Layer1 = m_SceneManager->createLayer(256, 256, CL_PixelFormat::rgba8888, 256*4, "layer1"); CL_SceneObject *Sprite1 = m_SceneManager->createSceneObject("Game/Sprite01", m_Manager); CL_SceneObject *Sprite2 = m_SceneManager->createSceneObject("Game/Sprite02", m_Manager); Layer1->attachObject(Sprite1); Layer1->attachObject(Sprite2);
The process of drawing this layer system is simply a matter of calling the draw method of the scene manager. Since the scene manager is a derived class of CL_Surface, the standard surface drawing routine applies.
Naturally, just as the scene manager can be created manually, it can also be constructed from a valid XML file. Consider the following code:
//Create scene manager and associate with a resource manager CL_ResourceManager *m_Manager = new CL_ResourceManager("resources.xml"); CL_PixelBuffer Buffer = CL_PixelBuffer(512, 512, 512*4, CL_PixelFormat::rgba8888, NULL); CL_SceneManager *m_SceneManager = new CL_SceneManager(Buffer, m_Manager); //Load from XML m_SceneManager->loadFromXMLFile("scene.xml");