Panda3D 1.7 Game Developer's Cookbook

4.5 (2 reviews total)
By Christoph Lang
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Setting Up Panda3D and Configuring Development Tools

About this book

Panda3D is a free and open source game engine. It has been used successfully by hobbyists as well as big studios to create games ranging from quick prototypes to full-scale commercial MMOs. Panda3D makes it easy to use models, textures, and sounds to create impressive interactive experiences. With this book, you too will be able to leverage the full power of the Panda3D engine.

Panda3D 1.7 Game Developer's Cookbook will supply you with a set of recipes with step-by-step instructions to guide you to usable results quickly and take you through all the topics involved in developing games with Panda3D. First it takes a quick sweep through setting up a basic scene. Then focused articles covering advanced topics of game development carry you closer to your game development goals step by step. With each article you will be able to add more features, as the recipes guide you through getting user input from gamepads, keyboard, mouse, microphone, or even webcam, using shader effects, setting up custom render-to-texture pipelines, applying full-screen post-processing effects, adding physics with the ODE, PhysX, or Bullet physics engine, using the engine's networking capabilities with the event-driven Twisted server framework, debugging and performance profiling, and packaging your game for distribution. It will also put you in touch with other languages and technologies like C++, the Cg shading language, and the Twisted server framework.

Panda3D 1.7 Game Developer's Cookbook provides a great reference for your Panda3D game development needs and helps you to deliver impressive results more quickly and with great ease.

Publication date:
March 2011
Publisher
Packt
Pages
336
ISBN
9781849512923

 

Chapter 1. Setting Up Panda3D and Configuring Development Tools

In this chapter, we will cover:

  • Downloading and configuring NetBeans to work with Panda3D

  • Configuring Visual Studio 2008 to work with Panda3D

  • Understanding Panda3D's runtime configuration options

  • Setting up the game structure

  • Building Panda3D from source code

 

Introduction


The Panda3D game engine has initially been a closed-source project of Disney Interactive but was later opened to the community, allowing anyone to use the engine or contribute code. Development of Panda3D is now driven and coordinated in a joint effort by Disney Interactive and the Entertainment Technology Center of the Carnegie Mellon University. Together, they are adding new features, fixing bugs, and preparing new releases of the engine.

Panda3D is distributed under a version of the very liberal BSD open-source license, which allows anyone interested to download, view, alter, and redistribute the source code compiled binaries without ever having to pay any license fees. This applies to commercial projects too. So creating a game using Panda3D and selling it is no problem and will never require any amount of money to be paid.

Panda3D is a very powerful and feature-rich game engine that comes with a lot of features needed for creating modern video games. Using Python as a scripting language to interface with the low-level programming libraries makes it easy to quickly create games because this layer of abstraction neatly hides many of the complexities of handling assets, hardware resources, or graphics rendering, for example. This also allows simple games and prototypes to be created very quickly and keeps the code needed for getting things going to a minimum.

Panda3D is a complete game engine package. This means that it is not just a collection of game programming libraries with a nice Python interface, but also includes all the supplementary tools for previewing, converting, and exporting assets as well as packing game code and data for redistribution. Delivering such tools is a very important aspect of a game engine that helps with increasing the productivity of a development team.

The Panda3D engine is a very nice set of building blocks needed for creating entertainment software, scaling nicely to the needs of hobbyists, students, and professional game development teams. Panda3D is known to have been used in projects ranging from one-shot experimental prototypes to full-scale commercial MMORPG productions like Toontown Online or Pirates of the Caribbean Online.

Before you are able to start a new project and use all the powerful features provided by Panda3D to their fullest, though, you need to prepare your working environment and tools. By the end of this chapter, you will have a strong set of programming tools at hand, as well as the knowledge of how to configure Panda3D to your future projects' needs.

 

Downloading and configuring NetBeans to work with Panda3D


When writing code, having the right set of tools at hand and feeling comfortable when using them is very important. Panda3D uses Python for scripting and there are plenty of good integrated development environments available for this language like IDLE, Eclipse, or Eric. Of course, Python code can be written using the excellent Vim or Emacs editors too.

