Panda3D really makes it very easy to load and use assets like models, actors, textures, and sounds. But there is a problem with the default behavior of the asset loader—it blocks the execution of the engine.
This is not a problem if all data is loaded before the player is allowed to see the game world, but if models and other assets are to be loaded while the game is running, we are facing a serious problem because the frame rate will drop dramatically for a moment. This will cause game execution to stop for a short moment in a sudden and unpredictable way that breaks gameplay.
To avoid getting into such problems, Panda3D offers the ability to load data through a background thread. This is a very useful feature if game assets are loaded on the fly, such as the popular use case with seamless streaming in game worlds. It is also a great way to reduce initial loading times. The main level geometry and everything visible from the starting position is loaded before the player enters the world and the rest of it is loaded afterwards, often depending on the position in the game world.
Getting ready
For this recipe you will need to set up the basic framework described in Setting up the game structure.
How to do it...
Follow these steps to create a sample application that demonstrates asynchronous data loading:
Press F6 to run the application. You will see a delay before the teapot and the panda appear in the window.
How it works...
The previous code enqueues calls to the load() method using doMethodLater() so you can see the objects pop up as soon as they are loaded. The list passed to the extraArgs parameter will be used as parameters for the call to load().
The call to loadModel() within the load method is very important, because instead of just passing the name of the model to load, you also set the callback parameter to one of the modelLoaded() and actorLoaded() methods, depending on what the cb parameter of load() contains.
As soon as a call to loadModel() uses the callback parameter, the request to load the data is handed off to a background thread. When the required asset has finished loading, the callback function is called and the loaded asset is passed as the first parameter, as you can see in the modelLoaded() and actorLoaded() methods.