Time for action—say "Hello World" OSG style
Can't wait to have a taste of OSG programming? Here is the simplest example, which shows how to load an existing model file and render it on the screen. It is much more interesting than just printing a "Hello World" text on the console:
- Create a new project with any source code editor:
#include <osgDB/ReadFile> #include <osgViewer/Viewer> int main( int argc, char** argv ) { osgViewer::Viewer viewer; viewer.setSceneData( osgDB::readNodeFile("cessna.osg") ); return viewer.run(); }
- Specify the OSG header location and dependent libraries. You need to tell the linker to link your project with five libraries: OpenThreads, osg, osgDB, osgUtil, and osgViewer. You will learn more about configuring an OSG application in the next chapter.
- Build your project. Make sure the file
cessna.osg
already exists in the same directory as the executable file, or in the path specified with the OSG_FILE_PATH environment variable. - Check it out! You get a full-screen display with a flight model shown in the middle:
- Try to make some changes to what you are observing simply with your mouse. Press and hold the left, middle, and right mouse buttons when you are moving the mouse, to rotate, move, and scale the Cessna. Note that you are not actually modifying the model but changing the virtual view point instead.
What just happened?
An easy-to-read example was just created to show how powerful and clear OSG is. The osgDB::readNodeFile()
function is used to read an existing node file, that is, a scene graph that represents the Cessna model. The osgViewer::Viewer
instance is then created to set the scene data and provide a simulation loop for the application.
Here, osgDB and osgViewer are namespaces, and Viewer is a class name. The naming style of a function or class member uses the same convention as the famous "camel-case", that is, the first word of the function name starts with a lowercase letter, and additional ones start with upper-case letters.