Tastes do differ, and every programmer has his or her own preferences when it comes to this decision. To make things easier and have a uniform working environment, however, we are going to use the free NetBeans IDE for developing Python scripts throughout this book. This choice was made out of pure preference and one of the many great alternatives might be used as well for following through the recipes in this book, but may require different steps for the initial setup and getting samples to run.

In this recipe we will install and configure the NetBeans integrated development environment to suit our needs for developing games with Panda3D using the Python programming language.

Getting ready

Before beginning, be sure to download and install Panda3D. To download the engine SDK and tools, go to www.panda3d.org/download.php:

The Panda3D Runtime for End-Users is a prebuilt redistributable package containing a player program and a browser plugin. These can be used to easily run packaged Panda3D games. You can find more information on this topic in Chapter 12, Packaging and Distribution.

Under Snapshot Builds, you will be able to find daily builds of the latest version of the Panda3D engine. These are to be handled with care, as they are not meant for production purposes.

Finally, the link labeled Panda3D SDK for Developers is the one you need to follow to retrieve a copy of the Panda3D development kit and tools. This will always take you to the latest release of Panda3D, which at this time is version 1.7.0. This version was marked as unstable by the developers but has been working in a stable way for this book. This version also added a great amount of interesting features, like the web browser plugin, an advanced shader, and graphics pipeline or built-in shadow effects, which really are worth a try and will be treated in the following chapters.

Click the link that says Panda3D SDK for Developers to reach the page shown in the following screenshot:

Here you can select one of the SDK packages for the platforms that Panda3D is available on. This book assumes a setup of NetBeans on Windows but most of the samples should work on these alternative platforms too, as most of Panda3D's features have been ported to all of these operating systems.

To download and install the Panda3D SDK, click the Panda3D SDK 1.7.0 link at the top of the page and download the installer package. Launch the program and follow the installation wizard, always choosing the default settings. In this and all of the following recipes we'll assume the install path to be C:\Panda3D-1.7.0, which is the default installation location. If you chose a different location, it might be a good idea to note the path and be prepared to adapt the presented file and folder paths to your needs!

How to do it...

Follow these steps to set up your Panda3D game development environment:

  1. Point your web browser to netbeans.org and click the prominent Download FREE button:

  2. Ignore the big table showing all kinds of different versions on the following page and scroll down. Click the link that says JDK with NetBeans IDE Java SE bundle.

  3. This will take you to the following page as shown here. Click the Downloads link to the right to proceed.

  4. You will find yourself at another page, as shown in the screenshot. Select Windows in the Platform dropdown menu and tick the checkbox to agree to the license agreement. Click the Continue button to proceed.

  5. Follow the instructions on the next page. Click the file name to start the download.

  6. Launch the installer and follow the setup wizard.

  7. Once installed, start the NetBeans IDE.

  8. In the main toolbar click Tools | Plugins.

  9. Select the tab that is labeled Available Plugins.

  10. Browse the list until you find Python and tick the checkbox next to it:

  11. Click Install. This will start a wizard that downloads and installs the necessary features for Python development.

  12. At the end of the installation wizard you will be prompted to restart the NetBeans IDE, which will finish the setup of the Python feature.

  13. Once NetBeans reappears on your screen, click Tools| Python Platforms.

  14. In the Python Platform Manager window, click the New button and browse for the file C:\Panda3D-1.7.0\python\ppython.exe.

  15. Select Python 2.6.4 from the platforms list and click the Make Default button. Your settings should now reflect the ones shown in the following screenshot:

  16. Finally we select the Python Path tab and once again, compare your settings to the screenshot:

  17. Click the Close button and you are done!

How it works...

In the preceding steps we configured NetBeans to use the Python runtime that drives the Panda3D engine and as we can see, it is very easy to install and set up our working environment for Panda3D.

There's more...

Different than other game engines, Panda3D follows an interesting approach in its internal architecture. While the more common approach is to embed a scripting runtime into the game engine's executable, Panda3D uses the Python runtime as its main executable. The engine modules handling such things as loading assets, rendering graphics, or playing sounds are implemented as native extension modules. These are loaded by Panda3D's custom Python interpreter as needed when we use them in our script code.

