1. Customizing OpenSceneGraph – OpenSceneGraph 3 Cookbook

Chapter 1. Customizing OpenSceneGraph

In this chapter, we will cover:

  • Checking out the latest version of OSG

  • Configuring CMake options

  • Building common plugins

  • Compiling and packaging OSG on different platforms

  • Compiling and using OSG on mobile devices

  • Compiling and using dynamic and static libraries

  • Generating the API documentation

  • Creating your own project using CMake


OpenSceneGraph, which will also be abbreviated as OSG in the following parts of this book, is one of the best open source, high performance 3D graphics toolkits. It is designed to run under different operation systems, and even mobile platforms. The CMake build system (http://www.cmake.org/) is used to configure its compilation process and generate native makefiles, as well as packaging the binaries and development files.

OSG also contains hundreds of plugins for reading and writing files. Some of the plugins require providing external dependencies, and some may not be workable under specified platforms. Meanwhile, there are plenty of options to enable or disable while you are compiling OSG from the source code. These options are designed and implemented using CMake scripts, with which we could also create our own projects and provide different choices to the team or the public (if you are working on open source projects) too.

We are going to talk about the following concepts in this chapter: The customization of the OpenSceneGraph library from source code, the understanding of basic CMake scripts, and the construction of your own programs by reusing them.

Of course, you may select to directly download the prebuilt binaries, which is already configured in an irrevocable way, to save your time of compiling and start programming at once. The OpenSceneGraph official download link is:


Binaries provided by the AlphaPixel, including Windows, Mac OS X, and Linux versions, can be found at:


And the online installer for Windows developers is located at:


Checking out the latest version of OSG

The first step we should do to customize the OpenSceneGraph library is to obtain it. Yes, you may simply get the source code of a stable version from the official download link we just introduced; otherwise, you could also find all kinds of developer releases in the following page:


Developer releases, with an odd minor version number (the first decimal place), always contains some new functionalities but haven't undergone different test rounds. For instance, 2.9.12 is a developer release, and it is one of the stepping stones towards the next stable release, that is, OpenSceneGraph 3.0.

Pay attention to the phrase 'new functionalities' here. Yes, that is what we really care about in this cookbook. It would be boring if we still focus on some very basic scene graph concepts such as group nodes and state sets. What we want here will be the latest features of OSG and OpenGL, as well as examples demonstrating them. So we will try to acquire the latest version of the source code too, using the source control service.

For beginners of OSG programming, please refer to the book "OpenSceneGraph 3.0: Beginner's Guide", Rui Wang and Xuelei Qian, Packt Publishing. Some other good resources and discussions can be found in the "osg-users" mailing list and Paul Martz's website (http://www.osgbooks.com/).

Getting ready

You have to make use of the Subversion tool, which is a popular revision-control system used by OSG. Its official website is:


You can easily download the binary packages of the specified platform in the Binary Packages section, which are mostly maintained by some third-party organizations and persons. Of course, you may also compile Subversion from source code if you have interest.

For Debian and Ubuntu users, make sure you have the root permission and type the command apt-get in the terminal as shown in the following command line:

# sudo apt-get install subversion

The hash sign (#) here indicates the prompt before the command. It may change due to different platforms.

For Windows users, a GUI client named TortoiseSVN is preferred. It is built against a stable enough version of Subversion, and provides easy access to different source control operations. You may download it from:


How to do it...

We will take Ubuntu and Windows as examples to check out the latest OSG source code with Subversion. Users of other platforms should first find the correct location of the executable file (usually named svn) and follow the steps with appropriate permissions.

We will split the recipe into two parts—for Ubuntu users and Windows users.


Be aware of the phrase 'check out'. It can be explained as downloading files from the remote repository. Another important word that you need to know is 'trunk'. It is the base of a project for the latest development work. So, 'check out the trunk' means to download the cutting-edge version of the source code. This is exactly what we want in this recipe.

For Ubuntu users

  1. Check out the OpenSceneGraph trunk by typing the following command in the terminal (you may have to add sudo at the beginning to run as an administrator):

    # svn checkout http://www.openscenegraph.org/svn/osg/OpenSceneGraph/trunk OpenSceneGraph
  2. The first argument, checkout indicates the command to use. The second argument is the remote link to check out from. And the third one, OpenSceneGraph is the local path, in which downloaded files will be saved. Subversion will automatically create the local sub-directory if it does not exist.

  3. Now you can take a look into the local directory ./OpenSceneGraph. It contains the entire source code of the latest OSG now! Before configuring and compiling it, there is no harm in checking the source information first. Run the following command in the directory:

    # cd OpenSceneGraph
    # svn info
  4. This screenshot shows some useful information: URL is the remote address from which you checked the source code out; Revision is an automatically increasing number which could indicate the version of the code.


    When discussing issues with anyone in the forum or in the mail list, it is quite helpful if you can provide the revision number of your OSG library.

  5. Remember that OSG is growing all the time. The source code you have checked out may be outdated in the next few days, or even in the next hour. The source tree may be modified to add new features or make fixes to previous functionalities. If you want to update these changes, go to the local directory and type the following:

# cd OpenSceneGraph
# svn update

  • Nothing will happen if no changes are made after the last updating. And there will be conflicts if you have altered some of the source code locally. In that case, you should consider removing these modified files and re-update the trunk to recover them. If you are going to commit your changes to the official OpenSceneGraph developer team, use the "osg-submissions" mailing list instead.

For Windows users

  1. It will be a little easier to check out and update the trunk if you are using TortoiseSVN. Right click on the desktop or in a specified folder and you will see an SVN Checkout menu item, if TortoiseSVN is installed properly. Click on it and fill in the pop up dialog as shown in the following screenshot:

  2. The most important options here are URL of repository and Checkout directory. Be sure to paste the following address to the former and specify an empty local folder for the latter:

  3. Everything will be done automatically after you click on OK and you will soon find the source code in the right place. Right click on the newly created directory, and there is a new SVN Update menu item. Use it to update to the latest trunk version.

How it works...

Source code control is pretty useful when you are working with a team and have to share sources with other developers. Of course, we may put all source files in one folder on the network driver for everyone to visit and edit. But there may be serious conflicts if more than one developer is modifying the same file at the same time. And in such cases, someone's changes will definitely be lost.

The solution is to save recently added files on a remote server, which cannot be modified directly. Each developer can have an own copy on the local disk by performing the checkout operation. Developers who have the 'write' permission can commit their code to the server, and the server will synchronize all changes to every other owner's copy when they perform the update operation.

This is what the OSG developer team actually does. Everyone can use the Subversion tool to clone a copy of the latest source code and keep it fresh, but only a few core developers have the rights to upload their code, and help more contributors to submit their code.

There's more...

The Subversion tool can be used to manage the OSG sample data and some other OSG-related projects as well. Some commands will be listed here for convenience.

Here is the command to obtain the latest sample data (you could also set the environment variable OSG_FILE_PATH to the local path here):

# svn checkout http://www.openscenegraph.org/svn/osg/OpenSceneGraph-Data/trunk OpenSceneGraph-data

VirtualPlanetBuilder is a terrain database-creation tool which will be used for managing and rendering massive paged data. We are going to demonstrate it in Chapter 7. Here it is so you can check it out for later use:

# svn checkout http://www.openscenegraph.org/svn/VirtualPlanetBuilder/trunk VirtualPlanetBuilder-trunk

Besides checking out the source code and updating it with Subversion, sometimes you may also want to export the whole source code directory to a clean one, that is, to clone the source code. The export command will work for you here, for example:

# svn export this_folder/OpenSceneGraph-trunk /another_folder/cloned-trunk


Remember, don't directly copy the directory. Subversion puts a lot of hidden folders (named .svn) inside to help manage the source code. And it is really a waste if we copy these to the target directory too.

It is certainly beyond this book to introduce all other SVN commands one by one. Some additional books would be of help if you are interested in this famous source control system, such as "Version Control with Subversion", Ben Collins-Sussman, O'Reilly Media. The online version can be found at http://svnbook.red-bean.com).

Configuring CMake options

If you have an experience of compiling OSG from the source code, you should already be familiar with the CMake system and the cmake-gui GUI tool. This book is neither a CMake tutorial book nor a step-by-step OSG compilation guide. Here we will quickly go through the configuration process, and tell you how to make use of some key options to change the behaviors and results.

Again, to come to understand what should be done before and after the configuration procedure, please refer to the book "OpenSceneGraph 3.0: Beginner's Guide", Rui Wang and Xuelei Qian, Packt Publishing.

Getting ready

At the least you should have the OSG source code, the CMake software, and a workable C++ compiler. GCC is the most common compiler for GNU and BSD operating systems, including most Linux distributions. Windows developers may choose Visual Studio or MinGW, or use Cygwin to construct a Linux-like environment. For Mac OS X users, XCode is preferred as the kernel developing toolkit.

CMake binary packages for various systems are available at:


You may also use the apt-get command here to install the cmake (command-line mode) and cmake-gui (GUI mode) utilities separately:

# sudo apt-get install cmake
# sudo apt-get install cmake-gui

You must have the OpenGL library before compiling OSG. This is certainly the bottom line. Install it with apt-get if you don't have it by executing the following commands:

# sudo apt-get install libgl1-mesa-dev
# sudo apt-get install libglu1-mesa-dev

How to do it...

The cmake-gui utility has a similar user interface under every platform. And the configuring steps are of little difference too. We will only introduce the Ubuntu case in this recipe.

  1. Run cmake-gui with administrator permission. Drag and drop CMakeLists.txt from OSG root directory to the GUI window. You will see the text boxes of source and build destinations changed immediately.

  2. Edit the Where to build the binaries box and specify a different place for the generated makefiles or project files, that is, an out-of-source build. That is because the SVN checkout operation will establish the source directory with an update and revision information of every file. Any newly added items will be marked and considered as 'to be committed to remote repository later', therefore, an out-of-source build will prevent the generated project and temporary files from being recorded improperly.

  3. Click on Configure and select a generator corresponding to your system (Unix Makefiles for Ubuntu). After checking the system automatically, you will see a lot of options appear in the GUI. Click on Finish as shown in the following screenshot:

  4. Next, check the Grouped checkbox to put the options in a more readable order. All the options shown here are marked with red at present, which means that they are not set yet. Change one or more of these options and click on Configure to confirm them. New unset options may appear as the results of previous choices. All you have to do is to confirm them until there are no red items, and click on Generate to finish it up.

    The default values of the configuration options are good enough. So we can just leave them except for setting up the build type (debug or release libraries) and the install prefix under which all OSG binaries and development files will be installed.

  5. The CMAKE_BUILD_TYPE item in the CMake group is used for deciding the build type. Input Debug in the Value column if you want a debug version of libraries and binaries. Input Release or leave it blank if not. By default, it is just empty (if you are using a Visual Studio generator under Windows, it contains multiple configurations).

  6. The CMAKE_INSTALL_PREFIX item, which is also in the CMake group, will help specify the base installation path. By default, it is set to /usr/local. Type the value manually or use the browse button on the right-hand side to make decisions.

  7. Confirm and generate the makefiles. Have a look into the target directory and if you like, do make and make install now (but you may have to do this again and again during the next few recipes).

There's more...

CMake supports various kinds of generators, each of which could be used under one or more specified platforms. The following table will provide more details about creating OSG makefiles or solutions using different generators:



Required environment


MinGW Makefiles



Makefiles for use with mingw32-make

NMake Makefiles


Visual Studio 7/8/9/10

Makefiles for use with nmake

Unix Makefiles



Mac OS X

GCC and G++

(available for Cygwin users under Windows)

Standard Unix makefiles

Visual Studio

(Specify the version number)


Visual Studio 7/8/9/10

(Previous versions are not suitable for compiling OSG)

Visual Studio solutions


(Specify the makefile type: MinGW, NMake, or Unix)



Mac OS X

Code::Blocks IDE

Code::Blocks projects


Mac OS X

Apple XCode

XCode projects

Building common plugins

OSG works with hundreds of kinds of plugins with a uniform prefix osgdb_*. Most of them can read specified file formats (mainly models and images) into scene objects, and some can also write the nodes or images back to files. The plugin mechanism brings us a lot of convenience as it handles file extensions and chooses a corresponding reader/writer for us internally. Developers will only have to call the osgDB::readNodeFile() or osgDB::readImageFile() method with the filename while writing OSG-based applications.

In this recipe, we are going to configure CMake options to build with the most common plugins. For general plugins, such as BMP, DDS, and the native OSG format reader/writer, the build process will be faithfully executed and they will always be generated without doubts. But for plugins requiring external dependencies, such as DAE (requires Collada DOM) and JPEG (requires libJPEG), CMake scripts will automatically remove the plugin sub-directories from the build queue in case the third-party includes a path and libraries are not specified correctly.

It is impossible to get all the plugins built under a certain platform. But we still have some very common plugins depending on external libraries. It is really a pity to leave them alone and thus lose some good features, such as FreeType font support and network data transferring with libCURL. To avoid missing them, there are two rules to follow: First, download or compile the development packages of external libraries; then, set related options while configuring OSG with CMake.

Getting ready

We will first make a list of the most practical plugins, download their dependent libraries, and set them up in the cmake-gui window. The list includes curl, freetype, gif, jpeg, png, Qt, and zlib plugins.


Have a look at the book "OpenSceneGraph 3.0: Beginner's Guide", Rui Wang and Xuelei Qian, Packt Publishing, in case you are interested in other plugins too. In Chapter 10, you will find a complete list of file I/O plugins currently supported by OSG.

How to do it...

Thanks to the apt-get tool, we can make things easier under Ubuntu as follows:

  1. Download all the binary packages of external dependencies with the apt-get command:

    # sudo apt-get install libcurl4-openssl-dev
    # sudo apt-get install libfreetype6-dev
    # sudo apt-get install libgif-dev
    # sudo apt-get install libjpeg62-dev
    # sudo apt-get install libpng12-dev
    # sudo apt-get install zlib1g-dev
  2. Download Qt online installer from:


  3. Make it executable and run it to download and install Qt SDK:

    # sudo chmod u+x Qt_SDK_Lin32_online_v1_1_1_en.run
    # sudo ./Qt_SDK_Lin32_online_v1_1_1_en.run
  4. Now it's time to configure these libraries using cmake-gui. Just reopen the GUI window and click on the Configure button. Check on the Advanced checkbox to show all the options and check into related groups, including CURL, FREETYPE, GIFLIB, JPEG, QT, PNG, and ZLIB. If you see nothing unexpected, you will happily find that every *_INCLUDE_DIR and *_LIBRARY is set correctly. CMake has already queried these installed libraries and got them ready for compiling corresponding plugins.

  5. Generate makefiles, and enjoy the compiling work again. It will take much shorter time to finish the entire process this time, unless you remove the build directory containing all the intermediate object files.

How it works...

Let us see what these plugins do and where to learn about their dependencies:

  • osgdb_curl: This plugin can provide OSG with network transferring functionalities. It helps fetch data from HTTP and FTP servers and use local file readers to parse them. It requires libCURL as the dependence. Binary packages and source code can be downloaded from http://curl.haxx.se/download.html.

  • osgdb_freetype: This plugin is important as it provides osgText with the ability of displaying TrueType fonts (TTF, TTC formats, and so on). The FreeType library is necessary, which could be downloaded from http://freetype.sourceforge.net/download.html.

  • osgdb_gif: This plugin reads GIF and animated GIF images, with GifLib (http://sourceforge.net/projects/giflib/) as dependence.

  • osgdb_jpeg: This plugin reads JPG and JPEG images, with libJPEG (http://www.ijg.org/) as dependence.

  • osgdb_png: This plugin reads PNG images, with Zlib and libPNG (http://www.libpng.org/pub/png/libpng.html) as dependence.

  • osgQt: The osgQt library can be used for OSG and Qt integration and QFont support. It requires the Qt toolkit (http://qt.nokia.com/downloads/). Don't miss it as we will talk about some interesting implementations about Qt and OSG in the following chapters.

  • Zlib: The Zlib library is used widely as the dependence of core libraries and plugins. For example, the osgDB library and the native IVE format can depend on Zlib to support file compression. And the osgdb_png plugin needs it too. Its official website is http://zlib.net/.

There's more...

For Windows users, it may not be simple to get all these dependencies at once. And to compile them from source code one-by-one is a really harrowing experience for some people (but for somebody else, it may be exciting. Tastes differ!). The following link may be helpful as it contains Win32 ports of some GNU libraries (FreeType, Giflib, libJPEG, libPNG, and Zlib):


Win32 binaries of libCurl and Qt can be found on their own websites.

CMake may not work like a charm under Windows systems, that is, it can hardly find installed libraries automatically. Specify the ACTUAL_3DPARTY_DIR option in Ungrouped Entries to the root path of uncompressed binaries and development files, and reconfigure to see if it works. Also, you can refer to Chapter 10 of the "OpenSceneGraph 3.0: Beginner's Guide" book.

Compiling and packaging OSG on different platforms

You must be familiar with the compilation of OSG under Unix-like systems by simply inputting the following commands in a terminal:

# sudo make
# sudo make install

Of course, the prerequisite is that you must have already configured OSG with cmake-gui or some other command-line tools and generated the makefiles as well. If not, then you may first read the book "OpenSceneGraph 3.0: Beginner's Guide", Rui Wang and Xuelei Qian, Packt Publishing, for basic knowledge about compiling OSG.

For Windows and Mac OS X users, we always have some slightly different ways to do this because of the wide use of IDEs (Integrated Development Environment), but we may also build from makefiles by specifying the generator type in the CMake configuration window.

Another interesting topic here is the packaging of built binaries. It may automatically create RPM, DEB, and GZIP packages under Linux, and even self-extracting installer sunder Windows.

Getting ready

The packaging feature is implemented by the CPack packaging system integrated with CMake, so you don't have to download or install it on your own. TGZ (.tar.gz) is chose as the default package format under Linux and ZIP is the default one under Windows.

WinZIP (http://www.winzip.com/win/en/index.htm) is required by CPack to generate ZIP files. And if you want a cool self-extracting installer/uninstaller, you may get the NSIS (Nullsoft Scriptable Install System) from:


Set the environment variable PATH to include the location of the executables, and CPack will automatically find and make use of each of them.

How to do it...

Under any UNIX-link systems, to enable packaging, you have to open cmake-gui and set BUILD_OSG_PACKAGES to ON. Looking at the option CPACK_GENERATOR in Ungrouped Entries, you can just keep the default value TGZ, or change it to RPM or DEB if you wish to. Corresponding software must be installed to ensure the package generator works.

After that, there is nothing besides make to build OSG libraries. Open a terminal and type make in the build folder to compile the OSG library, or use the generated solution file if you are using Visual Studio products. But instead of installing to a specific directory, this time you could make a series of .tar archives containing OSG binaries, development files, and applications and share these developer files with others. Just type the following:

# sudo make package_openscenegraph-all

Windows users may open the generated Visual Studio solution. Build the sub-project ALL_BUILD and click on INSTALL to compile one-by-one and install all targets. But similarly, they could also select to build the sub-project Package openscenegraph-all instead of clicking on INSTALL. This will result in a series of zipped files or NSIS installers.

For Mac OSX users, start XCode and open OpenSceneGraph.xcodeproj from the build directory. Choose Targets in the Groups & Files view and build ALL_BUILD and install in that order. Again, it is possible to choose package_ALL after all libraries built, if you have already had CPack options set before.

How it works...

Generated packages may differ as the result of changing CMake options. The following table shows what you will get after the make package operation. The prefix (for example, openscenegraph-all-3.0.0-Linux-i386-Release-*) of each package file is just ignored here.

Package name

Required option




The OpenThreads library file



The OpenThreads include files and static-link libraries



The OpenSceneGraph core library files



The OpenSceneGraph include files and static-link libraries



Applications (osgviewer, osgversion, and so on)






The OpenThreads reference documentation



The OpenSceneGraph reference documentation

Compiling and using OSG on mobile devices

It is really exciting to know that the latest OSG supports some of the most popular mobile platforms. After preparing necessary environments and changing some CMake options, we can then easily build OSG for iOS and Android systems, including iPhone, iPad, most Android based devices, and their simulators.

Remember, your mobile device must support OpenGL ES (OpenGL for Embedded Systems) to run any OSG applications. And there are also various API redefinitions and limitations that will make some functionalities work improperly. Fortunately, Google Android provides SDKs, simulators, and GLES libraries for development. So it will be an excellent example for demonstrating how to compile and use OSG on mobile devices.

Getting ready

Download Android SDK and Android NDK from their official websites:



Remember that you need NDK r4 or a later version to make the compilation successful. However, the SDK version doesn't matter most of the time.

A very important note before you are going on: At present, some Tegra devices, including Acer IconiaTab and Motorola XOOM, are unable to work with NEON extensions. But OSG at present doesn't provide direct options to disable NEON, so the only way to get these devices to work with OSG libraries in the future is to comment the following line in PlatformSpecifics/Android/modules.mk.in:

# LOCAL_ARM_NEON := true

And compile OSG following the instructions in the next section.

How to do it...

You have to make changes in CMake options to let OSG realize that it is going to work under GLES v1 or v2, and must be cross-compiled with the C++ compiler provided by Android NDK.

In this recipe, we will only show how to configure OSG with GLES v1 support.

  1. Start cmake-gui and reset the options in the group OSG as shown in the table:

    Option name





    Don't build dynamic libraries on Android



    Don't build dynamic libraries on Android



    Enable to build OSG for Android



    Disable the use of C++ exceptions



    No support for OpenGL 1.x



    No support for OpenGL 2.x



    No support for OpenGL 3.x



    Add supports for OpenGL ES 1.x



    No support for OpenGL ES 2.x



    No support for display lists



    Android has its own windowing system, so don't use any others here

  2. Configure the ANDROID_NDK option which appears after you press Configure. Make sure the ndk_build executable is in your NDK installation path (we suppose it is Your_NDK_Root) and specify Your_NDK_Root as the value.

  3. Configure the OpenGL include directory and libraries in the OPENGL group to support GLES v1:

    Option name



    The parent directory of EGL. You can find it at Your_NDK_Root/platforms/android-9/arch-arm/usr/include. Your_NDR_Root and android-9 may differ according to your NDK installation.


    The libEGL library. You can find it at Your_NDK_Root/platforms/android-9/arch-arm/usr/lib.


    The libGLESv1_CM library (may differ). You can find it at Your_NDK_Root/platforms/android-9/arch-arm/usr/lib.


    Don't set it. GLES can't use the GLU library.

  4. Nearly done! Now reset all the third-party library options (such as the JPEG, PNG groups, and so on) to NOTFOUND. That is because all of them have to be rebuilt with the Android compiler first, and there may be several limitations and errors. We are not going to discuss this painful process in this book.

  5. Now simply run the following command:

    # sudo make
  6. If you want to add some NDK building options, such as -B (to do a complete rebuild) or NDK_DEBUG=1 (to generate debugging code), use the ndk_build executable directly:

    # Your_NDK_Root/ndk_build NDK_APPLICATION_MK=Application.mk
  7. Now wait for the libraries to finish compiling.

There's more...

We won't discuss any examples on Android here; this will be done in the Chapter 9,Integrating with GUI.

If you want to compile OSG with GLES v2, remember to handle the following CMake options in addition to the preceding table, besides enabling OSG_GLES2_AVAILABLE (but they must be turned on if you choose GLES v1):

Option name





No support for OpenGL ES 1.x



No support for OpenGL matrix functions



No support for OpenGL vertex functions



No support for OpenGL vertex array functions



No support for all fixed functions

Maybe you are interested in how to configure OSG to use OpenGL ES instead of the standard OpenGL and GLU libraries. The following link will point out the main difference between the options of GLES v1 and GLES v2:


OSG can also work under Mac OS X to support iOS, and thus support iPhone, iPad, and other Apple devices with GLES. Check the option OSG_BUILD_PLATFORM_IPHONE or OSG_BUILD_PLATFORM_IPHONE_SIMULATOR and specify the iOS SDK location. Follow the discussions on "osg-users" mailing list and try to work out the compilation yourselves.

The OpenGL ES development files are always necessary when you are developing on mobile devices. And for Windows users, there are some other OpenGL ES emulators for you to test if OSG and your applications work under such environments.

ARM OpenGL ES 2.0 Emulator can be found at http://www.malideveloper.com/developer-resources/tools/opengl-es-20-emulator.php.

Qualcomm Adreno SDK can be found at http://developer.qualcomm.com/showcase/adreno-sdk.

NVIDIA Tegra's x86 Windows OpenGL ES 2.0 Emulator can be found at http://developer.download.nvidia.com/tegra/files/win_x86_es2emu_v100.msi.

Compiling and using dynamic and static libraries

The main difference between dynamic and static libraries is how they are shared in applications. Dynamic libraries (or shared libraries) allow many programs to use the same library at the same time, but static ones don't.

By default, OSG generates dynamic libraries such as libosg.so under Linux or osg.dll under Windows. The executable only record required routines in a library and all actual modules will be loaded at runtime. This enables multiple executables to make use of only one library, rather than compiling the library code into each program. But it also brings disadvantages such as dependency and distribution problems.

With static linking, target executables will include every referenced part of external libraries and object files at compile time, and there will be no extra shared files. This ensures that all the dependencies are loaded with the correct version. You may not be bothered by the installation of your applications again, as end users won't complain that a DLL file not found error is not displayed while using static-linked executables.

Of course, static libraries always make the result a larger size. Fortunately, OSG provides both static and dynamic linking options. It's up to the developers to decide which would win in their case.

Getting ready

Start the cmake-gui utility. Now we are going to configure the build system to generate static or dynamic version of OSG libraries. Be careful; each time you switch between static and dynamic, the whole project including libraries, plugins, and applications will be rebuilt. So it is clever to make a static-build and a dynamic-build directory separately, if you want to update both configurations.

How to do it...

It is actually very easy to build static-link version of OSG libraries. We will assume you have already had a static-build directory for the building process.

  1. Start cmake-gui and find the DYNAMIC group. It contains two options (checked by default)— DYNAMIC_OPENTHREADS and DYNAMIC_OPENSCENEGRAPH. Unmark them and confirm your changes.

  2. That's enough! Let us generate the makefiles/solutions and start the native compilation work.

  3. After the files are installed, go to the specified path and see what you have now. You will find that there are no .so or .dll files, and all the plugins are created as static-link libraries (.a or .lib), as well as the core libraries.

There's more...

This is what we have just described before—static linking doesn't require extra shared objects any more. All modules referred to by the executable will be directly included at compiling time.

While using static-linked plugins for programming, you must add corresponding file to the dependence list, and declare them in the global scope of the source code, which forces the compiler to look for modules in external dependencies. This can be done with a USE_OSGPLUGIN() macro. Another important macros include USE_DOTOSGWRAPPER_LIBRARY(), USE_SERIALIZER_WRAPPER_LIBRARY(), and USE_GRAPHICSWINDOW(). The first two can register native OSG and OSGB formats into your executable, and the last will specify the right windowing system to use. Without dynamic loading of files and dynamic allocating of global proxy variables, OSG wasn't able to automatically check for them this time.

The example osgstaticviewer, if you enabled BUILD_OSG_EXAMPLES in the BUILD group, could be a good example for such developing instructions.

Generating the API documentation

Before we start discussing this recipe, open the following link and have a look at it:


Some of you may say: "Oh, this is a wonderful reference guide for me during the programming work. It's impossible to keep all the classes in mind, and it's really rough to search for one method or function in the vast source directory. I'd love to have such a handy API document. But how did you make it, and how do you keep it fresh?"

Believe it or not, all this documenting work could be done by automatic generators, for example, Doxygen in our case. It will parse the source code and comments in prescribed forms, and output formatted results to HTML pages, or even CHM files.

And with the well-written build scripts, OSG can create such API documentation with the Doxygen tool in a very simple way.

Getting ready

Download the Doxygen tool first, and you can generate beautiful documents from the source code. The download link is:


There is a dot utility created by the Graph Visualization Software. It can draw some types of hierarchical graphs and thus makes life more colorful. The toolkit can be found at:


Ubuntu users can install these two utilities with the apt-get command directly by running the following two command lines:

# sudo apt-get install doxygen
# sudo apt-get install graphviz

Lastly, Windows users may choose to compile a CHM file. Microsoft HTML Workshop is required in this situation. If you don't have one, download it at:


How to do it...

  1. Start the cmake-gui window. Don't worry about a completely new compilation, which may take another few hours again. This time we are going to configure options for documentation building only.

  2. Find the BUILD group and click on BUILD_DOCUMENTATION. Click on Configure for more choices.

  3. A new group named DOXYGEN appears after reconfiguring. Look into the group and ensure that the doxygen and dot executables are set properly. Windows users may have to specify the locations of doxygen.exe and dot.exe manually.

  4. Another group DOCUMENTATION is used to decide whether we should build with the option HTML_HELP (CHM file). Selecting it means we are going to compile HTML documents into a CHM file. It requires hhc.exe from the HTML Workshop as the executable.

  5. For Windows users only, set up the location of hhc.exe and the Html Help SDK library. The latter can be found in the Windows SDK distribution.

  6. The common make and make install commands won't affect the generation of API documents. Use the following commands to obtain the OpenThreads and OpenSceneGraph API documents:

    # sudo make doc_openthreads
    # sudo make doc_openscenegraph
  7. Use any browser to open the index.html file in the /doc/OpenSceneGraphReferenceDocs/ folder in your build directory. See what great work you have just done!

There's more...

If you have generated Visual Studio solution files, find the sub-project DoxygenDoc and build it separately. The ALL_BUILD and INSTALL projects, which must be run to compile and install all OSG libraries and applications, can never affect the compilation of documents, and vice versa. So you may build the API documents without building OSG.


Interested in the generation of API documents? Or do you want your own project to be documented in such an automatic process too? Change your commenting habit from now on. Doxygen will try to recognize some special forms of comments and create great-looking and practical reference manuals for you. See the link below for more details:


Creating your own project using CMake

Now, you may have a question like the following—since CMake is a really powerful tool for constructing self-adaptive build systems, is it possible that I could make use of it?

In this recipe, we will create a small enough script file, in which we will design the compilation strategy of a small project with several source files. Our goal is to detect the OSG installation, set up the include directory, and link libraries to the project, and finally generate an executable file in the user-defined path. This build script (in fact only one CMakeLists.txt file) will be used throughout this book.


Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Getting ready

While CMake and the OpenSceneGraph libraries are all installed, you don't have to prepare anything before writing scripts. Open a text editor, such as Visual Studio, UltraEdit, or even Notepad! Make a new folder for your project; save the script file as .txt and go ahead.

How to do it...

Let us start coding in a plain text file named CMakeLists.txt. The name must not be changed because CMake will use it for parsing scripts.

  1. Set the common parts of the script, including the project name, postfix of Debug outputs, and CMake version configurations:

    SET(CMAKE_DEBUG_POSTFIX "d" CACHE STRING "add a postfix for Debug mode, usually d on windows")
    # set cmake policy
  2. Add necessary definitions and C++ compiling flags as you wish:

    SET(CMAKE_CXX_FLAGS "-W -Wall -Wno-unused")
  3. Find and set the OpenSceneGraph to include the directory and library path in some predicted locations, which will be used as external dependencies of your application. If not found, users who configure the CMake options of your project must specify them manually to make the generator work.

    # find include directory by looking for certain header file
    # find library directory by looking for certain library file
    # apply them to following projects
  4. Set up your own project files here. We would just take osggeometry.cpp as an example. It can be located at examples/osggeometry of the OpenSceneGraph source code. Just copy the .cpp file to your project's folder:

    SET(EXAMPLE_NAME cookbook_01_01)
    SET(EXAMPLE_FILES osggeometry.cpp)
  5. Link necessary OSG libraries to the project. The library path is already set before so we don't have to specify the exact file path again. We also want to install the executable to specified directory after build. So here is the installing script too:

    debug osg${CMAKE_DEBUG_POSTFIX} optimized osg
    debug osgUtil${CMAKE_DEBUG_POSTFIX} optimized osgUtil
    debug osgViewer${CMAKE_DEBUG_POSTFIX} optimized osgViewer
    debug osgDB${CMAKE_DEBUG_POSTFIX} optimized osgDB
    debug osgGA${CMAKE_DEBUG_POSTFIX} optimized osgGA
    debug OpenThreads${CMAKE_DEBUG_POSTFIX} optimized OpenThreads
  6. Now use cmake-gui to open it and generate the makefiles or solution files as below. Now we have a cool enough framework for creating cross-platform applications in the following chapters!

How it works...

Unfortunately, we don't have space to introduce CMake variables, functions, and grammars. It really requires some hundred pages to make you a CMake expert. Besides the CMake official website, the OSG source code also provides some good code snippets. And you may find a large amount of other information on the Internet, simply using CMake or CMakeLists as the searching keyword.

The book "Mastering CMake", Ken Martin and Bill Hoffman, Kitware, Inc., is also valuable for reading.