Essentially, the architecture of Panda3D turns the hierarchy between native code and the scripting runtime upside down. While in other game engines, native code initiates calls to the embedded scripting runtime, Panda3D shifts the direction of program flow. In Panda3D, the Python runtime is the core element of the engine that lets script code initiate calls into native programming libraries.

To understand Panda3D, it is important to understand this architectural decision. Whenever we start the ppython executable, we start up the Panda3D engine.

Note

If you ever get into a situation where you are compiling your own Panda3D runtime from source code, don't forget to revisit steps 13 to 17 of this recipe to configure NetBeans to use your custom runtime executable!

 

Configuring Visual Studio 2008 to work with Panda3D


The scripting-centric architecture of the Panda3D divides development into two sides. One of them is the application code written in Python that is created by game programmers to control the gameplay behavior of their games. On the opposite side we can find the engine modules, which are written in C++ and compiled to native modules. At runtime, the Python interpreter found that the core of Panda3D loads these modules and lets us make calls into them to control the engine and the game running on it.

This programming model combines the best of both of these programming worlds. While the performance critical parts are implemented in C++, gameplay programmers do not know any of the advanced stuff going on under the hood to get things done. Instead, they are able to use Python, an expressive and easy to learn programming language, for using Panda3D's great features. This also allows the engine developers to work on the internals of Panda3D while gameplay programmers are able to concentrate on creating interesting games.

While this split between application and gameplay code works really well, nothing keeps us from using the Panda3D programming libraries and writing application side code in C++. There' s nothing wrong with coding our games in Python, and in general it is the path to follow with Panda3D. But the possibility to use C++ is there, so we shouldn't omit discussing this topic.

In this recipe we will configure Visual Studio 2008 for compiling Panda3D C++ projects on Windows. Panda3D is a cross-platform game engine and other compilers like gcc and alternative IDEs like KDevelop might as well be used for writing C++ programs that link to the Panda3D libraries but within the context of this book, we will be looking at how things are working on the Windows platform.

Getting ready

This recipe assumes that Visual Studio 2008 is already installed on your system. If not, you can download Visual C++ 2008 Express Edition from www.microsoft.com/express/Downloads/ for free. Some restrictions apply to this free edition, but all recipes in this book are tested to work with this version of Visual Studio.

Note

Although technically very similar, the Express and full editions of Visual Studio do differ in several ways. Some menus, options, and functions of the full versions are not available in the free Express edition. So if you are looking for help online you should always clearly state which version you are using.

How to do it...

The following tasks will help you to configure Visual Studio 2008 for developing Panda3D projects:

  1. In a text editor of your choice, create a new file and paste the following code:

    <?xml version="1.0" encoding="Windows-1252"?>
    <VisualStudioPropertySheet
        ProjectType="Visual C++"
        Version="8.00"
        Name="PandaSettings"
        >
        <Tool
            Name="VCCLCompilerTool"
            AdditionalIncludeDirectories="&quot;C:\Panda3D-1.7.0\python\include&quot;;&quot;C:\Panda3D-1.7.0\include&quot;"
        />
        <Tool
            Name="VCLinkerTool"
            AdditionalDependencies="libp3framework.lib libpanda.lib libpandafx.lib libpandaexpress.lib libp3dtool.lib libp3dtoolconfig.lib libp3pystub.lib libp3direct.lib"
            AdditionalLibraryDirectories="&quot;C:\Panda3D-1.7.0\python\libs&quot;;&quot;C:\Panda3D-1.7.0\lib&quot;"
        />
    </VisualStudioPropertySheet>
  2. Save it as PandaSettings.vsprops in a directory of your choice.

  3. Start Visual Studio 2008 or Visual C++ 2008 Express and create a new C++ project.

  4. Open the Property Manager, which is located in the same pane as the Solution Explorer and the Class View by default. If you can't find it this way, click View | Property Manager in the main menu.

  5. Right-click the item Release | Win32 and select Add Existing Property Sheet... from the popup menu.

  6. Locate and select the PandaSettings.vsprops file.

How it works...

In this recipe we set all the options for using Panda3D using a feature of Visual Studio called Property Sheets, which allow you to configure each build target of your project independently and in a reusable way.

Property Sheet settings are stored using XML, as you can see in the previous sample code. Let's have a look at the data stored in PandaSettings.vsprops:

Following the XML header and the opening tag of the property sheet, we can see two <Tool/> tags, the first of which is adding the required include paths to the header search paths. The second <Tool/> tag instructs the linker to use the listed library files when it is generating the executable, as well as where it will need to look for these files.

There's more...

You might have noticed that we only configured the release target in this recipe. The reason for this is that the recipe is aimed at the precompiled Panda3D SDK, which only includes the files needed to produce release builds.

Note

If you want to create debug builds you will definitely need to compile Panda3D yourself and configure your debug target in the way shown in this recipe (but don't forget to modify the search paths accordingly!).

Also, you don't have to use Property Sheets to configure include directories and linked libraries. You may also right-click the project node in the project explorer, click Properties and then click Configuration Properties | Properties | C++ in the tree of configuration categories to then fill in the include directories in the Additional Include Directories field in the right pane of the window.

To configure the linker, choose Configuration Properties | Properties | Linker in the same window as previously described and fill in the library file names into the Additional Dependencies and Additional Library Directories fields.

 

Understanding Panda3D's runtime configuration options


Panda3D allows you to configure the engine runtime using a central configuration file. This recipe will show you where to find this configuration file and will explain a selection of settings you are able to specify to tweak Panda3D's behavior.

How to do it...

You can configure the Panda3D engine with these two steps:

  1. Open the file C:\Panda3D-1.7.0\etc\Config.prc in a text editor.

  2. Edit and add settings.

How it works...

Now that you've opened Panda3D's configuration file, it is time to explain a good part of the vast array of settings the engine allows you to modify. The following table will present the names of the configuration variables, the values that can be set, as well as a short description of what part of Panda3D is influenced by the setting.

The column containing the possible values uses several notations:

  • Square brackets are used to denote an interval of values. For example, [0..8] denotes an interval of integers between 0 and 8, while the notation [0.0..1.0] stands for an interval of floating point values. The interval boundaries are inclusive.

  • Within intervals, the labels MAX_INT and MAX_DBL are used as placeholders for the maximum possible values for signed integer and floating point variables.

  • The prc file format uses #t for true and #f for false for Boolean configuration flags. For example, the following line in Config.prc enables full screen mode:

    fullscreen #t
  • "A valid file path" means a Unix-style file path, even on Windows. For example, the following line is used to set the application icon:

    icon-filename /c/mygame/assets/icon.ico
  • Any other values than the ones previously described are meant to be inserted directly, without quotes. If multiple values are listed, you may use one of them at a time.

Name

Possible Values

Description

audio-volume

[0.0..1.0]

Sets the master volume of your game.

background-color

Any combination of 3 floating point numbers between 0 and 1, e.g.: 1.0 0.3 0.4

This variable sets the default background color for the render window and all render buffers in RGB format.

cursor-filename

A valid file path

Allows you to specify an image file to use as the mouse cursor.

cursor-hidden

#t, #f

If set to true, this makes the mouse cursor invisible when it is within the bounds of the game window.

disable-sticky-keys

#t, #f

If set to true, this disables the "sticky keys" feature of Windows. It's a good idea to set this to true because the sticky keys popup window will cause your game to lose focus!

fullscreen

#t, #f

Set this variable to #t if your game should switch to fullscreen mode on startup.

icon-filename

A valid file path

This variable instructs Panda3D to use the given file as its application icon.

model-path

A valid file path

The model-path variable sets one or more paths the engine will use as your search path when looking for models to load. The special symbol $THIS_PRC_DIR can be used to define directories relative to the configuration file. With $MAIN_DIR you are able to set a path relative to the directory the game's main python file resides in.

For example, we can find these three lines in the default Config.prc file:

model-path $MAIN_DIR

model-path $THIS_PRC_DIR/..

model-path $THIS_PRC_DIR/../models

These lines add the directory containing the main Python source file and the directories containing the sample models that come with the Panda3D SDK to the engine asset search path.

show-frame-rate-meter

#t, #f

If enabled, this shows a frame rate counter in the game window.

sync-video

#t, #f

Enables and disables vertical synchronization. If this is set to true, the maximum frame rate will be equal to the refresh rate of your display device.

win-origin

Two integer values, for example, 25 20

Lets you define the position of the top left corner of the game window. When fullscreen mode is enabled, this setting has no effect.

win-size

Two integer values, for example, 640 480

Sets the window size as well as the resolution when in fullscreen mode. When going to fullscreen mode, Panda3D switches the screen resolution to the values specified in this variable. If this does not match your screen resolution, it might have an effect on the positions and sizes of your desktop icons and any open program window.

window-title

A string

This setting is used to specify the title of the game window. The string does not have to be put within quotes even if it contains spaces.

There's more...

By setting the configuration variables above, you are already able to modify the engine's runtime behavior to your liking. But Panda3D's configuration system provides a few additional features you should know about.

Listing all configuration variables

The preceding table only shows a selection of the most commonly used configuration variables. To get a list of all configuration variables available in Panda3D, insert the following import statement and method call into your application code:

from panda3d.core import ConfigVariableManager
ConfigVariableManager.getGlobalPtr().listVariables()

Loading a specific configuration file

You do not need to put all engine settings into the global configuration file shown in this recipe. Instead, you can use the following function to load settings from any given file:

loadPrcFile("myconfig.prc")

You should put this call to a global scope to make sure settings are loaded before the engine systems that are using them are initialized.

Embedding configuration data in Python code

You can also put settings directly into your Python code files. Just add something similar to the following snippet to the global scope:

configVars = """
win-size 1440 900
fullscreen 1
"""

loadPrcFileData("", configVars)
 

Setting up the game structure


Through the course of this recipe you will learn the steps that are necessary to set up a very basic application structure to get your application going.

Getting ready

To follow the steps of this recipe you should have finished the first recipe in this chapter to have a properly configured development environment.

How to do it...

Follow these steps to create an empty project skeleton:

  1. Start NetBeans and click File | New Project… in the main menu.

  2. Select Python Project and click Next on the first screen of the New Project Wizard.

  3. On the New Python Project screen, set the Project Name and choose a Project Location. Also select Set as Main Project and Create Main File. Set the textbox to main.py, and check that the right Python Platform is active. Click Finish to proceed.

  4. Right-click the Project Name | Sources | Top Level item in the tree view in the Projects tab and select New | Empty Module.

  5. In the window that opens, set the File Name to Application and click Finish.

  6. Paste the following code into Application.py:

    from direct.showbase.ShowBase import ShowBase
    
    class Application(ShowBase):
        def __init__(self):
            ShowBase.__init__(self)
  7. The code that follows goes into main.py:

    from Application import Application
    
    if __name__ == "__main__":
        gameApp = Application()
        gameApp.run()
  8. Open your project directory in Windows Explorer and create folders called models and sounds next to the src folder. The folder structure should resemble the following screenshot:

  9. Open the Config.prc file as described in the prior recipe and add the following lines:

    model-path $MAIN_DIR/../models
    model-path $MAIN_DIR/../sounds
  10. Hit F6 to run the application.

How it works...

First, we start by creating a new project in NetBeans. It generally is a very good idea to name the main file that will be launched by the Python runtime main.py, so we are already set when we want to package our code and assets for redistribution later on.

The Application class, derived from ShowBase, is added as an abstraction of our game application. We must not forget to call the constructor of ShowBase in the constructor of Application or else there won't be a window opening when launching the program.

Because we do not want code files and assets to be scattered in a mess inside one single folder, we add folders dedicated to certain asset types. Depending on the type of project we intend to create, this setup may vary and we may wish to add additional folders. What's important about that is not to forget to add these extra folders to Panda3D's search paths too in Config.prc, just like the models and sounds folders!

 

Building Panda3D from source code


When developing a game with Panda3D you may want to—and most likely will need to—compile the engine from source code. This recipe will show how to do this and show which options there are for configuring how your custom build of Panda3D is created.

Getting ready

The following instructions rely on the target system having installed Microsoft Visual Studio 2008 or Microsoft Visual C++ Express 2008. To build the DirectX 8 and 9 renderers, you also need the DirectX SDK, which can be downloaded from msdn.microsoft.com/en-us/directx/aa937788.aspx. If you have the Professional Edition of Visual Studio, you're set and ready to go.

For making the recipe work with the Express Edition you will need to download and install the Windows Server 2003 R2 Platform SDK, as recommended in the documentation of Panda3D. It can be obtained from the following URL: www.microsoft.com/downloads/details.aspx?familyid=0BAF2B35-C656-4969-ACE8-E4C0C0716ADB

How to do it...

Work through these tasks to build Panda3D from source code:

  1. Go to www.panda3d.org/download.php?platform=windows&version=1.7.0&sdk, download the Panda3D Complete Source Code package and unzip the archive at a location of your choice.

  2. Open the file makepanda\makepanda.bat in a text editor and change the line if %PROCESSOR_ARCHITECTURE% == AMD64 goto :AMD64 to REM if %PROCESSOR_ARCHITECTURE% == AMD64 goto :AMD64.

  3. Open a Visual Studio 2008 Command Prompt by clicking Microsoft Visual Studio 2008 | Visual Studio Tools | Visual Studio Command Prompt in the Start menu. If you have Visual C++ Express 2008, you can find it under Microsoft Visual C++ Express 2008 | Visual Studio Tools | Visual Studio Command Prompt.

  4. Change to the directory you unpacked the source code to. If you enter the dir command and see the following directory listing (or a similar looking one) you are in the right directory:

  5. Type makepanda\makepanda.bat --everything.

How it works...

Panda3D uses its own custom build system to produce builds from source code. In step 2, we need to modify the build system's start script to prevent it from throwing an error if the build system is using a 64-bit processor. Building 64-bit executables does not work with version 1.7.0 of Panda3D and isn't officially supported, so we force the build system to compile 32-bit executables and libraries.

In the following steps we open a Visual Studio 2008 Command Prompt, which guarantees that all required search paths are set properly and kick off a complete build of Panda3D. Please note that such a build, depending on the power of your machine, takes about one hour to complete!

Once the build is complete, the freshly compiled version of Panda3D can be found in the built subdirectory.

There's more...

Panda3D's build system allows us to configure the build using a number of command line flags. The --everything option we already used before will instruct the makepanda script to build Panda3D and all third party libraries.

The exact counterpart of the --everything option is --nothing, which will disable all third party libraries to be built.

Of course there isn't just on and off. The makepanda build script allows us to set which libraries we do and do not want to include in our build. This can be done by setting the various --use-xxx and --no-xxx flags, where xxx stands for a library to be included or left out of the resulting executable. For a full list, just issue the command makepanda\makepanda.bat from the top level of the unpacked source package.

The --optimize option allows to set the optimization level used when compiling Panda3D on a range from 1 to 4, where 1 creates a debug build and 4 enables the most aggressive optimizations, including link time code generation. If not set, this value defaults to 3, which provides a safe default while generating a very well performing build.

Lastly, we can use the --installer flag to generate an installer, which for example makes it easier to redistribute the custom build of the engine to other developers on a team.

About the Author

  • Christoph Lang

    Christoph Lang is a game developer currently working for Mi’pu’mi Games in Vienna. He has a BSc in Computer Science and an MSc in Game Engineering and Simulation Technology, both from UAS Technikum Wien. You can find him blogging on altdevblogaday.com and tweeting as @moorx.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Un bon livre de recette qui me sera très utile. Dommage que les explications de certaines parties des programmes ne soient pas plus détaillées.
The book is very useful to get started with Panda3D.
Panda3D 1.7 Game Developer's Cookbook
Unlock this book and the full library for FREE
Start free trial