
\begin{DoxyItemize}
\item Getting Started
\begin{DoxyItemize}
\item \hyperlink{building-ogre}{Guide to building O\+G\+RE}
\item \hyperlink{setup}{Setting up an O\+G\+RE project}
\item \hyperlink{tut_FirstScene}{Your First Scene}
\item \hyperlink{tut_LightsCamerasShadows}{Lights, Cameras, and Shadows}
\item \hyperlink{working-with-numpy}{Working with Num\+Py}
\end{DoxyItemize}
\item Components
\begin{DoxyItemize}
\item \hyperlink{trays}{Trays G\+UI System}
\item \hyperlink{volume}{Volume Component}
\end{DoxyItemize}
\item In Depth
\begin{DoxyItemize}
\item \hyperlink{manual-mesh-creation}{Manual mesh creation}
\item \hyperlink{profiler}{Using the Profiler}
\item \hyperlink{External-Texture-Sources}{External Texture Sources}
\item \hyperlink{ShadowMappingOgre}{Shadow Mapping in Ogre}
\item \hyperlink{deferred}{Deferred Shading}
\item \hyperlink{pczscenemanager}{Using the P\+CZ Scene Manager} 
\end{DoxyItemize}
\end{DoxyItemize}\hypertarget{building-ogre}{}\section{Guide to building O\+G\+RE}\label{building-ogre}
\hyperlink{namespace_ogre}{Ogre} uses \href{https://cmake.org/}{\tt C\+Make} as its build system on all supported platforms. This guide will explain to you how to use C\+Make to build \hyperlink{namespace_ogre}{Ogre} from source. You need a C\+Make version $>$= 3.\+3.

\subsection*{What is C\+Make? }

C\+Make is a cross-\/platform build system -\/ or perhaps more accurately a build configurator. It is a program which, from a set of C\+Make scripts, creates a native build system for your platform that allows you to build \hyperlink{namespace_ogre}{Ogre}. The build process is configurable via C\+Make. \hyperlink{namespace_ogre}{Ogre} provides several options which you can use to customise your build.

\subsection*{Preparing the build environment }

You should now create a build directory for \hyperlink{namespace_ogre}{Ogre} somewhere outside \hyperlink{namespace_ogre}{Ogre}\textquotesingle{}s sources. This is the directory where C\+Make will create the build system for your chosen platform and compiler, and this is also where the \hyperlink{namespace_ogre}{Ogre} libraries will be compiled. This way, the \hyperlink{namespace_ogre}{Ogre} source dir stays clean, and you can have multiple build directories all working from the same \hyperlink{namespace_ogre}{Ogre} source.

\subsection*{Getting dependencies }

By default ogre will build the essential dependencies automatically when you run cmake the first time. If you would rather use system wide libraries set {\ttfamily O\+G\+R\+E\+\_\+\+B\+U\+I\+L\+D\+\_\+\+D\+E\+P\+E\+N\+D\+E\+N\+C\+I\+ES=O\+FF}.

\hyperlink{namespace_ogre}{Ogre} will install the dependencies into the subfolder {\ttfamily Dependencies} in the build dir by default. You can configure it by setting {\ttfamily O\+G\+R\+E\+\_\+\+D\+E\+P\+E\+N\+D\+E\+N\+C\+I\+E\+S\+\_\+\+D\+IR} in cmake. For instance to point to a common dependencies folder for all of your projects. Inside this directory you must have the subdirectories bin, lib and include where you place .dll, .lib and header files of the dependencies, respectively

On linux you additionally need the following system headers to build the GL Render\+Systems (command for Ubuntu)\+: \begin{DoxyVerb}sudo apt-get install libgles2-mesa-dev libxt-dev libxaw7-dev
\end{DoxyVerb}


furthermore we recommend installing the following optional packages \begin{DoxyVerb}sudo apt-get install nvidia-cg-toolkit libsdl2-dev doxygen
\end{DoxyVerb}


these will enable input handling in the Sample\+Browser and building the documentation.

If you cannot obtain prebuilt binaries of a dependency for your platform, please refer to the list below and get a source package from the website, then build it according to its documentation.

\subsubsection*{Essential dependencies\+:}


\begin{DoxyItemize}
\item freetype\+: \href{http://www.freetype.org}{\tt http\+://www.\+freetype.\+org}
\end{DoxyItemize}

\subsubsection*{Recommended dependencies\+:}


\begin{DoxyItemize}
\item zlib\+: \href{http://www.zlib.net}{\tt http\+://www.\+zlib.\+net}
\item zziplib\+: \href{https://github.com/paroj/ZZIPlib}{\tt https\+://github.\+com/paroj/\+Z\+Z\+I\+Plib}
\item S\+DL\+: \href{https://www.libsdl.org/}{\tt https\+://www.\+libsdl.\+org/}
\end{DoxyItemize}

\subsubsection*{Optional dependencies\+:}


\begin{DoxyItemize}
\item DirectX S\+DK\+: \href{http://msdn.microsoft.com/en-us/directx/}{\tt http\+://msdn.\+microsoft.\+com/en-\/us/directx/}
\item Free\+Image\+: \href{http://freeimage.sourceforge.net}{\tt http\+://freeimage.\+sourceforge.\+net}
\item Doxygen\+: \href{http://doxygen.org}{\tt http\+://doxygen.\+org}
\item Cg\+: \href{http://developer.nvidia.com/object/cg_toolkit.html}{\tt http\+://developer.\+nvidia.\+com/object/cg\+\_\+toolkit.\+html}
\item Boost\+: \href{http://www.boost.org}{\tt http\+://www.\+boost.\+org} (+)
\item P\+O\+CO\+: \href{http://pocoproject.org}{\tt http\+://pocoproject.\+org} (+)
\item T\+BB\+: \href{http://www.threadingbuildingblocks.org}{\tt http\+://www.\+threadingbuildingblocks.\+org} (+)
\end{DoxyItemize}

(+) can be used for threading instead of {\ttfamily std\+::thread}

\subsection*{Running C\+Make }

Now start the program cmake-\/gui by either typing the name in a console or selecting it from the start menu. In the field {\itshape Where is the source code} enter the path to the \hyperlink{namespace_ogre}{Ogre} source directory (the directory which contains this file). In the field {\itshape Where to build the binaries} enter the path to the build directory you created. Hit {\itshape Configure}. A dialogue will appear asking you to select a generator.

Check the \href{https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html}{\tt C\+Make documentation} for details on which one is appropriate for your platform and compiler. \begin{DoxyNote}{Note}
on O\+SX, you must to use the Xcode generator to get a proper Sample\+Browser .app bundle.
\end{DoxyNote}
Click {\itshape Finish}. C\+Make will now gather some information about your build environment and try to locate the dependencies. It will then show a list of build options. You can adjust the settings to your liking; for example unchecking any of the {\ttfamily O\+G\+R\+E\+\_\+\+B\+U\+I\+L\+D\+\_\+\+X\+XX} options will disable that particular component from being built. Once you are satisfied, hit {\itshape Configure} again and then click on {\itshape Generate}. C\+Make will then create the build system for you.

\subsection*{Building }

Go to your chosen build directory. C\+Make has generated a build system for you which you will now use to build \hyperlink{namespace_ogre}{Ogre}. If you are using Visual Studio, you should find the file O\+G\+R\+E.\+sln. Open it and compile the target {\itshape B\+U\+I\+L\+D\+\_\+\+A\+LL}. Similarly you will find an Xcode project to build \hyperlink{namespace_ogre}{Ogre} on Mac\+OS.

If you rather want to trigger the build form a console, then cd to your build directory and call the appropriate make program as \begin{DoxyVerb}cmake --build . --config release
\end{DoxyVerb}


to start the build process.

If you have doxygen installed and C\+Make picked it up, then there will be an additional build target called {\itshape Ogre\+Doc} which you can optionally build. This will freshly generate the A\+PI documentation for \hyperlink{namespace_ogre}{Ogre}\textquotesingle{}s classes from the header files. In Visual Studio, just select and build the target {\itshape Ogre\+Doc}, on Linux type\+: \begin{DoxyVerb} make OgreDoc
\end{DoxyVerb}


\subsection*{Installing }

Once the build is complete, you can optionally have the build system copy the built libraries and headers to a clean location. We recommend you do this step as it will make it easier to use \hyperlink{namespace_ogre}{Ogre} in your projects. In Visual Studio, just select and build the target {\itshape I\+N\+S\+T\+A\+LL}. For Makefile based generators, type\+:

\begin{DoxyVerb}make install  # (or sudo make install, if root privileges are required)
\end{DoxyVerb}


On Linux \hyperlink{namespace_ogre}{Ogre} will be installed to {\ttfamily /usr/local} by default. On Windows this will create the folder {\ttfamily sdk} inside your build directory and copy all the required libraries there. You can change the install location by changing the variable {\ttfamily C\+M\+A\+K\+E\+\_\+\+I\+N\+S\+T\+A\+L\+L\+\_\+\+P\+R\+E\+F\+IX} in C\+Make.

\subsection*{Building on Mac OS X for i\+OS OS }

To build \hyperlink{namespace_ogre}{Ogre} for i\+OS, you need to specify the ios cross toolchain to cmake as \begin{DoxyVerb}cmake -DCMAKE_TOOLCHAIN_FILE=CMake/toolchain/ios.toolchain.xcode.cmake -G Xcode .
\end{DoxyVerb}


Unfortunately, you will now have to do a few manual steps to make the generated build system work properly.

A Xcode project has now been generated in the build directory, so to start the \hyperlink{namespace_ogre}{Ogre} build, open O\+G\+R\+E.\+xcodeproj and build as usual. To run samples on your device you will need to have a valid i\+OS Developer certificate installed. For each sample, double click on target in the Groups \& Files list. Ensure that a valid identity is selected in the Code Signing Identity drop menu. Also, because we can\textquotesingle{}t tell C\+Make what Xcode project format you want, you will have to change it yourself. Open the Project Menu, choose Edit Project Settings. Click on the General tab in the settings window. Change Project Format to Xcode 3.\+1-\/compatible. And another thing. You will need to manually set the Bundle Identifier property of the Info.\+plist file to match the App ID of the chosen code signing identity. This can be done from the Target Properties panel. It must match the bundle identifier of a valid developer certificate if you are building for devices.

\subsection*{Building as Windows Store or Windows Phone application }

You need Windows 8.\+0 or later, Windows 10 is recommended.

You need Visual Studio 2012 or later, Visual Studio 2015 is recommended as it is bundled with Universal 10.\+0.\+240.\+0, Win\+Store 8.\+0/8.1 and Win\+Phone 8.\+0/8.1 S\+D\+Ks.

Download and install C\+Make 3.\+4 or later.

Patched dependencies must be used, compiled with appropriate W\+I\+N\+A\+P\+I\+\_\+\+F\+A\+M\+I\+LY. Cg is not supported. You can use \href{https://bitbucket.org/eugene_gff/ogre-dependencies-winrt}{\tt https\+://bitbucket.\+org/eugene\+\_\+gff/ogre-\/dependencies-\/winrt} -\/ has V\+S2012 and V\+S2013 projects for Win32, Win\+RT (can be reused for Win\+Phone) Compile dependencies for all configurations that you plan to use before running C\+Make. Dependencies for Win32 and for Win\+RT must be located in separate folders, Win32 version can be built from Ogre\+Dependencies.\+V\+S201x.\+sln, Win\+RT from Ogre\+Dependencies.\+V\+S201x.\+Win\+R\+T.\+sln

Run C\+Make, specify source and binaries folders, than \char`\"{}\+Configure\char`\"{}, select \char`\"{}\+Visual Studio 14 2015\char`\"{} generator and \char`\"{}\+Specify options for cross-\/compiling\char`\"{} option, specify Operating System = \char`\"{}\+Windows\+Store\char`\"{} or \char`\"{}\+Windows\+Phone\char`\"{}, Version = \char`\"{}8.\+0\char`\"{}, \char`\"{}8.\+1\char`\"{} or for U\+AP Operating System = \char`\"{}\+Windows\+Store\char`\"{}, Version = \char`\"{}10.\+0.\+10240.\+0\char`\"{}, \char`\"{}10.\+0.\+10586.\+0\char`\"{} then \char`\"{}\+Finish\char`\"{}, specify Win\+RT dependencies folder for O\+G\+R\+E\+\_\+\+D\+E\+P\+E\+N\+D\+E\+N\+C\+I\+E\+S\+\_\+\+D\+IR, \char`\"{}\+Configure\char`\"{}, should be no more errors, then press \char`\"{}\+Generate\char`\"{}.

Select Sample\+Browser as the start up project and run.

\subsubsection*{Notes}


\begin{DoxyEnumerate}
\item The code and generated C\+Make solution should be on local N\+T\+FS drive, and can\textquotesingle{}t be on a network drive, including V\+M\+Ware shared folders -\/ or you will get a errors when you will try to compile/link/run resulting exe.
\item \hyperlink{namespace_ogre}{Ogre} uses d3dcompiler\+\_\+xx.\+dll to compile shaders, and Win\+Store and Win\+Phone 8.\+1 projects can use it without restriction as it is part of OS. But Win\+Store and Win\+Phone 8.\+0 applications should load already compiled shaders from cache, as d3dcompiler\+\_\+xx.\+dll is available to them only during development. Therefore to avoid necessity to deploy d3dcompiler\+\_\+xx.\+dll during development (additional configurations with d3dcompiler\+\_\+xx.\+dll) and generation of such cache -\/ use version 8.\+1 of these platforms.
\item Running Win\+Phone emulator in OS running under V\+Mware\+: We were able to run the emulation and debug without an issue by using two steps\+: (a) Under the settings of the VM $>$ C\+PU, make sure you have the option to pass-\/through the Intel V\+T-\/x/\+E\+PT feature, (b) Edit the config file .vmx and add the parameter\+: hypervisor.\+cpuid.\+v0 = \char`\"{}\+F\+A\+L\+S\+E\char`\"{} All versions of Visual Studio 2012 have a window refresh issue when running in V\+Mware and the window is maximized, the solution is just to change the size of the Visual Studio window to be less the the screen width and height.
\end{DoxyEnumerate}

\subsection*{Building on Ubuntu for Android }

To build \hyperlink{namespace_ogre}{Ogre} for Android, you need to specify the ios cross toolchain to cmake as \begin{DoxyVerb}cmake -DCMAKE_TOOLCHAIN_FILE=CMake/toolchain/android.toolchain.cmake -DANDROID_NDK=path/to/android-ndk .
\end{DoxyVerb}


this will build the core \hyperlink{namespace_ogre}{Ogre} libraries. Also if your {\ttfamily P\+A\+TH} contains the {\ttfamily android} executable it will generate the Sample\+Browser A\+PK.

To manually generate the A\+PK and install it on your device, run \begin{DoxyVerb}ant debug install
\end{DoxyVerb}


\subsection*{Building for H\+T\+M\+L5 (Emscripten) }

Install the Emscripten S\+DK and make sure that the environment variables are correctly set.

Run cmake in cross compile mode using emscripten as following\+: \begin{DoxyVerb}cmake -DCMAKE_TOOLCHAIN_FILE=$EMSCRIPTEN/cmake/Modules/Platform/Emscripten.cmake .
\end{DoxyVerb}


in cmake G\+UI change {\ttfamily C\+M\+A\+K\+E\+\_\+\+AR} to {\ttfamily emcc}. Then run {\ttfamily make}.

this will not build the full Sample\+Browser, but just a minimal Sample. The resulting {\ttfamily Emscripten\+Sample.\+html} will be placed in {\ttfamily \$\{C\+M\+A\+K\+E\+\_\+\+B\+I\+N\+A\+R\+Y\+\_\+\+D\+IR\}/bin/}.

To prevent any cross-\/origin issues, start a local webserver as {\ttfamily python3 -\/m http.\+server 8000} and visit {\ttfamily localhost\+:8000}. \hypertarget{setup}{}\section{Setting up an O\+G\+RE project}\label{setup}
\begin{DoxyNote}{Note}
see \hyperlink{building-ogre}{Guide to building O\+G\+RE} for instructions how to build O\+G\+RE itself 
\end{DoxyNote}
\hypertarget{setup_cmake}{}\subsection{C\+Make Configuration}\label{setup_cmake}
\hyperlink{namespace_ogre}{Ogre} uses C\+Make as its build system. It is recommended that you use it in your project as well. Then all you need is to add the following lines to your project 
\begin{DoxyCodeInclude}
\textcolor{comment}{# specify which version and components you need}
find\_package(OGRE 1.11 REQUIRED COMPONENTS Bites RTShaderSystem)

\textcolor{comment}{# copy resource.cfg next to our binaries where OGRE looks for it}
file(COPY $\{OGRE\_CONFIG\_DIR\}/resources.cfg DESTINATION $\{CMAKE\_BINARY\_DIR\})
\end{DoxyCodeInclude}
These settings include all available components and third party libraries O\+G\+RE depends on (e.\+g. boost) -\/ nothing more to do.

If you installed O\+G\+RE in a non-\/standard path, you will have to set {\ttfamily O\+G\+R\+E\+\_\+\+D\+IR} to the location of {\ttfamily O\+G\+R\+E\+Config.\+cmake} so {\ttfamily find\+\_\+package} can figure out the rest.

For inspecting the detected O\+G\+RE installation, the following C\+Make variables are available
\begin{DoxyItemize}
\item {\ttfamily O\+G\+R\+E\+\_\+\+S\+T\+A\+T\+IC} -\/ whether ogre was build as static lib
\item {\ttfamily O\+G\+R\+E\+\_\+\$\{C\+O\+M\+P\+O\+N\+E\+NT\}\+\_\+\+F\+O\+U\+ND} -\/ \$\{C\+O\+M\+P\+O\+N\+E\+NT\} is available
\item {\ttfamily O\+G\+R\+E\+\_\+\+P\+L\+U\+G\+I\+N\+\_\+\+D\+IR} -\/ The directory where the O\+G\+RE plugins are located
\item {\ttfamily O\+G\+R\+E\+\_\+\+M\+E\+D\+I\+A\+\_\+\+D\+IR} -\/ The directory where the O\+G\+RE sample media is located
\item {\ttfamily O\+G\+R\+E\+\_\+\+C\+O\+N\+F\+I\+G\+\_\+\+D\+IR} -\/ The directory where the O\+G\+RE config files are located
\end{DoxyItemize}\hypertarget{setup_skeleton}{}\subsection{Application skeleton}\label{setup_skeleton}
The easiest way to get started is the \hyperlink{namespace_ogre_bites}{Ogre\+Bites} Component. It handles \hyperlink{namespace_ogre}{Ogre} startup/ tear down (including \hyperlink{class_ogre_1_1_overlay}{Ogre\+::\+Overlay}, \hyperlink{rtss}{R\+T\+SS}), input using S\+D\+L2 and even includes a \hyperlink{trays}{Simple G\+UI System}.

This is useful if all you want is to get a Scene with a F\+PS counter up and running (rapid prototyping). If available it also uses S\+D\+L2 for input -\/ you now just have to implement the callbacks.

To use it, simply derive from \hyperlink{class_ogre_bites_1_1_application_context}{Ogre\+Bites\+::\+Application\+Context} and if you want to get input events from \hyperlink{struct_ogre_bites_1_1_input_listener}{Ogre\+Bites\+::\+Input\+Listener}


\begin{DoxyCode}
\textcolor{keyword}{class }MyTestApp : \textcolor{keyword}{public} \hyperlink{class_ogre_bites_1_1_application_context}{OgreBites::ApplicationContext}, \textcolor{keyword}{public} 
      \hyperlink{struct_ogre_bites_1_1_input_listener}{OgreBites::InputListener}
\{
    ...
\}
\end{DoxyCode}
 in the constructor we set our application name. The ogre configuration files will be stored in a system dependant location specific to our app. 
\begin{DoxyCodeInclude}
MyTestApp::MyTestApp() : \hyperlink{namespace_ogre_bites}{OgreBites}::ApplicationContext(\textcolor{stringliteral}{"OgreTutorialApp"})
\{
\}
\end{DoxyCodeInclude}
 to handle input events, we then override the according method 
\begin{DoxyCodeInclude}
\textcolor{keywordtype}{bool} MyTestApp::keyPressed(\textcolor{keyword}{const} \hyperlink{struct_ogre_bites_1_1_keyboard_event}{OgreBites::KeyboardEvent}& evt)
\{
    \textcolor{keywordflow}{if} (evt.\hyperlink{struct_ogre_bites_1_1_keyboard_event_a675789f0663c8e7c8ac38db339a98a60}{keysym}.\hyperlink{struct_ogre_bites_1_1_keysym_a0174848a10c2790beb05a3f21317a5c3}{sym} == \hyperlink{namespace_ogre_bites_aa3f92c9c582664d88fe3d488fb9b16e1a02467a4c39b543a4c53cbfd192837cfc}{OgreBites::SDLK\_ESCAPE})
    \{
        getRoot()->queueEndRendering();
    \}
    \textcolor{keywordflow}{return} \textcolor{keyword}{true};
\}
\end{DoxyCodeInclude}
 the interesting part however is the setup method 
\begin{DoxyCodeInclude}
\textcolor{keywordtype}{void} MyTestApp::setup(\textcolor{keywordtype}{void})
\{
    \textcolor{comment}{// do not forget to call the base first}
    \hyperlink{class_ogre_bites_1_1_application_context_ad2bfdfa72c9d95e55657854c2094c610}{OgreBites::ApplicationContext::setup}();
    
    \textcolor{comment}{// register for input events}
    addInputListener(\textcolor{keyword}{this});

    \textcolor{comment}{// get a pointer to the already created root}
    \hyperlink{class_ogre_1_1_root}{Ogre::Root}* root = getRoot();
    \hyperlink{class_ogre_1_1_scene_manager}{Ogre::SceneManager}* scnMgr = root->\hyperlink{class_ogre_1_1_root_a8bb8655f823a98007775f69278c1b0f9}{createSceneManager}();

    \textcolor{comment}{// register our scene with the RTSS}
    \hyperlink{class_ogre_1_1_r_t_shader_1_1_shader_generator}{Ogre::RTShader::ShaderGenerator}* shadergen = 
      \hyperlink{class_ogre_1_1_r_t_shader_1_1_shader_generator_acd96bb2cad55be69d0fe8c6dc28d3590}{Ogre::RTShader::ShaderGenerator::getSingletonPtr}();
    shadergen->\hyperlink{class_ogre_1_1_r_t_shader_1_1_shader_generator_a60704776c069e2a6bd37692f88c56815}{addSceneManager}(scnMgr);

    \textcolor{comment}{// without light we would just get a black screen    }
    \hyperlink{class_ogre_1_1_light}{Ogre::Light}* light = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}(\textcolor{stringliteral}{"MainLight"});
    \hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}* lightNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    lightNode->\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}(0, 10, 15);
    lightNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(light);

    \textcolor{comment}{// also need to tell where we are}
    \hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}* camNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    camNode->\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}(0, 0, 15);
    camNode->\hyperlink{class_ogre_1_1_scene_node_a665c4750906917dd061b141c03d432de}{lookAt}(\hyperlink{class_ogre_1_1_vector3}{Ogre::Vector3}(0, 0, -1), 
      \hyperlink{class_ogre_1_1_node_ac42e2063379286eb673eaffff6ca5e99a34e6c3ebabc2e9fa00de4f62be0ce7ce}{Ogre::Node::TS\_PARENT});

    \textcolor{comment}{// create the camera}
    \hyperlink{class_ogre_1_1_camera}{Ogre::Camera}* cam = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a62ca781b4c6d23dc3aab1f3a45d61843}{createCamera}(\textcolor{stringliteral}{"myCam"});
    cam->\hyperlink{class_ogre_1_1_frustum_a7bc8b601d85642059f23e739fb4438bb}{setNearClipDistance}(5); \textcolor{comment}{// specific to this sample}
    cam->\hyperlink{class_ogre_1_1_camera_aac250bb57c630543b8241bfc8eb8b88a}{setAutoAspectRatio}(\textcolor{keyword}{true});
    camNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(cam);

    \textcolor{comment}{// and tell it to render into the main window}
    getRenderWindow()->addViewport(cam);

    \textcolor{comment}{// finally something to render}
    \hyperlink{class_ogre_1_1_entity}{Ogre::Entity}* ent = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"Sinbad.mesh"});
    \hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}* node = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    node->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(ent);
\}
\end{DoxyCodeInclude}
\begin{DoxyNote}{Note}
The above code is explained in detail in \hyperlink{tut_FirstScene}{Your First Scene}.
\end{DoxyNote}
finally we start everything as 
\begin{DoxyCodeInclude}
\textcolor{keywordtype}{int} main(\textcolor{keywordtype}{int} argc, \textcolor{keywordtype}{char} *argv[])
\{
    MyTestApp app;
    app.initApp();
    app.getRoot()->startRendering();
    app.closeApp();
    \textcolor{keywordflow}{return} 0;
\}
\end{DoxyCodeInclude}
\begin{DoxyNote}{Note}
You can find the full code of the above example at
\begin{DoxyItemize}
\item {\ttfamily Samples/\+Tutorials/\+Bootstrap.\+cpp} for C++
\item {\ttfamily Samples/\+Python/bites\+\_\+sample.\+py} for Python
\item {\ttfamily Samples/\+Android\+J\+N\+I/\+Main\+Activity.\+java} for Java (Android)
\end{DoxyItemize}
\end{DoxyNote}
\hyperlink{namespace_ogre_bites}{Ogre\+Bites} itself is also a good starting point if you need more control over the Camera or the Window creation. For instance to render into an existing Qt Window.

\begin{DoxySeeAlso}{See also}
\hyperlink{class_ogre_1_1_root_aeaad25268c0ad8007ce8961a32242c77}{Ogre\+::\+Root\+::render\+One\+Frame} 

\hyperlink{class_ogre_1_1_render_system_aaf156b9f935396e6c17f532f6e6c847e}{Ogre\+::\+Render\+System\+::\+\_\+create\+Render\+Window} 

\hyperlink{class_ogre_1_1_render_system_a77766da49c29112c390fde51069f543a}{Ogre\+::\+Render\+System\+::pre\+Extra\+Threads\+Started} 
\end{DoxySeeAlso}
\hypertarget{tut_FirstScene}{}\section{Your First Scene}\label{tut_FirstScene}
This first tutorial will cover the basic elements of building a scene in \hyperlink{namespace_ogre}{Ogre}. The primary focus will be the \hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}, \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}, and Entity(external link). An \hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity} is anything represented by a mesh. A \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node} is what attaches an object to your scene. Finally, the Scene\+Manager is the object that organizes everything. It keeps track of the entities and nodes in your scene and determines how to display them.

We\textquotesingle{}ll start with an explanation of some of the basic concepts in \hyperlink{namespace_ogre}{Ogre}. Don\textquotesingle{}t worry, this first tutorial has a little more explanation than the rest, but that changes very quickly once you get to the later tutorials. We will be building plenty of things. We just have to lay a little groundwork first, so you have somewhere to stand.

The full source for this tutorial (Basic\+Tutorial1.\+cpp) can be found in samples directory {\bfseries Samples/\+Tutorials}.

\begin{DoxyNote}{Note}
Refer to \hyperlink{setup}{Setting up an O\+G\+RE project} for instructions how set up an \hyperlink{namespace_ogre}{Ogre} project and compile it successfully.
\end{DoxyNote}
\hypertarget{tut__first_scene_howogreworks}{}\subsection{How Ogre Works}\label{tut__first_scene_howogreworks}
We are going to provide a quick introduction to the basic elements of an \hyperlink{namespace_ogre}{Ogre} scene.\hypertarget{tut__first_scene_scenemanager}{}\subsubsection{Scene\+Manager}\label{tut__first_scene_scenemanager}
Everything that appears on the screen is managed by the Scene\+Manager. The Scene\+Manager keeps track of the locations and other attributes of the objects in your scene. The Scene\+Manager also manages any cameras that you add to your scene. There are multiples types of Scene\+Managers. There are managers focused on rendering terrain and other managers focused on rendering B\+SP maps. The different types of Scene\+Manager are listed \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=SceneManagersFAQ}{\tt here}.\hypertarget{tut__first_scene_SceneNode}{}\subsubsection{Scene\+Node}\label{tut__first_scene_SceneNode}
Scene\+Nodes carry information that is used for all of the objects that are attached to it. An Entity is not rendered in your scene until it is attached to a Scene\+Node. In addition, a Scene\+Node is not a visible object in your scene. It only holds abstract information like location and orientation. Only when it is connected to something like an Entity is that information used to actually render something in the scene.

Scene\+Nodes can have more than one object attached to them. We may want to have a light that will follow a character around in a scene. To do this, we could attach both the character Entity and the light to the same Scene\+Node. This will cause them both to share the same location information. We can even attach Scene\+Nodes to other Scene\+Nodes. This is useful in many circumstances. Imagine you have a character and you want to attach a tool to their hand. You wouldn\textquotesingle{}t want to attach the tool to Scene\+Node for the entire character. Instead, you could attach a Scene\+Node representing their hand to the character\textquotesingle{}s main Scene\+Node, and then attach the tool Entity to that \char`\"{}child\char`\"{} Scene\+Node. more complicated uses of Scene\+Nodes will be covered in later tutorials.

One final thing to keep in mind about Scene\+Nodes is that their position is relative to their parent Scene\+Node and each Scene\+Manager creates a root Node to which all other Scene\+Nodes are attached.\hypertarget{tut__first_scene_Entity}{}\subsubsection{Entity}\label{tut__first_scene_Entity}
An Entity is one type of object that you can render in your scene. It is anything that is represented by a 3D mesh. Even terrain objects are very large entities. Lights, Billboards, Particles, and Cameras are examples of scene elements that are not entities. \hyperlink{namespace_ogre}{Ogre} uses a well-\/known design pattern that separates renderable objects from information like their location. This means that you don\textquotesingle{}t directly place an Entity into your scene. Instead, you place a Scene\+Node into your scene, then attach your Entity to that Scene\+Node. The Entity is then rendered using information taken from the Scene\+Node.\hypertarget{tut__first_scene_SettingUptheScene}{}\subsection{Setting Up the Scene}\label{tut__first_scene_SettingUptheScene}
It\textquotesingle{}s finally time to start building something in our scene. All source addition will be in \char`\"{}tutorial section\char`\"{} in cpp file of the tutorial Tutorial\+Application\+::setup method.

The first thing we want to do is turn on the lights.


\begin{DoxyCodeInclude}
    scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a7c26cdbb5703cf10a99add1f6a930ca2}{setAmbientLight}(ColourValue(0.5, 0.5, 0.5));
\end{DoxyCodeInclude}
 The set\+Ambient\+Light method takes an \hyperlink{class_ogre_1_1_colour_value}{Ogre\+::\+Colour\+Value}. The three values represent the red, green, and blue values of the colour, and they range between 0 and 1.

scn\+Mgr is a variable that is defined in \hyperlink{class_ogre_bites_1_1_application_context}{Ogre\+Bites\+::\+Application\+Context}. There are a number of features avariables, like setting up resources and initialization of required routines for rendering. They will be introduced as we need them.

Lights will be covered in detail in the next tutorial, but we will still add a simple one to this scene as a teaser. New Light objects can also be requested from the \hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}. We give the Light a unique name when it is created.


\begin{DoxyCodeInclude}
    Light* light = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}(\textcolor{stringliteral}{"MainLight"});
    SceneNode* lightNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    lightNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(light);
\end{DoxyCodeInclude}
 Starting from \hyperlink{namespace_ogre}{Ogre} 1.\+10 camera and lights require to create separate scene node for them so that they need to be attached to them.

Once the Light is created and attached to its Scene\+Node, we set its position. The three parameters are the x, y, and z coordinates of the location we want to place the Light.


\begin{DoxyCodeInclude}
    lightNode->setPosition(20, 80, 50);
\end{DoxyCodeInclude}
 Next step is to create a camera.


\begin{DoxyCodeInclude}
    SceneNode* camNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();

    \textcolor{comment}{// create the camera}
    Camera* cam = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a62ca781b4c6d23dc3aab1f3a45d61843}{createCamera}(\textcolor{stringliteral}{"myCam"});
    cam->\hyperlink{class_ogre_1_1_frustum_a7bc8b601d85642059f23e739fb4438bb}{setNearClipDistance}(5); \textcolor{comment}{// specific to this sample}
    cam->setAutoAspectRatio(\textcolor{keyword}{true});
    camNode->attachObject(cam);
    camNode->setPosition(0, 0, 140);

    \textcolor{comment}{// and tell it to render into the main window}
    getRenderWindow()->addViewport(cam);
\end{DoxyCodeInclude}
 Details about camera will be covered in the following tutorial.

The next thing we do is ask the Scene\+Manager to create an Entity.


\begin{DoxyCodeInclude}
    Entity* ogreEntity = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"ogrehead.mesh"});
\end{DoxyCodeInclude}
 The parameter given to this function must be a mesh that was loaded by \hyperlink{namespace_ogre}{Ogre}\textquotesingle{}s resource manager. For now, resource loading is one of the many things that \hyperlink{class_ogre_bites_1_1_application_context}{Ogre\+Bites\+::\+Application\+Context} is taking care of for us. It will be explained further in later tutorials.

Now that we have an Entity, we need to create a Scene\+Node so the Entity can be displayed in our scene. Every Scene\+Manager has a root node. That node has a method called create\+Child\+Scene\+Node that will return a new Scene\+Node attached to the root. In older versions of \hyperlink{namespace_ogre}{Ogre}, you were required to provide a unique name for your Entities and Scene\+Nodes. This is now optional. \hyperlink{namespace_ogre}{Ogre} will generate names for them if you do not provide one.


\begin{DoxyCodeInclude}
    SceneNode* ogreNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
\end{DoxyCodeInclude}
 We save the Scene\+Node pointer that is returned by the method so that we can attach our Entity to it.


\begin{DoxyCodeInclude}
    ogreNode->attachObject(ogreEntity);
\end{DoxyCodeInclude}
 We now have a basic scene set up. Compile and run your application. You should see an \hyperlink{namespace_ogre}{Ogre}\textquotesingle{}s head on your screen. This is only the beginning...

\hypertarget{tut__first_scene_CoordinatesSystems}{}\subsection{Coordinates Systems}\label{tut__first_scene_CoordinatesSystems}
Before we go on, let\textquotesingle{}s cover some basics of \hyperlink{namespace_ogre}{Ogre}\textquotesingle{}s coordinate system. \hyperlink{namespace_ogre}{Ogre}, like many other graphics engines, uses the x-\/z plane as the \char`\"{}floor\char`\"{} in a scene. This means that the y-\/axis is the vertical axis to ensure \hyperlink{namespace_ogre}{Ogre} is using a \href{http://mathworld.wolfram.com/Right-HandedCoordinateSystem.html}{\tt right-\/handed coordinate system}



The x-\/axis starts with negative values to the left and increases to the right (passing through zero at the origin). The z-\/axis runs forwards and backwards. The positive direction of the z-\/axis points \char`\"{}out of the screen\char`\"{}. So if a character walks towards the screen, then its z value will be increasing. Finally, the y-\/axis runs from the bottom to the top. Values that are \char`\"{}below ground\char`\"{} are negative. Don\textquotesingle{}t take these terms in parenthesis literally. You can put the ground wherever you want. It is just to help you orient yourself in the scene.

When you run your application, notice how your \hyperlink{namespace_ogre}{Ogre} head is facing towards the camera down the positive z-\/axis. This is a property of the mesh itself and the orientation of the camera. Cameras are covered in a later tutorial. The \hyperlink{namespace_ogre}{Ogre} head is sitting at the origin of our world, (0, 0, 0). The direction the head is facing by default is a result of which way it was facing when it was originally modeled. You can effectively change this from within \hyperlink{namespace_ogre}{Ogre} as well, but it will require some knowledge of quaternions, which aren\textquotesingle{}t really covered until the \href{#}{\tt Intermediate Tutorials}.

\hyperlink{namespace_ogre}{Ogre} uses a vector class to represent positions and directions. There are vectors defined for 2-\/4 dimensions. They are called \hyperlink{class_ogre_1_1_vector2}{Ogre\+::\+Vector2}, \hyperlink{class_ogre_1_1_vector3}{Ogre\+::\+Vector3}, and \hyperlink{class_ogre_1_1_vector4}{Ogre\+::\+Vector4} -\/ Vector3 being the most commonly used by far. If you are not familiar with the concept of vectors it is highly recommended to learn a little before attempting these tutorials. Even though \hyperlink{namespace_ogre}{Ogre} is an abstraction over many of the complications involved with Open\+GL and DirectX, there is still no escaping some mathematical concepts. Vectors and basic linear algebra will be some of the most useful things you can learn if you intend to proceed with 3D rendering. This \href{http://www.wildbunny.co.uk/blog/vector-maths-a-primer-for-games-programmers/}{\tt site} has produced a nice primer on vectors focused on game programmers.\hypertarget{tut__first_scene_AddingAnotherEntity}{}\subsection{Adding Another Entity}\label{tut__first_scene_AddingAnotherEntity}
It\textquotesingle{}s time to get back to the coding. With our first Entity, we did not specify the location we wanted anywhere. Many of the functions in \hyperlink{namespace_ogre}{Ogre} have default parameters. The Scene\+Node\+::create\+Child\+Scene\+Node(external link) method can take three parameters, but we called it with none. The parameters are the name, position, and rotation of the Scene\+Node being created. We\textquotesingle{}ve already mentioned that \hyperlink{namespace_ogre}{Ogre} generates a unique name for us. It also uses (0, 0, 0) as a default position.

First, let\textquotesingle{}s move the camera so we can fit more Entities on screen. Place this call right after you set the ambient light in create\+Scene\+:


\begin{DoxyCodeInclude}
    camNode->setPosition(0, 47, 222);
\end{DoxyCodeInclude}
 Now, let\textquotesingle{}s create another Entity and Scene\+Node, but this time we\textquotesingle{}ll give it a new position.


\begin{DoxyCodeInclude}
    Entity* ogreEntity2 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"ogrehead.mesh"});
    SceneNode* ogreNode2 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}(Vector3(84, 48, 0));
    ogreNode2->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(ogreEntity2);
\end{DoxyCodeInclude}
 This is the same thing we did the first time, except we are now providing a Vector3 to our create\+Child\+Scene\+Node method. This will override the default position. Remember, the Scene\+Node\textquotesingle{}s position is always relative to its parent. In this case, the parent Scene\+Node is the root Scene\+Node, which is positioned at (0, 0, 0) by default.

Compile and run your application. Your \hyperlink{namespace_ogre}{Ogre} head should have a buddy.

\hypertarget{tut__first_scene_MoreAboutEntities}{}\subsection{More About Entities}\label{tut__first_scene_MoreAboutEntities}
The \hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity} class is very extensive. We will now introduce just a few more of its methods that will be useful. The Entity class has set\+Visible and is\+Visible methods. If you want an Entity to be hidden, but you still need it later, then you can use this function instead of destroying the Entity and rebuilding it later.

\begin{DoxyNote}{Note}
Entities do not need to be pooled like they are in some graphics engines. Only one copy of each mesh and texture is ever loaded into memory, so there is not a big savings from trying to minimize the number of Entities.
\end{DoxyNote}
The get\+Name method returns the name of an Entity, and the get\+Parent\+Scene\+Node method returns the Scene\+Node that the Entity is attached to. In our case, this would be the root Scene\+Node.\hypertarget{tut__first_scene_MoreAboutSceneNodes}{}\subsection{More About Scene\+Nodes}\label{tut__first_scene_MoreAboutSceneNodes}
The \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node} class is very complex. For now, we will only cover some of the most useful methods.

You can set the position after creating the node with set\+Position. This is still relative to its parent node. You can move an objective relative to its current position by using translate.

Scene\+Nodes are used to set a lot more than just position. They also manage the scale and rotation of objects. You can set the scale of an object with set\+Scale. And you can use yaw, pitch, and roll to set the object\textquotesingle{}s orientation. You can use reset\+Rotation to return the object to its default orientation. Finally, you can use rotate to perform more complicated rotations. This will again involve the use of quaternions, which will not be covered until the \href{#}{\tt Intermediate Tutorials}.

We\textquotesingle{}ve already used the attach\+Object method of a Scene\+Node. There are few more methods that are useful for dealing with the objects that are attached to a Scene\+Node. You can use num\+Attached\+Objects to return the number of children attached to your node. You can use one of the many versions of \hyperlink{class_ogre_1_1_scene_node_a2ff8d20961b48225690e1561bc39f993}{Ogre\+::\+Scene\+Node\+::get\+Attached\+Object} to retrieve one of the Scene\+Node\textquotesingle{}s children. The method detach\+Object can be used to remove a specific child node, and detach\+All\+Objects can be used to remove all.

Since the position of a child node is relative to its parent, it makes it very easy to move large groups of nodes together. For example, if we changed this line\+:


\begin{DoxyCode}
\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}* ogreNode2 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}(\hyperlink{class_ogre_1_1_vector3}{Ogre::Vector3}(84, 48, 0));
\end{DoxyCode}


To this\+:


\begin{DoxyCode}
\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode}* ogreNode2 = ogreNode->\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}(
      \hyperlink{class_ogre_1_1_vector3}{Ogre::Vector3}(84, 48, 0));
\end{DoxyCode}


Then our new node would be parented directly to the Scene\+Node for our first Entity. This would mean that moving ogre\+Node would also move ogre\+Node2. It would also mean that the position of ogre\+Node2 would be relative to ogre\+Node.

If you\textquotesingle{}re having trouble with the idea of a relative location, then maybe an example will help. Let\textquotesingle{}s say we put our first node, ogre\+Node, at (10, 10, 10) and attach ogre\+Node2 directly to ogre\+Node. Then we set the position of ogre\+Node2 to be (-\/10, -\/10, -\/10). To figure out where ogre\+Node2 will be displayed we add its position to the position of its parent.


\begin{DoxyCode}
(10, 10, 10) + (-10, -10, -10) = (0, 0, 0)
  ogreNode        ogreNode2
   parent           child
\end{DoxyCode}


So this means that ogre\+Node2 would actually be placed at (0, 0, 0) in our world, even though we set its position to (-\/10, -\/10, -\/10). If we detached this node and reattached it to the root Scene\+Node, then it would really be displayed at (-\/10, -\/10, -\/10), because\+:


\begin{DoxyCode}
(0, 0, 0) + (-10, -10, -10) = (-10, -10, -10)
   root        ogreNode2
  parent         child
\end{DoxyCode}


Take a few seconds to soak this in. Relativity is hard. That\textquotesingle{}s why it took an Einstein to really figure it out.

Lastly, you can get a Scene\+Node or Entity by its name (if you gave it one), by calling get\+Scene\+Node or get\+Entity, which are \hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager} methods. This way you don\textquotesingle{}t have to keep a pointer to all of your Scene\+Nodes. You should generally only define pointers for nodes you will use often.\hypertarget{tut__first_scene_ChangingAnEntitysScale}{}\subsection{Changing An Entity\textquotesingle{}s Scale}\label{tut__first_scene_ChangingAnEntitysScale}
We can set the scale of an Entity by calling set\+Scale. This method allows us to provide a scale factor for each dimension. Let\textquotesingle{}s add another \hyperlink{namespace_ogre}{Ogre} head and give it a different scale for demonstration. We will also position it so it fits well on the screen.


\begin{DoxyCodeInclude}
    Entity* ogreEntity3 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"ogrehead.mesh"});
    SceneNode* ogreNode3 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    ogreNode3->\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}(0, 104, 0);
    ogreNode3->setScale(2, 1.2, 1);
    ogreNode3->attachObject(ogreEntity3);
\end{DoxyCodeInclude}
 Compile and run your application. You should see a fat \hyperlink{namespace_ogre}{Ogre} head up top.

\hypertarget{tut__first_scene_RotatingAnEntity}{}\subsection{Rotating An Entity}\label{tut__first_scene_RotatingAnEntity}
An Entity\textquotesingle{}s rotation can be changed using the yaw, pitch, and roll methods.



These methods will take either an \hyperlink{class_ogre_1_1_degree}{Ogre\+::\+Degree} or \hyperlink{class_ogre_1_1_radian}{Ogre\+::\+Radian}. As the picture demonstrates, rotation around the y-\/axis is called yaw, around the x-\/axis is called pitch, and around the z-\/axis is called roll. These are terms often used in describing the movements of an aircraft.

There is a well-\/known trick for remembering which direction is a positive rotation around an axis. It is called the \href{http://en.wikipedia.org/wiki/Right-hand_rule}{\tt right-\/hand rule}. Point your thumb in the direction of the axis, and the direction your fingers curl towards is the positive direction. You can now see why these are often called \char`\"{}right-\/handed coordinate systems\char`\"{}. There are about a million ways of doing the right-\/hand rule. This is why you might see a group of physics students throwing gang signs while doing their homework. They\textquotesingle{}re trying to remember which direction the magnetic field is headed.

Let\textquotesingle{}s put this to use and place a rotated Entity into our scene. We will also position it nicely.


\begin{DoxyCodeInclude}
    Entity* ogreEntity4 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"ogrehead.mesh"});
    SceneNode* ogreNode4 = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    ogreNode4->\hyperlink{class_ogre_1_1_node_a72e58d4789cfe29e4538399b4250ce5a}{setPosition}(-84, 48, 0);
    ogreNode4->roll(Degree(-90));
    ogreNode4->attachObject(ogreEntity4);
\end{DoxyCodeInclude}
 Compile and run your application. We should now have a rotated \hyperlink{namespace_ogre}{Ogre} head in our scene.

\hypertarget{tut__first_scene_TheOgreEnvironment}{}\subsection{The Ogre Environment}\label{tut__first_scene_TheOgreEnvironment}
The library and configuration files for \hyperlink{namespace_ogre}{Ogre} can be found in the \textquotesingle{}bin\textquotesingle{} folder of your Ogre\+S\+DK. You should use the debug files when building your application in debug mod\hypertarget{tut__first_scene_LibrariesandPlugins}{}\subsubsection{Libraries and Plugins}\label{tut__first_scene_LibrariesandPlugins}
\hyperlink{namespace_ogre}{Ogre} is divided into three shared library groups\+: main library, plugins, and third-\/party libraries.\hypertarget{tut__first_scene_Mainlibrary}{}\paragraph{Main library}\label{tut__first_scene_Mainlibrary}
The main library group contains the \hyperlink{namespace_ogre}{Ogre} library itself and the shared libraries it relies on. The \hyperlink{namespace_ogre}{Ogre} library is contained within Ogre\+Main.\+dll or lib\+Ogre\+Main.\+so depending on your platform. This library must be included in all of your \hyperlink{namespace_ogre}{Ogre} applications. Ogre\+Main.\+dll requires a few other libraries like cg.\+dll.\hypertarget{tut__first_scene_Plugins}{}\paragraph{Plugins}\label{tut__first_scene_Plugins}
The second group of shared libraries are the plugins. \hyperlink{namespace_ogre}{Ogre} pushes a good portion of its functionality into shared libraries so that they may be turned on or off easily. The core plugins that are included with \hyperlink{namespace_ogre}{Ogre} have names that start with \char`\"{}\+Plugin\+\_\+\char`\"{}. You can also write your own plugins.

\hyperlink{namespace_ogre}{Ogre} also uses plugins for the different render systems (such as Open\+GL, DirectX, etc). These plugins start with \char`\"{}\+Render\+System\+\_\+\char`\"{}. This is also so that you can add only the systems you will need. This can be useful if you write shaders that rely on a particular system, because you can simply remove the incompatible system so that the program won\textquotesingle{}t try to run incorrect code. This also means you can write your own plugins if you want to extend \hyperlink{namespace_ogre}{Ogre} into another render system.\hypertarget{tut__first_scene_ThirdpartyPlugins}{}\paragraph{Third-\/party Plugins}\label{tut__first_scene_ThirdpartyPlugins}
The last major group contains third-\/party libraries and other general support libraries. \hyperlink{namespace_ogre}{Ogre} is focused sharply on being a graphics rendering library. This group makes it easy to integrate external libraries to add things like physics, input, and G\+UI systems. These libraries are used together to form a full game development environment. You might find this piecemeal approach a little strange, but it is a very common design pattern in large software projects. It is harder to comprehend at first, but it is a much more flexible approach when you want to start building more complicated scenes.

The \hyperlink{namespace_ogre}{Ogre} demos and S\+DK include some of these third-\/party libraries. The \href{https://www.libsdl.org/}{\tt Simple Direct\+Media} can be used to manage input events and distribute them to \hyperlink{namespace_ogre}{Ogre}. You can also make use of Cg, which is used by Cg\+Program\+Manager. This library allows you to produce materials with custom shaders. There are other libraries (not included with \hyperlink{namespace_ogre}{Ogre}) that offer functionality such as sound and physics.\hypertarget{tut__first_scene_TestingvsRelease}{}\paragraph{Testing vs Release}\label{tut__first_scene_TestingvsRelease}
When you\textquotesingle{}re building your application you can just leave every plugin activated. This will allow you to experiment with using them or not. But when you get ready to distribute a release build of your work, then you will want to deactivate any of the plugins you are not using.\hypertarget{tut__first_scene_ConfigurationFiles}{}\subsubsection{Configuration Files}\label{tut__first_scene_ConfigurationFiles}
\hyperlink{namespace_ogre}{Ogre} uses several configuration files ($\ast$.cfg). They control things like which plugins are loaded and where your application will search for resource files. We will briefly introduce you to each of these files. You\textquotesingle{}ll slowly read more about them as you progress through the tutorials as well.\hypertarget{tut__first_scene_PluginConfiguration}{}\paragraph{Plugin Configuration}\label{tut__first_scene_PluginConfiguration}
{\bfseries plugins.\+cfg}

This file tells \hyperlink{namespace_ogre}{Ogre} which plugins to load. You modify this file when you want to load a different set of plugins. It is often most useful to simply \char`\"{}comment out\char`\"{} lines instead of removing them, because you never know when a stroke of inspiration will mean you want to reload some unused plugins. Here is some sample content\+:


\begin{DoxyCode}
# Plugin=RenderSystem\_Direct3D9
# Plugin=RenderSystem\_Direct3D10
# Plugin=RenderSystem\_Direct3D11
Plugin=RenderSystem\_GL
\end{DoxyCode}


We have the three DirectX systems commented out, and an active line for Open\+GL. On a windows system, you may have this reversed. You can see why it might be helpful not to delete unused lines, because then you have to try and remember whether it was Render\+System\+\_\+\+Open\+GL or Render\+System\+\_\+\+GL.

You can also decide where \hyperlink{namespace_ogre}{Ogre} looks for plugins by changing the \textquotesingle{}Plugin\+Folder\textquotesingle{} variable. You can use both absolute and relative paths, but you cannot use environment variables like . For example, if you have built \hyperlink{namespace_ogre}{Ogre} from source on a linux machine, then you will need a line like this at the beginning of your file\+:


\begin{DoxyCode}
PluginFolder=/usr/local/lib/OGRE
\end{DoxyCode}


By default, \hyperlink{namespace_ogre}{Ogre} would have been looking in \textquotesingle{}/usr/lib/\+O\+G\+RE\textquotesingle{}. This is where it would be placed if you installed \hyperlink{namespace_ogre}{Ogre} from a package manager. You may have to do something similar on Mac.\hypertarget{tut__first_scene_ResourceConfiguration}{}\paragraph{Resource Configuration}\label{tut__first_scene_ResourceConfiguration}
{\bfseries resources.\+cfg}

This file contains a list of the directories \hyperlink{namespace_ogre}{Ogre} will use to search for resources. Resources include scripts, meshes, textures, G\+UI layouts, and others. You can also use both absolute and relative paths in this file, but you still cannot use environment variables. \hyperlink{namespace_ogre}{Ogre} will {\bfseries not} search subdirectories, so you have to manually enter them. Here is an example\+:


\begin{DoxyCode}
[General]
FileSystem=../media
FileSystem=../media/materials/scripts
FileSystem=../media/materials/textures
FileSystem=../media/models
\end{DoxyCode}


Here is an example of a relative path being used and the need to list subdirectories. Including the \textquotesingle{}../media\textquotesingle{} directory did not automatically include the \textquotesingle{}../media/models\textquotesingle{} directory. This is so that \hyperlink{namespace_ogre}{Ogre} doesn\textquotesingle{}t get greedy and waste time loading up unneeded resources.\hypertarget{tut__first_scene_MediaConfiguration}{}\paragraph{Media Configuration}\label{tut__first_scene_MediaConfiguration}
{\bfseries media.\+cfg}

This file provides \hyperlink{namespace_ogre}{Ogre} with more detailed information about some resources. It is unlikely that you will need to modify this file for quite a long time. More information can be found in the \hyperlink{namespace_ogre}{Ogre} manual.\hypertarget{tut__first_scene_OgreConfiguration}{}\paragraph{Ogre Configuration}\label{tut__first_scene_OgreConfiguration}
{\bfseries ogre.\+cfg}

This file is generated by the Render Settings dialog that appears when you run your application. This file will be specific to your own setup. {\bfseries Do not} distribute this file with your application. This file will contain your choices for things like screen resolution. Do not modify this file directly. Change the settings with the dialog and it will be automatically updated.\hypertarget{tut__first_scene_Quake3SettingsConfiguration}{}\paragraph{Quake 3 Settings Configuration}\label{tut__first_scene_Quake3SettingsConfiguration}
{\bfseries quake3settings.\+cfg}

This file is used by the B\+S\+P\+Scene\+Manager. You would only need this file if you were using that Scene\+Manager (the tutorials will not). This should not be distributed with your application.

That covers all of the configuration files that \hyperlink{namespace_ogre}{Ogre} manipulates directly. \hyperlink{namespace_ogre}{Ogre} will look for these files in the same directory as your executable and it must find \textquotesingle{}plugins.\+cfg\textquotesingle{}, \textquotesingle{}resources.\+cfg\textquotesingle{}, and \textquotesingle{}media.\+cfg\textquotesingle{} to function properly. Later tutorials will cover more of their use.\hypertarget{tut__first_scene_Conclusion1}{}\subsection{Conclusion}\label{tut__first_scene_Conclusion1}
You should now have a basic understanding of setting up an \hyperlink{namespace_ogre}{Ogre} scene. This tutorial provided an introduction to three of the most important objects in \hyperlink{namespace_ogre}{Ogre}\+: \hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity}, \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}, and \hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager}. These objects allow us to render and manipulate a scene filled with 3D objects.

An \hyperlink{class_ogre_1_1_entity}{Ogre\+::\+Entity} represents anything that has an \hyperlink{namespace_ogre}{Ogre} mesh. A \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node} is used to hold properties like location, scale, and rotation. It is also the anchor that attaches your Entities to your scene and allows them to be rendered on screen. Finally, The \hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager} is the object that orchestrates it all. It has methods that allow you to create Entities and Scene\+Nodes and keep them organized within a complicated scene. \hypertarget{tut_LightsCamerasShadows}{}\section{Lights, Cameras, and Shadows}\label{tut_LightsCamerasShadows}
This tutorial will expand on the use of Lights in a scene and using them to cast shadows.

The full source for this tutorial (Basic\+Tutorial2.\+cpp) can be found in samples directory {\bfseries Samples/\+Tutorials}.

\begin{DoxyNote}{Note}
Refer to \hyperlink{setup}{Setting up an O\+G\+RE project} for instructions how set up an \hyperlink{namespace_ogre}{Ogre} project and compile it successfully.
\end{DoxyNote}
\hypertarget{tut__lights_cameras_shadows_bt2TheOgreCameraClass}{}\subsection{The Ogre Camera Class}\label{tut__lights_cameras_shadows_bt2TheOgreCameraClass}
A Camera is the object we use to view our scene. A \hyperlink{class_ogre_1_1_camera}{Ogre\+::\+Camera} is a special object that works similar to a \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}. It has methods like set\+Position and yaw. You can also attach it to a Scene\+Node. For instance, you might want to temporarily attach your Camera to a Scene\+Node that follows a path through the sky to create an aerial cutscene. Just like a Scene\+Node the Camera\textquotesingle{}s position will be relative to its parent Scene\+Node. The Camera is not a Scene\+Node (it actually inherits from the Frustum class), but for movement and rotation, you can treat it like a Scene\+Node.

\begin{DoxyNote}{Note}
Starting from version 1.\+10 functionality related to rotate and translate camera are deprecated. You should attach camera to \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node} and do all transformation with this node.
\end{DoxyNote}
\hypertarget{tut__lights_cameras_shadows_bt2CreatingaCamera}{}\subsection{Creating a Camera}\label{tut__lights_cameras_shadows_bt2CreatingaCamera}
We will now cover camera creation part which we just applied in previous tutorial. We remeber that now we need to have Scene\+Node for camera. The first step will be doing is creating that Scene\+Node and asking the Scene\+Manager to create a new Camera. Add the following to create Scene\+Node and Camera\+:


\begin{DoxyCodeInclude}
    SceneNode* camNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    Camera* cam = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a62ca781b4c6d23dc3aab1f3a45d61843}{createCamera}(\textcolor{stringliteral}{"myCam"});
\end{DoxyCodeInclude}
You can retrieve the Camera by name using the Scene\+Manager\textquotesingle{}s get\+Camera method.

Next, we will position the Camera and use a method called look\+At to set its direction using cam\+Node. 
\begin{DoxyCodeInclude}
    camNode->setPosition(200, 300, 400);
    camNode->lookAt(Vector3(0, 0, 0), Node::TransformSpace::TS\_WORLD);
\end{DoxyCodeInclude}
The \hyperlink{class_ogre_1_1_scene_node_a665c4750906917dd061b141c03d432de}{Ogre\+::\+Scene\+Node\+::look\+At} method is very useful. It does exactly what it says. It rotates the Scene\+Node so that its line of sight focuses on the vector you give it. It makes the Camera \char`\"{}look at\char`\"{} the point.

The last thing we\textquotesingle{}ll do (apart of attachning camera to a Scene\+Node) is set the near clipping distance to 5 units. This is the distance at which the Camera will no longer render any mesh. If you get very close to a mesh, this will sometimes cut the mesh and allow you to see inside of it. The alternative is filling the entire screen with a tiny, highly magnified piece of the mesh\textquotesingle{}s texture. It\textquotesingle{}s up to you what you want in your scene. For demonstration, we\textquotesingle{}ll set it here.


\begin{DoxyCodeInclude}
    cam->setNearClipDistance(5);
    camNode->attachObject(cam);
\end{DoxyCodeInclude}
 \hypertarget{tut__lights_cameras_shadows_bt2Viewports}{}\subsection{Viewports}\label{tut__lights_cameras_shadows_bt2Viewports}
When dealing with multiple Cameras in a scene, the concept of a Viewport becomes very useful. We will touch on it now, because it will help you understand more about how \hyperlink{namespace_ogre}{Ogre} decides which Camera to use when rendering a scene. \hyperlink{namespace_ogre}{Ogre} makes it possible to have multiple Scene\+Managers running at the same time. It also allows you to break up the screen and use separate Cameras to render different views of a scene. This would allow the creation of things like splitscreens and minimaps. These kinds of things will be covered in later tutorials.

There are three constructs that are crucial to understanding how \hyperlink{namespace_ogre}{Ogre} renders a scene\+: the Camera, the Scene\+Manager, and the Render\+Window. We have not yet covered the Render\+Window. It basically represents the whole window we are rendering to. The Scene\+Manager will create Cameras to view the scene, and then we tell the Render\+Window where to display each Camera\textquotesingle{}s view. The way we tell the Render\+Window which area of the screen to use is by giving it a \hyperlink{class_ogre_1_1_viewport}{Ogre\+::\+Viewport}. For many circumstances, we will simply create one Camera and create a Viewport which represents the whole screen.\hypertarget{tut__lights_cameras_shadows_bt2CreatingaViewport}{}\subsection{Creating a Viewport}\label{tut__lights_cameras_shadows_bt2CreatingaViewport}
Let\textquotesingle{}s create a Viewport for our scene. To do this, we will use the add\+Viewport method of the Render\+Window. 
\begin{DoxyCodeInclude}
    Viewport* vp = getRenderWindow()->addViewport(cam);
\end{DoxyCodeInclude}
get\+Render\+Window() is a method defined for us in \hyperlink{class_ogre_bites_1_1_application_context}{Ogre\+Bites\+::\+Application\+Context} which returns \hyperlink{class_ogre_1_1_render_window}{Ogre\+::\+Render\+Window}.

Now let\textquotesingle{}s set the background color of the Viewport. 
\begin{DoxyCodeInclude}
    vp->setBackgroundColour(ColourValue(0, 0, 0));
\end{DoxyCodeInclude}
 We\textquotesingle{}ve set it to black because we are going to add colored lighting later, and we don\textquotesingle{}t want the background color affecting how we see the lighting.

The last thing we are going to do is set the aspect ratio of our Camera. If you are using something other than a standard full-\/window viewport, then failing to set this can result in a distorted scene. We will set it here for demonstration even though we are using the default aspect ratio.


\begin{DoxyCodeInclude}
    cam->setAspectRatio(\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}(vp->getActualWidth()) / \hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real}(vp->getActualHeight()));
\end{DoxyCodeInclude}
 We have retrieved the width and height from the Viewport to set the aspect ratio. As we mentioned, the default is already set to use the full screen\textquotesingle{}s dimensions.

Compile and run your application. You should still only see a black screen, just make sure it runs.\hypertarget{tut__lights_cameras_shadows_bt2BuildingtheScene}{}\subsection{Building the Scene}\label{tut__lights_cameras_shadows_bt2BuildingtheScene}
Before we get to shadows and lighting, let\textquotesingle{}s add some elements to our scene. Let\textquotesingle{}s put a ninja right in the middle of things. Add the following code right after we set the ambient light\+: 
\begin{DoxyCodeInclude}
    Entity* ninjaEntity = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"ninja.mesh"});
    ninjaEntity->\hyperlink{class_ogre_1_1_movable_object_acbfc4840224e8b6ed6e27849d3341675}{setCastShadows}(\textcolor{keyword}{true});

    scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(ninjaEntity);
\end{DoxyCodeInclude}
 This should look familiar, except we are asking the mesh to cast shadows this time. And notice that we have created a child scene node and attached the ninja\+Entity all in one call this time.

We will also create something for the ninja to be standing on. We can use the \hyperlink{class_ogre_1_1_mesh_manager}{Ogre\+::\+Mesh\+Manager} to create meshes from scratch. We will use it to generate a textured plane to use as the ground.

The first thing we\textquotesingle{}ll do is create an abstract Plane object. This is not the mesh, it is more of a blueprint. 
\begin{DoxyCodeInclude}
    Plane plane(Vector3::UNIT\_Y, 0);
\end{DoxyCodeInclude}
 We create a plane by supplying a vector that is normal to our plane and its distance from the origin. So we have created a plane that is perpendicular to the y-\/axis and zero units from the origin. Here\textquotesingle{}s a picture\+:



There are other overloads of the Plane constructor that let us pass a second vector instead of a distance from the origin. This allows us to build any plane in 3D space we want.

Now we\textquotesingle{}ll ask the Mesh\+Manager to create us a mesh using our Plane blueprint. The Mesh\+Manager is already keeping track of the resources we loaded when initializing our application. On top of this, it can create new meshes for us.


\begin{DoxyCodeInclude}
    MeshManager::getSingleton().createPlane(
            \textcolor{stringliteral}{"ground"},
            ResourceGroupManager::DEFAULT\_RESOURCE\_GROUP\_NAME,
            plane,
            1500, 1500, 20, 20,
            \textcolor{keyword}{true},
            1, 5, 5,
            Vector3::UNIT\_Z);
\end{DoxyCodeInclude}
This is a complicated method, and we\textquotesingle{}re not entirely equipped to understand all of it yet. You can read through the \hyperlink{class_ogre_1_1_mesh_manager}{Ogre\+::\+Mesh\+Manager} class specification if you want to learn more now. Basically, we\textquotesingle{}ve created a new mesh called \char`\"{}ground\char`\"{} with a size of 1500x1500.

Now we will create a new Entity using this mesh. 
\begin{DoxyCodeInclude}
    Entity* groundEntity = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{createEntity}(\textcolor{stringliteral}{"ground"});
    scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(groundEntity);
\end{DoxyCodeInclude}
 Be careful that you don\textquotesingle{}t confuse the parameter given to create\+Entity for the Entity\textquotesingle{}s name. It is actually the name of the mesh we just created. We\textquotesingle{}re used to seeing mesh names end with \textquotesingle{}.mesh\textquotesingle{}.

We want to tell our Scene\+Manager not to cast shadows from our ground Entity. It would just be a waste. Don\textquotesingle{}t get confused, this means the ground won\textquotesingle{}t cast a shadow, it doesn\textquotesingle{}t mean we can\textquotesingle{}t cast shadows on to the {\itshape ground}. 
\begin{DoxyCodeInclude}
    groundEntity->setCastShadows(\textcolor{keyword}{false});
\end{DoxyCodeInclude}
 And finally we need to give our ground a material. For now, it will be easiest to use a material from the script that \hyperlink{namespace_ogre}{Ogre} includes with its samples. You should have these resources in your S\+DK or the source directory you downloaded to build \hyperlink{namespace_ogre}{Ogre}. 
\begin{DoxyCodeInclude}
    groundEntity->setMaterialName(\textcolor{stringliteral}{"Examples/Rockwall"});
\end{DoxyCodeInclude}
 Make sure you add the texture for the material and the Examples.\+material script to your resource loading path. In our case, the texture is called \textquotesingle{}rockwall.\+tga\textquotesingle{}. You can find the name yourself by reading the entry in the material script.\hypertarget{tut__lights_cameras_shadows_bt2UsingShadowsinOgre}{}\subsection{Using Shadows in Ogre}\label{tut__lights_cameras_shadows_bt2UsingShadowsinOgre}
Enabling shadows in \hyperlink{namespace_ogre}{Ogre} is easy. The Scene\+Manager class has a \hyperlink{class_ogre_1_1_scene_manager_ad716d3752418408f073d9be9bbfe62d0}{Ogre\+::\+Scene\+Manager\+::set\+Shadow\+Technique} method we can use. Then whenever we create an Entity, we call set\+Cast\+Shadows to choose which Entities will cast shadows. set\+Shadow\+Techinique method takes several of different techniques. Refer to \hyperlink{group___general_ga79dcd426d291c31072c1ad6f183715d6}{Ogre\+::\+Shadow\+Technique} for more details.

Let\textquotesingle{}s turn off the ambient light so we can see the full effect of our lights. Add the following changes\+:


\begin{DoxyCodeInclude}
    scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a7c26cdbb5703cf10a99add1f6a930ca2}{setAmbientLight}(ColourValue(0, 0, 0));
    scnMgr->\hyperlink{class_ogre_1_1_scene_manager_ad716d3752418408f073d9be9bbfe62d0}{setShadowTechnique}(
      \hyperlink{group___general_gga79dcd426d291c31072c1ad6f183715d6af1b698ef34b8d97c261b7ade00010b7f}{ShadowTechnique::SHADOWTYPE\_STENCIL\_MODULATIVE});
\end{DoxyCodeInclude}
 Now the Scene\+Manager will use modulative stencil shadows. Let\textquotesingle{}s add some lights to see this in action.\hypertarget{tut__lights_cameras_shadows_bt2Lights}{}\subsection{Lights}\label{tut__lights_cameras_shadows_bt2Lights}
\hyperlink{namespace_ogre}{Ogre} provides three types of lighting.
\begin{DoxyItemize}
\item \hyperlink{class_ogre_1_1_light_a4f1dea084d1497c6f49e802ade940dbca0d59bfdcfeb338dbfe06e2e2999e752f}{Ogre\+::\+Light\+::\+L\+T\+\_\+\+P\+O\+I\+NT} -\/ This Light speads out equally in all directions from a point.
\item \hyperlink{class_ogre_1_1_light_a4f1dea084d1497c6f49e802ade940dbca8fc40a1ccfb026944417ef92b7ddaefe}{Ogre\+::\+Light\+::\+L\+T\+\_\+\+S\+P\+O\+T\+L\+I\+G\+HT} -\/ This Light works like a flashlight. It produces a solid cylinder of light that is brighter at the center and fades off.
\item \hyperlink{class_ogre_1_1_light_a4f1dea084d1497c6f49e802ade940dbca4c5582d28848ce40c2b652488494b4a3}{Ogre\+::\+Light\+::\+L\+T\+\_\+\+D\+I\+R\+E\+C\+T\+I\+O\+N\+AL} -\/ This Light simulates a huge source that is very far away -\/ like daylight. Light hits the entire scene at the same angle everywhere.
\end{DoxyItemize}

The \hyperlink{class_ogre_1_1_light}{Ogre\+::\+Light} class has a wide range of properties. Two of the most important are the \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=-Diffuse+%28Light%29}{\tt diffuse} and \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=-Specular+%28Light%29}{\tt specular} color. Each material script defines how much specular and diffuse lighting a material reflects. These properties will be covered in some of the later tutorials.\hypertarget{tut__lights_cameras_shadows_CreatingaLight}{}\subsection{Creating a Light}\label{tut__lights_cameras_shadows_CreatingaLight}
Let\textquotesingle{}s add a Light to our scene. We do this by calling the \hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{Ogre\+::\+Scene\+Manager\+::create\+Light} method. Add the following code right after we finish creating the ground\+Entity\+: 
\begin{DoxyCodeInclude}
    Light* spotLight = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}(\textcolor{stringliteral}{"SpotLight"});
\end{DoxyCodeInclude}
 We\textquotesingle{}ll set the diffuse and specular colors to pure blue. 
\begin{DoxyCodeInclude}
    spotLight->setDiffuseColour(0, 0, 1.0);
    spotLight->setSpecularColour(0, 0, 1.0);
\end{DoxyCodeInclude}
 Next we will set the type of the light to spotlight.


\begin{DoxyCodeInclude}
    spotLight->setType(Light::LT\_SPOTLIGHT);
\end{DoxyCodeInclude}
 The spotlight requires both a position and a direction -\/ remember it acts like a flashlight. We\textquotesingle{}ll place the spotlight above the right shoulder of the ninja shining down on him at a 45 degree angle.


\begin{DoxyCodeInclude}
    SceneNode* spotLightNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    spotLightNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(spotLight);
    spotLightNode->setDirection(-1, -1, 0);
    spotLightNode->setPosition(Vector3(200, 200, 0));
\end{DoxyCodeInclude}
 

Finally, we set what is called the spotlight range. These are the angles that determine where the light fades from bright in the middle to dimmer on the outside edges.


\begin{DoxyCodeInclude}
    spotLight->setSpotlightRange(Degree(35), Degree(50));
\end{DoxyCodeInclude}
Compile and run the application. You should see the shadowy blue figure of a ninja.

\hypertarget{tut__lights_cameras_shadows_CreatingMoreLights}{}\subsection{Creating More Lights}\label{tut__lights_cameras_shadows_CreatingMoreLights}
Next we\textquotesingle{}ll add a directional light to our scene. This type of light essentially simulates daylight or moonlight. The light is cast at the same angle across the entire scene equally. As before, we\textquotesingle{}ll start by creating the Light and setting its type.


\begin{DoxyCodeInclude}
    Light* directionalLight = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}(\textcolor{stringliteral}{"DirectionalLight"});
    directionalLight->\hyperlink{class_ogre_1_1_light_a6019f7fa89624e35316ba444e519d8f8}{setType}(Light::LT\_DIRECTIONAL);
\end{DoxyCodeInclude}
 Now we\textquotesingle{}ll set the diffuse and specular colors to a dark red. 
\begin{DoxyCodeInclude}
    directionalLight->setDiffuseColour(ColourValue(0.4, 0, 0));
    directionalLight->setSpecularColour(ColourValue(0.4, 0, 0));
\end{DoxyCodeInclude}
 Finally, we need to set the Light\textquotesingle{}s direction. A directional light does not have a position because it is modeled as a point light that is infinitely far away.


\begin{DoxyCodeInclude}
    SceneNode* directionalLightNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    directionalLightNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(directionalLight);
    directionalLightNode->setDirection(Vector3(0, -1, 1));
\end{DoxyCodeInclude}
 

The Light class also defines a \hyperlink{class_ogre_1_1_light_a2880f26669477a55cf01919f906bb65d}{Ogre\+::\+Light\+::set\+Attenuation} function which allows you to control how the light dissipates as you get farther away from it. After you finish this tutorial, try using this method in your scene to see how it affects your lights.

Compile and run the application. Your ninja should now have a shadow cast behind him, and the scene should be filled with red light.



To complete the set, we will now add a point light to our scene. 
\begin{DoxyCodeInclude}
    Light* pointLight = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_ab127d52207729591dd51cb12a5b2ed2c}{createLight}(\textcolor{stringliteral}{"PointLight"});
    pointLight->\hyperlink{class_ogre_1_1_light_a6019f7fa89624e35316ba444e519d8f8}{setType}(Light::LT\_POINT);
\end{DoxyCodeInclude}
 We\textquotesingle{}ll set the the specular and diffuse colors to a dark gray.


\begin{DoxyCodeInclude}
    pointLight->setDiffuseColour(0.3, 0.3, 0.3);
    pointLight->setSpecularColour(0.3, 0.3, 0.3);
\end{DoxyCodeInclude}
 A point light has no direction. It only has a position. We will place our last light above and behind the ninja.


\begin{DoxyCodeInclude}
    SceneNode* pointLightNode = scnMgr->\hyperlink{class_ogre_1_1_scene_manager_a854ef69f989aadd1da0bd79a61f88f9e}{getRootSceneNode}()->
      \hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}();
    pointLightNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(pointLight);
    pointLightNode->setPosition(Vector3(0, 150, 250));
\end{DoxyCodeInclude}
 Compile and run the application. You should see a long shadow cast in front of the ninja now. And you should see the effects of the point light brightening up the area behind the ninja. Try to think about why the colors turn out the way they do. For instance, why does the shadow behind the ninja appear to have no red at all?

\hypertarget{tut__lights_cameras_shadows_ShadowTypes}{}\subsection{Shadow Types}\label{tut__lights_cameras_shadows_ShadowTypes}
\hyperlink{namespace_ogre}{Ogre} supports set of different shadow types. Please refer to \hyperlink{group___general_ga79dcd426d291c31072c1ad6f183715d6}{Ogre\+::\+Shadow\+Technique} enumerator for more details.

Try experimenting with the different shadow types. There are also other shadow-\/related methods in the \hyperlink{class_ogre_1_1_scene_manager}{Ogre\+::\+Scene\+Manager} class that you can play with.

\hyperlink{namespace_ogre}{Ogre} does not provide soft shadows as part of the engine. You can write your own vertex and fragment programs to implement soft shadows and many other things. The \hyperlink{namespace_ogre}{Ogre} Manual has a full description of \hyperlink{Shadows}{Shadows}.\hypertarget{tut__lights_cameras_shadows_Conclusion2}{}\subsection{Conclusion}\label{tut__lights_cameras_shadows_Conclusion2}
This tutorial introduced the use of lights and shadows into the scene. To begin, we covered how to use the Mesh\+Manager to generate meshes from scratch. We then chose which shadow type \hyperlink{namespace_ogre}{Ogre} should use. Finally, we begin adding an example of each type of Light to our scene. We created a spotlight, a directional light, and a point light. You can even extend \hyperlink{namespace_ogre}{Ogre}\textquotesingle{}s lighting and shadow systems by writing your own vertex and fragment programs. Refer to the \hyperlink{namespace_ogre}{Ogre} Manual for more details.

There are a lot of different settings we\textquotesingle{}ve covered that allow you to customize how \hyperlink{namespace_ogre}{Ogre} renders light and shadow. After you\textquotesingle{}ve finished each tutorial, it is a good idea to play around with the new tools you have. This will greatly increase your comfort level working with the library, and it is an excellent way to learn how to navigate A\+PI documentation. \hypertarget{working-with-numpy}{}\section{Working with Num\+Py}\label{working-with-numpy}
\hyperlink{namespace_ogre}{Ogre} includes a Python component which automatically generates Python bindings from the C++ headers. However with Python you most likely do not only want to just use \hyperlink{namespace_ogre}{Ogre}, but connect it to other components. For this we ship a small module called {\ttfamily Ogre\+Numpy} that helps you converting between \hyperlink{namespace_ogre}{Ogre} and Num\+Py.

We start with a simple 3 channel python array representing a green gradient\+:


\begin{DoxyCodeInclude}
    arr = np.zeros((256, 256, 3), dtype=np.uint8)
    arr[:,:,1] = np.mgrid[0:256,0:256][1]
\end{DoxyCodeInclude}
 

To be able to load it into Ogre we need a pointer that we can pass to \hyperlink{class_ogre_1_1_image}{Ogre.\+Image}. For this we {\itshape copy} the contents of our array into an \hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.\+Memory\+Data\+Stream}. Here Ogre\+Numpy.\+As\+Data\+Stream automatically allocates the Memory\+Data\+Stream of the according size and takes care of the copying.


\begin{DoxyCodeInclude}
    mem = OgreNumpy.AsDataStream(arr)
    ogre\_img = \hyperlink{class_ogre_1_1_image}{Ogre.Image}()
    ogre\_img.loadDynamicImage(mem.getPtr(), 256, 256, Ogre.PF\_BYTE\_RGB)
    
    \hyperlink{class_ogre_1_1_texture_manager_ac6fb858ee86f3b7b75de32e3e04ee5c8}{Ogre.TextureManager.getSingleton}().loadImage(\textcolor{stringliteral}{"gradient"}, \textcolor{stringliteral}{"General"}, 
      ogre\_img)
\end{DoxyCodeInclude}
 While this is not the fastest option, we now have an \hyperlink{namespace_ogre}{Ogre} data type, that we can use as usual and upload to an Texture.

For completeness we also create a small scene where we map the texture on a screen-\/centred rectangle. 
\begin{DoxyCodeInclude}
    mat = \hyperlink{class_ogre_1_1_material_manager_a100f413d9d2316028e7ae740e5a43161}{Ogre.MaterialManager.getSingleton}().create(\textcolor{stringliteral}{"gradient\_mat"}, \textcolor{stringliteral}{"
      General"})
    rpass = mat.getTechniques()[0].getPasses()[0]
    rpass.setLightingEnabled(\textcolor{keyword}{False})
    rpass.createTextureUnitState(\textcolor{stringliteral}{"gradient"})

    rect = \hyperlink{class_ogre_1_1_rectangle2_d}{Ogre.Rectangle2D}(\textcolor{keyword}{True})
    rect.setCorners(-0.5, 0.5, 0.5, -0.5) \textcolor{comment}{# in normalized screen space}
    rect.setMaterial(mat)
    rect.setBoundingBox(\hyperlink{class_ogre_1_1_axis_aligned_box}{Ogre.AxisAlignedBox}(Ogre.AxisAlignedBox.BOX\_INFINITE))

    scn\_mgr.getRootSceneNode().createChildSceneNode().attachObject(rect)
\end{DoxyCodeInclude}
 As the rectangle does not cover the full scene, we also set a background colour 
\begin{DoxyCodeInclude}
    gray = (0.3, 0.3, 0.3)
    vp.setBackgroundColour(\hyperlink{class_ogre_1_1_colour_value}{Ogre.ColourValue}(*gray))
\end{DoxyCodeInclude}
Here we use the normal python iterable unpacking. Again this is copying the data.

Finally we want to store the rendered image into a file. This time we manually allocate the memory with \hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.\+Memory\+Data\+Stream} to store the pixel values.


\begin{DoxyCodeInclude}
    mem = \hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.MemoryDataStream}(win.getWidth() * win.getHeight() * 3)
    pb = \hyperlink{class_ogre_1_1_pixel_box}{Ogre.PixelBox}(win.getWidth(), win.getHeight(), 1, Ogre.PF\_BYTE\_RGB, mem.getPtr())
    win.copyContentsToMemory(pb, pb)
\end{DoxyCodeInclude}
 Finally we store the image to disk using pyplot.


\begin{DoxyCodeInclude}
    pyplot.imsave(\textcolor{stringliteral}{"screenshot.png"}, OgreNumpy.view(pb))
\end{DoxyCodeInclude}
 To convert the \hyperlink{class_ogre_1_1_pixel_box}{Ogre.\+Pixel\+Box} to a Num\+Py array we use Ogre\+Numpy.\+view. This function does {\itshape not} copy the data, but as the name suggests just creates a Num\+Py view on the underlying \hyperlink{class_ogre_1_1_memory_data_stream}{Ogre.\+Memory\+Data\+Stream}. Using this pattern we could also have avoided the copy when loading the numpy array as a Texture.



\begin{DoxyNote}{Note}
There is also \hyperlink{class_ogre_1_1_render_target_afb7ac36166a3e7c38a102edc6e7d2c1d}{Ogre\+::\+Render\+Target\+::write\+Contents\+To\+File} if you do not need the pixel data in Python. 
\end{DoxyNote}
\hypertarget{trays}{}\section{Trays G\+UI System}\label{trays}
Ever wanted really simple G\+UI controls for your sample? Don\textquotesingle{}t want to write one from scratch, but C\+E\+G\+UI\textquotesingle{}s just a little too much? The Trays system was created to address this issue. It\textquotesingle{}s a simple G\+UI system based on the O\+G\+RE Overlay system and designed just for samples. Because it\textquotesingle{}s simple, you\textquotesingle{}re not going to be able to skin it or build very unique interfaces, but you\textquotesingle{}ll also find it much easier to use. The entire system is based on the O\+G\+RE Overlay system.\hypertarget{trays_trays-1}{}\subsection{Trays}\label{trays_trays-1}
Why trays? The concept of trays is central to the system in that it removes the need for the G\+UI designer (you) to calculate or specify positional coordinates of any kind. Think about the widget locations in a typical G\+UI. They are almost always in any of the four corners, along any of the four edges or, on the rare occasion, in the center of the screen. In Trays, there are nine \char`\"{}trays\char`\"{}, one in each of the locations previously mentioned. When you create a widget, you specify one of these nine locations, and the widget will be added to the tray at that location. Your widget will be added directly beneath the last widget in that tray. When you add a widget to a tray, the tray grows in size. Trays along the top of the screen grow downward, Trays along the bottom grow upward, and the trays in the middle row grow vertically in both directions. Visually, the trays are semi-\/transparent panels that fit the widgets they contain. Only non-\/empty trays are visible. If this is hard to visualise, don\textquotesingle{}t worry, here\textquotesingle{}s a picture to help you out. \hypertarget{trays_traymanager}{}\subsection{Tray\+Manager}\label{trays_traymanager}
To use Trays, you have to create an Tray\+Manager. This is the class through which you will create and manage all your widgets, manipulate the cursor, change the backdrop image, adjust tray properties, pop up dialogs, show/hide the loading bar, etc. You can have multiple tray managers in one application. For example, the O\+G\+RE Sample Browser uses its own tray manager and hides it when a sample is running, and the S\+DK samples also have their own tray managers, which are hidden when the samples are paused by the browser. The Tray\+Manager requires \char`\"{}\+Trays.\+zip\char`\"{}, so you can only create it after loading that resource. Also, make sure you\textquotesingle{}re using the \hyperlink{namespace_ogre_bites}{Ogre\+Bites} namespace (Trays is part of the \hyperlink{namespace_ogre_bites}{Ogre\+Bites} Samples Framework). Create your tray manager like so\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_bites_1_1_tray_manager}{OgreBites::TrayManager}* mTrayMgr = \textcolor{keyword}{new} 
      \hyperlink{class_ogre_bites_1_1_tray_manager}{OgreBites::TrayManager}(\textcolor{stringliteral}{"InterfaceName"}, mWindow, \textcolor{keyword}{this});
\end{DoxyCode}
 You must pass in a name for your interface, an {\ttfamily \hyperlink{class_ogre_1_1_render_window}{Ogre\+::\+Render\+Window}} and an {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_listener}{Ogre\+Bites\+::\+Tray\+Listener}}. You can extend your sample or sample context to be a tray listener. Destroy your tray manager like so\+: 
\begin{DoxyCode}
\textcolor{keyword}{delete} mTrayMgr;
mTrayMgr = 0;
\end{DoxyCode}
 Once you have your tray manager, make sure you relay your O\+IS events to it. 
\begin{DoxyCode}
\textcolor{keywordtype}{bool} mousePressed(\textcolor{keyword}{const} \hyperlink{struct_ogre_bites_1_1_mouse_button_event}{OgreBites::MouseButtonEvent}& evt)
\{
    \textcolor{keywordflow}{if} (mTrayMgr->injectMouseDown(evt)) \textcolor{keywordflow}{return} \textcolor{keyword}{true};
    \textcolor{comment}{/* normal mouse processing here... */}
    \textcolor{keywordflow}{return} \textcolor{keyword}{true};
\}

\textcolor{keywordtype}{bool} mouseReleased(\textcolor{keyword}{const} \hyperlink{struct_ogre_bites_1_1_mouse_button_event}{OgreBites::MouseButtonEvent}& evt)
\{
    \textcolor{keywordflow}{if} (mTrayMgr->injectMouseUp(evt)) \textcolor{keywordflow}{return} \textcolor{keyword}{true};
    \textcolor{comment}{/* normal mouse processing here... */}
    \textcolor{keywordflow}{return} \textcolor{keyword}{true};
\}

\textcolor{keywordtype}{bool} mouseMoved(\textcolor{keyword}{const} \hyperlink{struct_ogre_bites_1_1_mouse_motion_event}{OgreBites::MouseMotionEvent}& evt)
\{
    \textcolor{keywordflow}{if} (mTrayMgr->injectMouseMove(evt)) \textcolor{keywordflow}{return} \textcolor{keyword}{true};
    \textcolor{comment}{/* normal mouse processing here... */}
    \textcolor{keywordflow}{return} \textcolor{keyword}{true};
\}
\end{DoxyCode}
 The injection methods return true if the event was relevant to the tray manager, and should not be processed again by you. For example, if you click a button that is over an interactive part of your scene, you want the button to be pressed, but you don\textquotesingle{}t want the scene interaction to take place. So the injection methods double as filters for your mouse events.

You\textquotesingle{}re now free to create widgets! Try adding a button to the top-\/left tray\+: 
\begin{DoxyCode}
Button* b = mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a7486bcec7a51e1d6df53bfdead3281dd}{createButton}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530afe04de8736168ab0dd6e7938e679c292}{TL\_TOPLEFT}, \textcolor{stringliteral}{"MyButton"}, \textcolor{stringliteral}{"Click Me!"});
\end{DoxyCode}
 Tray\+Manager is a huge class, and you can do tons of things with it. For some examples, see the Things to Try section below.

\subsection*{The Cursor}

The cursor has three parts in the Trays system\+: The layer it moves around in Overlay, the container which positions the cursor (Overlay\+Container), and the cursor image, which is a child of the container (Overlay\+Element). When hiding/showing the cursor, the entire cursor layer is hidden/shown. The top left corner of the cursor container is used as the hotspot of the cursor. By positioning the cursor image relative to the cursor container, you can basically decide which part of the cursor image is the \char`\"{}clicking part\char`\"{}. For the default arrow cursor, the image is simply lined up with the container, meaning the top left is the hotspot. However, for something like a crosshair cursor, you could move the cursor image so that its center is over the top left corner of the cursor container. To show the cursor, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a1cc48ac157278b5845d425abbe9acefd}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Cursor}}, which takes an optional material name for the cursor image. If unspecified, the cursor image is not changed. To hide the cursor, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a979ff2ad2d729223259b3bebb237cafb}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Cursor}}. You can get the cursor\textquotesingle{}s different parts using get\+Cursor\+Layer, get\+Cursor\+Container, and get\+Cursor\+Image. Note that if the cursor is hidden, all interactions with widgets are disabled.

\subsection*{The Backdrop}

If you want to show a backdrop, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_ad554418c27edb907f0e3bead8659b83c}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Backdrop}}, which takes an optional material name for the backdrop. If unspecified, the backdrop image is not changed. To hide it, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a6129a1e92ac22789a4602cf36f9c5394}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Backdrop}}.\hypertarget{trays_widgets}{}\subsection{Widgets}\label{trays_widgets}
There are 10 basic widgets. Each widget is just an instance of an Overlay\+Element template, and all widgets use \{L\+E\+X()\}pixel\{L\+EX\} metrics. You can get access to any widget\textquotesingle{}s underlying Overlay\+Element through {\ttfamily \hyperlink{class_ogre_bites_1_1_widget_a379d3f1a2ca6eaf13fc5c52afaafd0d2}{Ogre\+Bites\+::\+Widget\+::get\+Overlay\+Element}}. Do not instantiate and delete widgets manually. Create and destroy them using the Tray\+Manager. The first argument to any one of Tray\+Manager\textquotesingle{}s widget creation methods is the location of the tray you want the widget to be in. This is of the enumerated type Tray\+Location. The second argument is the name of your widget (this is not your widget\textquotesingle{}s caption, but a unique string identifier for your widget). The rest of the arguments are specific to the type of widget.

\subsection*{Button}

This is the most basic widget of all. To create a button, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a7486bcec7a51e1d6df53bfdead3281dd}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Button}}. In addition to a tray location and a name, you must specify a caption for your button, and an optional width. If width is not specified, the button will automatically resize to fit its caption. There are no button states. You only get notified when a button is pushed. To see how to respond to button push events, see the Tray\+Listener section below.

\subsection*{Text\+Box}

This widget consists of a bold caption bar and a text area that can be scrolled vertically. In addition to a tray location and a name, {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a07a8d212939266339e877ff2118250a6}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Text\+Box}} takes a caption, width, and height. You can set/get the caption, the text area contents, text padding, text alignment, manually change the scroll bar position, among other things.

\subsection*{Select\+Menu}

A basic drop-\/down menu. To create it, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a60864ca00d65b2bf1b97bb8545fab737}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Long\+Select\+Menu}} or {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a98f478c8daa5084b53146de03adbc216}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Thick\+Select\+Menu}}. Both these methods return a Select\+Menu object, but they give one of two different visual styles to the widget. One is thicker, but shorter, because it places the caption over the item box. This style of menu is good for putting in the side trays. The other is longer, but thinner, because it places the item box next to the caption. This style of menu is good for putting in the top or bottom trays. create\+Thick\+Select\+Menu takes a tray location, a name, a caption, the width of the whole widget, the maximum number of visible items when expanded, and an optional string vector of items. The medthod {\ttfamily create\+Long\+Select\+Menu} takes nearly the same arguments, except that it needs the width of the text box that shows the currently selected item. Also, for long menus, it is optional to specify the total width because it will automatically resize to fit the item box and the caption. You can set/get the caption, and set/get the items in many different ways. You can also manually change the selection, with the option of not firing an event. To see how to respond to menu item selection events, see the Tray\+Listener section below.

\subsection*{Label}

A big, semi-\/transparent, tabby-\/looking label. This widget uses a different font from the rest of the widgets, and is good for section headings and such. In addition to a tray location and a name, {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a15375d59b5c57059c9c6549fc5a1bfcd}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Label}} takes a caption, and an optional width. If the width is not specified, the label automatically adjusts its width to fill the tray it\textquotesingle{}s currently in, so it matches the other contents of the tray. Labels can also be clicked. To see how to respond to label click events, see the Tray\+Listener section below.

\subsection*{Separator}

A horizontal line which looks like it was etched into the tray. Good for dividing up other widgets into sections without taking up as much space as a label. {\ttfamily Tray\+Manager\+::create\+Separator} takes a tray location, name, and an optional width. If the width is not specified, the behaviour is the same as a Label\textquotesingle{}s.

\subsection*{Slider}

A slider bar consists of a container box, a small text box to display the value, and a track + handle. Sliders are type-\/agnostic. Using three parameters -\/ a minimum value, a maximum value, and the number of \char`\"{}snapping points\char`\"{}, you can give your slider track of any kind of discrete scale -\/ integer, floating point, or even nominal. Snapping points are basically the \char`\"{}steps\char`\"{} on your slider track. By specifying how many of them there are, you are in effect specifying an entire range of values all the way from your minimum value to your maximum value. Let\textquotesingle{}s say you have minimum value 0, maximum value 1, and 6 snapping points. Underneath the surface, each slider stores a floating point value, so in this case you would be able to display 6 floating point values\+: \{0, 0.\+2, 0.\+4, 0.\+6, 0.\+8, 1\}. The slider will display your value in the cleanest way possible (using {\ttfamily \hyperlink{class_ogre_1_1_string_converter_a45fb498a2f798c82bbf88116a5a34c53}{Ogre\+::\+String\+Converter\+::to\+String}}). This means that if all your values happen to land on integers, then they will be displayed as integers without decimals. You can also exploit this by using your slider\textquotesingle{}s integer values as indices into an array of string values, and manually set your slider\textquotesingle{}s value to the new string value. Basically, you can make your slider display things like Low, Medium, High, 1/4, 3/4, \$4.\+00, N/A, etc. This requires you to respond to slider move events. More on this in the Tray\+Listener section below. Then your Like select menus, sliders also come in two flavours -\/ thick and long. The thick style places the caption and the value box above the track, while the long style places the caption, track, and value box side by side in that order. {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a597ec173c1b424980e18fd92e0c56905}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Thick\+Slider}} takes a tray location, name, caption, total width, value box width, minimum value, maximum value, and the number of snapping points. {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a321429ade975d3a63dfc1125b4375e78}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Long\+Slider}} takes a an optional total width, track width, value box width, minimum value, maximum value, and the number of snapping points. If the total width is not specified, the slider will automatically scale to fit the track, the value box, and the caption text. You can get/set the slider\textquotesingle{}s caption, displayed value, actual value, and range of values. When you change the range, the value is reset to be the minimum value. When you change the value, you also have the option of not firing an event. To respond to slider move events, see the Tray\+Listener section below.

\subsection*{Params\+Panel}

This panel displays an arbitrary number of parameters and their values. This could be anything you want. For example, the stats panel in the S\+DK samples shows the average framerate, best framerate, batch count, etc. The details panel in the S\+DK samples shows the texture filtering technique, the polygon mode, and the camera position and orientation. To create a Params\+Panel, use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a5ae6b66603e05193b3077f30900209eb}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Params\+Panel}}, which takes a tray location, a name, a width, and then either a string vector of parameter names or the number of parameters (lines) to leave room for. The parameter names will be left justified, and their values will be right justified on the same line. At any time, you can set/get the parameter names and values either one at a time, or all at once using a string vector.

\subsection*{Check\+Box}

Self-\/explanatory. {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a7433f3e89c5b3a1b1b0012dfcb121f1d}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Check\+Box}} takes a tray location, name, caption, and an optional width. Unspecified width means auto-\/fit to caption. You can set/get the state of the check box, with the option of not triggering an event. To respond to check box state change events, see the Tray\+Listener section below. \subsection*{Decor\+Widget}

This widget takes any Overlay\+Element template, and creates a widget out of it. If you want to put your own picture, icons, or other static objects into the trays, make an Overlay\+Element template out of it, and then turn it into a Decor\+Widget. {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a24d1b3a3b95ddcf274bf899b7600deba}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Decor\+Widget}} takes a tray location, a name, and an Overlay\+Element template name. These are basically the same things you would normally use to create an Overlay\+Element from a template. The O\+G\+RE logo in the S\+DK samples is a Decor\+Widget. \subsection*{Progress\+Bar}

A progress bar with a caption, a comment/details box, and a meter that fills up. {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a431a347db6465bbf66af82ef363c875f}{Ogre\+Bites\+::\+Tray\+Manager\+::create\+Progress\+Bar}} takes a tray location, a name, a caption, a total width, and comment box width. You can use progress bars to show any kind of progress you want, but for the most common kind (loading resources), there\textquotesingle{}s a special instance of Progress\+Bar already created by Tray\+Manager which you can use. See Loading Bar below.

\subsection*{The Null Tray}

In addition to the nine trays you can place your widgets in, there is also a \char`\"{}null tray\char`\"{}. This is an imaginary tray, whose location is specified by {\ttfamily T\+L\+\_\+\+N\+O\+NE}. This tray is virtual, invisible, and does not arrange widgets within it. Basically, if you place a widget in this tray, it becomes \char`\"{}free-\/floating\char`\"{}, and you\textquotesingle{}re allowed to manually position it anywhere on the screen. Widgets must always reside in a tray for as long as they exist, so when a widget is removed from a tray, it is automatically placed in the null tray.\hypertarget{trays_special-widgets}{}\subsection{Special Widgets}\label{trays_special-widgets}
Some widgets are so common they deserve special treatment.

\subsection*{Frame Stats}

This is not exactly one widget, but a combination of Label that displays the current F\+PS, and a Params\+Panel that displays advanced frame statistics (such as average F\+PS and batch count). Use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a49e2f792fee94e75b1b472826bcc8019}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Frame\+Stats}} and {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a1c2e9618a3e6b061a9cfeac4f2cb55e9}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Frame\+Stats}} to show/hide this special widget. You can choose where to put it. When the user clicks the F\+PS label, it toggles the visibility of the advanced frame stats, so they can be out of the way when they\textquotesingle{}re unwanted. You can also manually toggle the visibility of the advanced frame stats using {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_aed00f8a1009f2ebf6806774cb894d0d7}{Ogre\+Bites\+::\+Tray\+Manager\+::toggle\+Advanced\+Frame\+Stats}}.

\subsection*{Logo}

This is just a decor widget of the O\+G\+RE logo. Use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_affee57f47066e25437649d64daaa7dd9}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Logo}} and {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_ac1ee637b7ef5e887170c8a9aca1c4c7b}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Logo}} to show/hide the logo. You can choose where to put it.

\subsection*{Loading Bar}

This is a progress bar that shows you the progress of your current resource loading job. The comment box will show the current resource being loaded. Use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a0d51005a4b148a4df2c1c6b55e34f085}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Loading\+Bar}} before you begin your loading job. Specify the number of resource groups you will initialise, the number of groups you will load, and, if you want to, the proportion of time you think will go to initialisation (default estimate is 70\%). You cannot decide where to place this loading bar. The screen will be darkened, and the loading bar will appear in the center. Any other dialog or loading bar will be closed. When you finish your loading job, call {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_aab014a2c48c8f91556182e42684d44ad}{Ogre\+Bites\+::\+Tray\+Manager\+::hide\+Loading\+Bar}}.

\subsection*{Information Dialog}

This is a dialog which tells the user something and displays an OK button. It\textquotesingle{}s a combination of a Text\+Box and a Button. Use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_abf3bd8e4ef9a6d0d76f27535a6010623}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Ok\+Dialog}} to display an information dialog. Specify the caption of the Text\+Box, and the message you want to display in it. Any other dialog or loading bar will be closed. The screen will be darkened, and the dialog will appear in the center. All other widget interactions are disabled until the dialog is closed. You can manually close a dialog using {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_af5d95dcaa7c74d3345308e4f4e3035e8}{Ogre\+Bites\+::\+Tray\+Manager\+::close\+Dialog}}. To respond to information dialog closing events, see the Tray\+Listenersection below.

\subsection*{Question Dialog}

Same as the Information Dialog except it asks the user something and displays a Yes button and a No button. Use {\ttfamily \hyperlink{class_ogre_bites_1_1_tray_manager_a85d47aa11d761742884dc6457ec11cdf}{Ogre\+Bites\+::\+Tray\+Manager\+::show\+Yes\+No\+Dialog}} to display a question dialog. Specify the caption of the Text\+Box, and the question you want to display in it. To respond to question dialog closing events, see the Tray\+Listener section below.\hypertarget{trays_tray-listener}{}\subsection{Tray\+Listener}\label{trays_tray-listener}
This class contains handlers for all the different events that your widgets can fire. The Tray\+Manager class itself is an Tray\+Listener, because it responds to events from its special widgets. You should extend your sample class from Tray\+Listener as well as Sample if you want to handle widget events. If you\textquotesingle{}re using Sdk\+Sample, you\textquotesingle{}re all set because it\textquotesingle{}s already an Tray\+Listener. Some widgets give you an option of not firing an event when you change their state. This is helpful for initialising or resetting a widget, in which case there shouldn\textquotesingle{}t be a response of any sort. For example, if you\textquotesingle{}re initialising your slider bar before the scene is set up, and your slider bar is used to control some part of your scene, firing an event would cause an error. Below is a list of the different handlers. All handlers have return type void.
\begin{DoxyItemize}
\item {\bfseries button\+Hit}\+: Gives you a pointer to the Button which was hit.
\item {\bfseries item\+Selected}\+: Gives you a pointer to the Select\+Menu the item was chosen from. You can then use the Select\+Menu to see which item was selected.
\item {\bfseries label\+Hit}\+: Gives you a pointer to the Label that was clicked.
\item {\bfseries slider\+Moved}\+: Gives you a pointer to the Slider whose value was changed. You can then use the Slider to see what its new value is. Also, you can convert this value into a more suitable form and display it using Slider\+::set\+Displayed\+Value.
\item {\bfseries check\+Box\+Toggled}\+: Gives you a pointer to the Check\+Box whose state was changed. You can then use the Check\+Box to see if it\textquotesingle{}s been checked or unchecked.
\item {\bfseries ok\+Dialog\+Closed}\+: Gives you the message of the OK dialog that was closed.
\item {\bfseries yes\+No\+Dialog\+Closed}\+: Gives you the question of the Yes-\/\+No dialog that was closed, and a boolean indicating whether or not the Yes button was pressed.
\end{DoxyItemize}\hypertarget{trays_things-to-try}{}\subsection{Things to Try}\label{trays_things-to-try}
Getting access to widgets\+: 
\begin{DoxyCode}
Button* b;
b = (Button*)mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a97c3f74f3b947200c6fed0c465b78556}{getWidget}(\textcolor{stringliteral}{"MyButton"});  \textcolor{comment}{// by name}
b = (Button*)mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a97c3f74f3b947200c6fed0c465b78556}{getWidget}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}, 0);  \textcolor{comment}{// by tray and position}
b = (Button*)mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a97c3f74f3b947200c6fed0c465b78556}{getWidget}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}, \textcolor{stringliteral}{"MyButton"});  \textcolor{comment}{// by tray and name}
b = (Button*)mTrayMgr->getWidgetIterator(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}).getNext();  \textcolor{comment}{// by iterator}
\end{DoxyCode}
 Counting widgets\+: 
\begin{DoxyCode}
\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{int} n = mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a992a25c65079b1882fd29806d5d4467b}{getNumWidgets}();  \textcolor{comment}{// total}
\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{int} n = mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a992a25c65079b1882fd29806d5d4467b}{getNumWidgets}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT});  \textcolor{comment}{// by tray}
\end{DoxyCode}
 Moving widgets to other trays\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(b, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(b, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6a2d593eb6164a5b842e985e8252c3bd}{TL\_BOTTOM}, 1);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6a2d593eb6164a5b842e985e8252c3bd}{TL\_BOTTOM}, 1, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6bc278d85090ab3af3dc01472c1a83f2}{TL\_RIGHT}, 3);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6bc278d85090ab3af3dc01472c1a83f2}{TL\_RIGHT}, 3, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a6a2d593eb6164a5b842e985e8252c3bd}{TL\_BOTTOM});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(\textcolor{stringliteral}{"MyButton"}, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530ae4e5c068e88e5c0561a2c30dca2ec5a5}{TL\_TOP}, \textcolor{stringliteral}{"MyButton"}, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT});
\end{DoxyCode}
 Removing widgets from trays\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}(b);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}(\textcolor{stringliteral}{"MyButton"});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_ac2f939d0bd36af335a78589b462506e9}{removeWidgetFromTray}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}, 0);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a35ae90e6dbe0c86e18ee171078fd1266}{moveWidgetToTray}(b, \hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a04a1085bdee61d7234849663cce08664}{TL\_NONE});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a77ba6e4d641c146e262b6cdd2c8b04a0}{clearTray}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a9787ec5e8989bf6cfa89d03c6ddd27b6}{clearAllTrays}();
\end{DoxyCode}
 Destroying widgets\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a4ba9ec359b55a612fc860f69cecd96a7}{destroyWidget}(b);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a4ba9ec359b55a612fc860f69cecd96a7}{destroyWidget}(\textcolor{stringliteral}{"MyButton"});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a4ba9ec359b55a612fc860f69cecd96a7}{destroyWidget}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}, 0);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a4a89cd6f7d87e0e538aa842f1a42a7bc}{destroyAllWidgetsInTray}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT});
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_aadb1f5a3b7e3b5397b10bdd3449e1603}{destroyAllWidgets}();
\end{DoxyCode}
 Finding the position of a widget in a tray\+: 
\begin{DoxyCode}
\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{int} pos = mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_aa993d2b60cfbcb903aecbff1c4896b67}{locateWidgetInTray}(b);
\end{DoxyCode}
 Finding the tray a widget is in\+: 
\begin{DoxyCode}
\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530}{TrayLocation} trayLoc = b->getTrayLocation();
\end{DoxyCode}
 Changing the tray listener object\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a3235fea714a0c61e463dee69ae308be8}{setListener}(newListener);
\end{DoxyCode}
 Toggling system visibility\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a075805136b2241cbb03eeb2c3d27b40d}{showAll}();
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a188f1d5f5ca16af3b28d11ecd553105a}{hideAll}();
\end{DoxyCode}
 Changing horizontal widget alignment in one tray\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_adfbbc97615fd5f1a939be6e7a1f00c07}{setTrayWidgetAlignment}(\hyperlink{namespace_ogre_bites_a637c114a713225e37b0f0316f5da3530a0ea49133cba5ca84010b7df05947ca13}{TL\_LEFT}, \hyperlink{group___overlays_gga3396780cdb2d731aa5e4389148bdc5f3a270f18cf07dbe4e75e1b790d02924205}{GHA\_RIGHT});
\end{DoxyCode}
 Changing spacing and padding\+: 
\begin{DoxyCode}
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a33a3e3f66a3989dd3de48b4c4577422f}{setWidgetSpacing}(5);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a52d3fc8638533540232232c37b257de6}{setWidgetPadding}(3);
mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a866229b6d88dc9d3a609115eaab46e67}{setTrayPadding}(12);
\end{DoxyCode}
 Casting 3D ray from under cursor into the scene\+: 
\begin{DoxyCode}
Ray r = mTrayMgr->\hyperlink{class_ogre_bites_1_1_tray_manager_a9dd5d303968329462e9bf4225f59722e}{getCursorRay}(mCamera);
\end{DoxyCode}
 Casting 3D ray from any 2D screen coordinate into the scene\+: 
\begin{DoxyCode}
Ray r = \hyperlink{class_ogre_bites_1_1_tray_manager_a6833f46b0303b559a050f310fa0204fc}{OgreBites::TrayManager::screenToScene}(mCamera, Vector2(320, 24
      0));
\end{DoxyCode}
 Converting a 3D scene coordinate to a 2D screen coordinate\+: 
\begin{DoxyCode}
Vector2 p = \hyperlink{class_ogre_bites_1_1_tray_manager_aa7a456c2c0c37123e2ab0e497f2c0ccc}{OgreBites::TrayManager::sceneToScreen}(mCamera, 
      Vector3::ZERO);
\end{DoxyCode}
 \hypertarget{volume}{}\section{Volume Component}\label{volume}
Welcome to the Volume Component of O\+G\+RE. It is a component to render volumes. It can handle any volume data but featurewise has a tedency towards terrains. The terrain aspect means, that it\textquotesingle{}s all about huge meshes being displayed with high performance via a level of detail mechanism. Thanks to volume rendering, caves, cliffes, holes and similar geometry can be displayed. Also constructive solid geometry gets easy.

A dense list of the features\+:
\begin{DoxyItemize}
\item Volume Rendering via Dual Marching Cubes
\item L\+OD mechanism via a chunk tree and marching squares skirts for crack patching
\item Data-\/\+Sources\+: 3D Textures with density values and the ability to buildup a C\+S\+G-\/\+Tree with 3D Textures, Spheres, Cubes, Planes, Intersection, Union, Difference and Negation, Simplex\+Noise addition
\item Loading a 3D Texture Scene from config files
\item An own file format for discrete density values which compresses a lot better
\item Realtime editing
\item Serialization and Deserialization from and to an own file format for discrete density values which compresses a lot better than 3D textures
\item A triplanar texturing example material
\item A triplanar texturing Sub\+Render\+State for the R\+T\+SS
\end{DoxyItemize}

This documentation is only intended for the usage of the Volume Component, not the algorithms which make it work. If you want to get to know the theory behind it, you can read the articles on this page\+: \href{http://volume-gfx.com/}{\tt http\+://volume-\/gfx.\+com/}\hypertarget{volume_howto}{}\subsection{How to use it}\label{volume_howto}
Here is an example loading the volume scene from a configuration file. The configuration file must be findable by the resource system of course. Only \char`\"{}\+Ogre\+Volume\+Chunk.\+h\char`\"{} has to be included. 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_volume_1_1_chunk}{Ogre::Volume::Chunk} *volumeRoot = \hyperlink{group___general_gab5fc1358fd5a889de0a06d07e45df1ff}{OGRE\_NEW} 
      \hyperlink{class_ogre_1_1_volume_1_1_chunk}{Ogre::Volume::Chunk}();
SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\textcolor{stringliteral}{"VolumeParent"});
volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_a9557d5a30cbf29a46d4f8246a1e6d176}{load}(volumeRootNode, mSceneMgr, \textcolor{stringliteral}{"volumeTerrain.cfg"});
\end{DoxyCode}
 The first line creates the volume chunk which is the Movable\+Object holding the Volume-\/\+Root. Next, a Scene\+Node is created where the volume(-\/tree) is attached to. And lastly, the volume is loaded from the configuration file \char`\"{}volume\+Terrain.\+cfg\char`\"{}. m\+Scene\+Mgr is the Scene\+Manager who should show the volume. Later, when you don\textquotesingle{}t need it anymore, you have to free the volume\+Root Chunk via O\+G\+R\+E\+\_\+\+D\+E\+L\+E\+TE.\hypertarget{volume_creation}{}\subsection{Manual creation of a C\+S\+G-\/\+Tree}\label{volume_creation}
This example skips the configuration file and loads a simple C\+S\+G-\/\+Scene\+: An union of a 3D Texture and a sphere with 5 L\+OD levels. It also setups a material L\+OD system. First, create a sphere with the radius 5 at the coordinates 128, 150, 128\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_volume_1_1_c_s_g_sphere_source}{Ogre::Volume::CSGSphereSource} sphere (5, Vector3(128, 150, 128));
\end{DoxyCode}
 Now a 3D texture from \char`\"{}volume\+Terrain\+Big.\+dds\char`\"{} which has the world dimensions 256, 256, 256. The next flag indicates that the trilinear interpolation of the value-\/selection should be activated. We switch off the trilinear interpolation and the sobel filter of the normal for the sake of faster loading times\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_volume_1_1_texture_source}{Ogre::Volume::TextureSource} volumeTexture (\textcolor{stringliteral}{"volumeTerrainBig.dds"}, 256, 256, 256
      , \textcolor{keyword}{true}, \textcolor{keyword}{false}, \textcolor{keyword}{false});
\end{DoxyCode}
 Now combine them\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_volume_1_1_c_s_g_union_source}{Ogre::Volume::CSGUnionSource} unionSrc (&sphere, &volumeTexture);
\end{DoxyCode}
 Set the general parameters, see the comments for their meaning\+: 
\begin{DoxyCode}
\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters}{Ogre::Volume::ChunkParameters} parameters;
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a3e154a179b8c824f79b1b426608743ad}{sceneManager} = mSceneMgr;       \textcolor{comment}{// The SceneManager to use}
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a111c9e9333e7ae3497fc818190a03fd8}{src} = &unionSrc;                \textcolor{comment}{// The just created density source.}
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a4444eac27c71e02886615dcf7fbfed27}{baseError} = (\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})1.8;          \textcolor{comment}{// The error of the highest LOD-level}
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_aa6186649b7323f937b83828eb86711fa}{errorMultiplicator} = (\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})0.9; \textcolor{comment}{// The factor between each LOD-level
       (error = baseError * errorMultiplicator  * level)}
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a986b4a97b153d50f65603ab507bb4614}{skirtFactor} = (\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})0.7;        \textcolor{comment}{// Controls how long the skirts are. The lower
       the number, the shorter the skirts are. This saves geometry. But if they are too short, cracks might occure.}
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_af6ed62b76c67d04eb98424414fb1dc72}{scale} = 10;                     \textcolor{comment}{// The displayed volume will be scaled by this factor.}
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_ae125003c00de0d6c0a1a4bd6b99c4ebf}{maxScreenSpaceError} = 30;       \textcolor{comment}{// The screen space error controlling when
       the LOD-levels change.}
\end{DoxyCode}


Create the root-\/chunk and load now. The two vectors define the area to be scanned in the volume-\/source. The following integer determines the amount of L\+O\+D-\/levels. 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_volume_1_1_chunk}{Ogre::Volume::Chunk} *volumeRoot = \hyperlink{group___general_gab5fc1358fd5a889de0a06d07e45df1ff}{OGRE\_NEW} Chunk();
volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_a9557d5a30cbf29a46d4f8246a1e6d176}{load}(mVolumeRootNode, Vector3::ZERO, Vector3(256), 5, &parameters);
\end{DoxyCode}
 Now setup the global volume material\+: 
\begin{DoxyCode}
volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_a5129bccc53d17060635ada67443324f7}{setMaterial}(\textcolor{stringliteral}{"triplanarReference"});
\end{DoxyCode}
 \hypertarget{volume_triangles}{}\subsection{Getting the triangles of the chunks}\label{volume_triangles}
When you want to integrate the volume triangles in a physics engine for example, you need to hand over the exact triangles. For this scenario, the Chunk\+Parameters hold a pointer to a \textquotesingle{}\textquotesingle{}Mesh\+Builder\+Callback\textquotesingle{}\textquotesingle{} and a number \textquotesingle{}\textquotesingle{}lod\+Callback\+Lod\textquotesingle{}\textquotesingle{}. The first is an interface with a single function \textquotesingle{}\textquotesingle{}triangles\+Ready\textquotesingle{}\textquotesingle{} which is called, when the triangles of a chunk are ready. The chunks are chosen via the \textquotesingle{}\textquotesingle{}lod\+Callback\+Lod\textquotesingle{}\textquotesingle{}. If you build a volume with 3 L\+OD levels and you want the triangles of the highest detail level, you set this parameter to 3. Example\+:


\begin{DoxyCode}
\textcolor{keyword}{class }MyMeshBuilderCallback : \textcolor{keyword}{public} MeshBuilderCallback
\{
\textcolor{keyword}{public}:
    \textcolor{keyword}{virtual}  ready(\textcolor{keyword}{const} SimpleRenderable *simpleRenderable, \textcolor{keyword}{const} \hyperlink{group___volume_ga42533278f4be6a1aeae58d18255d0ca1}{VecVertex} &vertices, \textcolor{keyword}{const} 
      \hyperlink{group___volume_ga00db3f974951d99d4a0902580eeb8151}{VecIndices} &indices, \textcolor{keywordtype}{size\_t} level, \textcolor{keywordtype}{int} inProcess)
    \{
        \textcolor{keywordtype}{size\_t} count = indices.size();
        \textcolor{keywordflow}{for} (\textcolor{keywordtype}{size\_t} i = 0; i < count; i += 3)
        \{
            \hyperlink{group___volume_ga90facc4b1e8fd828ae06b8edd0f5b701}{Vertex} v1 = vertices[indices[i]];
            \hyperlink{group___volume_ga90facc4b1e8fd828ae06b8edd0f5b701}{Vertex} v2 = vertices[indices[i + 1]];
            \hyperlink{group___volume_ga90facc4b1e8fd828ae06b8edd0f5b701}{Vertex} v3 = vertices[indices[i + 2]];
            \textcolor{comment}{// Do something with the Triangle...}
        \}
    \}
\};
\end{DoxyCode}


And using it like this\+: 
\begin{DoxyCode}
\hyperlink{group___volume_ga89fbc5eed010b8802358563eb88e674a}{ChunkParameters} parameters;
...
MyMeshBuilderCallback callback;
parameters.\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a6403e2875cc7b81aefd43ba9f22c2b31}{lodCallback} = &callback;
parameters.lodCallbackLod = 3;
...
rootChunk->load(parent, from, to, 3, &parameters);
\end{DoxyCode}
 Or in case of loading from a configuration file\+: 
\begin{DoxyCode}
MyMeshBuilderCallback callback;
rootChunk->load(parent, sceneManager, \textcolor{stringliteral}{"myVolume.cfg"}, 0, &callback, 3);
\end{DoxyCode}


You might have seen, that a pointer to a Simple\+Renderable is handed in, too. This is actually the Chunk whose triangles are loaded. It\textquotesingle{}s parent class is used to not create a circular dependency. You might get the triangle data from it, too by getting the Renderoperation.\hypertarget{volume_intersecting}{}\subsection{Intersecting a ray with a volume}\label{volume_intersecting}
When you want to do something exactly on the volume surface, you can cast rays and find their first intersection point. Behold that the triangle representation might be slightly different than the actual volume surface. And you have to scale the ray origin just like the volume. Here is an example which uses the negative z-\/axis of the camera as ray as it might be done like in an ego-\/shooter\+: 
\begin{DoxyCode}
Ray ray(mCamera->getPosition() / rootChunk->getScale(), -mCamera->getOrientation().zAxis());
Vector3 intersection;
\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real} scale = mVolumeRoot->getChunkParameters()->scale;
\textcolor{keywordtype}{bool} intersects = mVolumeRoot->getChunkParameters()->src->getFirstRayIntersection(ray, intersection, scale)
      ;
\textcolor{keywordflow}{if} (intersects)
\{
    intersection *= scale; \textcolor{comment}{// As it is in volume space.}
    \textcolor{comment}{// Do something with intersection.}
\}
\end{DoxyCode}
\hypertarget{volume_editing}{}\subsection{Editing a Volume made from a Grid\+Source}\label{volume_editing}
A usecase is realtime editing of volume terrain as seen as in the sample. Let\textquotesingle{}s union the terrain with a sphere of the radius 2.\+5 and the center 123/123/123. {\bfseries volume\+Root} is the Chunk instance with which the terrain was initially loaded. The factor 1.\+5 is just to have a save border arround the sphere which also gets updated. The rest of the parameters are 5 L\+OD levels and a volume mesh covering an area of 384$^\wedge$3. 
\begin{DoxyCode}
Vector3 center(123);
\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real} radius = (\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})2.5;
CSGSphereSource sphere(radius, center);
CSGUnionSource operation;
\textcolor{keyword}{static\_cast<}GridSource*\textcolor{keyword}{>}(volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}()->\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_a111c9e9333e7ae3497fc818190a03fd8}{src})->combineWithSource(&
      operation, &sphere, center, radius * (\hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})1.5);
volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}()->\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_aeefacd1d618206fcb432ed947b58e06e}{updateFrom} = center - radius * (
      \hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})1.5;
volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}()->\hyperlink{struct_ogre_1_1_volume_1_1_chunk_parameters_afe30999e8cc71a1f48d87d68bf43059d}{updateTo} = center + radius * (
      \hyperlink{namespace_ogre_aa3a7b6dfb905e6572d62f0dfa3d4274d}{Real})1.5;
volumeRoot->\hyperlink{class_ogre_1_1_volume_1_1_chunk_a9557d5a30cbf29a46d4f8246a1e6d176}{load}(volumeRootNode, Vector3::ZERO, Vector3(384), 5, volumeRoot->
      \hyperlink{class_ogre_1_1_volume_1_1_chunk_acdc6b1e00c67353f3317e1e0ce6d19d9}{getChunkParameters}());
\end{DoxyCode}
 \hypertarget{manual-mesh-creation}{}\section{Manual mesh creation}\label{manual-mesh-creation}
There are two ways to create your own mesh. The first way is to create a \hyperlink{class_ogre_1_1_mesh}{Ogre\+::\+Mesh} instance and provide it with the vertex and index buffers directly.

The second way is the high level \hyperlink{class_ogre_1_1_manual_object}{Ogre\+::\+Manual\+Object} interface. Instead of filling position and color buffers, you simply call the \char`\"{}position\char`\"{} and \char`\"{}colour\char`\"{} functions.

\section*{Using Manual Object}

Building one-\/off geometry objects manually usually requires getting down and dirty with the vertex buffer and vertex declaration A\+PI, which some people find a steep learning curve. This class gives you a simpler interface specifically for the purpose of building a 3D object simply and quickly. Note that if you intend to instance your object you will still need to become familiar with the Mesh class.

This class draws heavily on the interface for Open\+GL immediate-\/mode ({\ttfamily gl\+Begin}, {\ttfamily gl\+Vertex}, {\ttfamily gl\+Normal} etc), since this is generally well-\/liked by people. There are a couple of differences in the results though -\/ internally this class still builds hardware buffers which can be re-\/used, so you can render the resulting object multiple times without re-\/issuing all the same commands again. Secondly, the rendering is not immediate, it is still queued just like all O\+G\+RE objects. This makes this object more efficient than the equivalent GL immediate-\/mode commands, so it\textquotesingle{}s feasible to use it for large objects if you really want to.

To construct some geometry with this object\+:
\begin{DoxyEnumerate}
\item If you know roughly how many vertices (and indices, if you use them) you\textquotesingle{}re going to submit, call estimate\+Vertex\+Count() and estimate\+Index\+Count(). This is not essential but will make the process more efficient by saving memory reallocations.
\item Call begin() to begin entering data
\item For each vertex, call position(), normal(), texture\+Coord(), colour() to define your vertex data. Note that each time you call position() you start a new vertex. Note that the first vertex defines the components of the vertex -\/ you can\textquotesingle{}t add more after that. For example if you didn\textquotesingle{}t call normal() in the first vertex, you cannot call it in any others. You ought to call the same combination of methods per vertex.
\item If you want to define triangles (or lines/points) by indexing into the vertex list, you can call index() as many times as you need to define them. If you don\textquotesingle{}t do this, the class will assume you want triangles drawn directly as defined by the vertex list, i.\+e. non-\/indexed geometry. Note that stencil shadows are only supported on indexed geometry, and that indexed geometry is a little faster; so you should try to use it.
\item Call end() to finish entering data.
\item Optionally repeat the begin-\/end cycle if you want more geometry using different rendering operation types, or different materials After calling end(), the class will organise the data for that section internally and make it ready to render with. Like any other Movable\+Object you should attach the object to a Scene\+Node to make it visible. Other aspects like the relative render order can be controlled using standard Movable\+Object methods like set\+Render\+Queue\+Group.
\end{DoxyEnumerate}

You can also use begin\+Update() to alter the geometry later on if you wish. If you do this, you should call set\+Dynamic(true) before your first call to begin(), and also consider using estimate\+Vertex\+Count() / estimate\+Index\+Count() if your geometry is going to be growing, to avoid buffer recreation during growth.

\begin{DoxyNote}{Note}
like all O\+G\+RE geometry, triangles should be specified in anti-\/clockwise winding order (whether you\textquotesingle{}re doing it with just vertices, or using indexes too). That is to say that the front of the face is the one where the vertices are listed in anti-\/clockwise order.
\end{DoxyNote}
\subsection*{Example}

We will use the Manual\+Object to create a single textured plane. After creating the object, we start a new geometry block that will use the given material


\begin{DoxyCodeInclude}
    \hyperlink{class_ogre_1_1_manual_object}{Ogre::ManualObject}* man = mSceneMgr->createManualObject(\textcolor{stringliteral}{"test"});
    man->\hyperlink{class_ogre_1_1_manual_object_a70d5945478fbc7fa056cecd88fdf2781}{begin}(\textcolor{stringliteral}{"Examples/OgreLogo"}, \hyperlink{class_ogre_1_1_render_operation_a7a272218dae54048c87f31176c19e10da8c00ee152b44fe8000c2fd675437c087}{Ogre::RenderOperation::OT\_TRIANGLE\_LIST}
      );
\end{DoxyCodeInclude}
 Next we specify the vertices of the plane


\begin{DoxyCodeInclude}
    man->\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}(-20, 20, 20);
    man->\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}(0, 0, 1);
    man->\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}(0, 0);

    man->\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}(-20, -20, 20);
    man->\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}(0, 0, 1);
    man->\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}(0, 1);

    man->\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}(20, -20, 20);
    man->\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}(0, 0, 1);
    man->\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}(1, 1);

    man->\hyperlink{class_ogre_1_1_manual_object_a9986bd2627b75deeba14636c81efcde0}{position}(20, 20, 20);
    man->\hyperlink{class_ogre_1_1_manual_object_a59c0b0a41e2a4ced5ff89589c9a924a1}{normal}(0, 0, 1);
    man->\hyperlink{class_ogre_1_1_manual_object_a64854d64967680d2294788768ebbd1d7}{textureCoord}(1, 0);
\end{DoxyCodeInclude}
 Now we can define the face. Ogre will split the quad into triangles for us.


\begin{DoxyCodeInclude}
    man->\hyperlink{class_ogre_1_1_manual_object_a1ac70dbc6f35180d5c8bab671c3f2257}{quad}(0, 1, 2, 3);
\end{DoxyCodeInclude}
 Calling {\ttfamily end()} creates the actual Hardware Buffers to be used for rendering and we can attach the Object to a \hyperlink{class_ogre_1_1_scene_node}{Ogre\+::\+Scene\+Node}.


\begin{DoxyCodeInclude}
    man->\hyperlink{class_ogre_1_1_manual_object_a49d6bfe460ff1e0178c6d77b95d3dc5a}{end}();
    mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man);
\end{DoxyCodeInclude}
 In case you need multiple Ogre\+::\+Entities of the plane, you should call \hyperlink{class_ogre_1_1_manual_object_a657275e617d9558951a3037f02b07efe}{Ogre\+::\+Manual\+Object\+::convert\+To\+Mesh} first and then use \hyperlink{class_ogre_1_1_scene_manager_afb393cca49de8b928f7dd60838047185}{Ogre\+::\+Scene\+Manager\+::create\+Entity} as usual.

\section*{Using vertex and index buffers directly}

This time we are going to create a plane using the lower level \hyperlink{class_ogre_1_1_hardware_buffer}{Ogre\+::\+Hardware\+Buffer} primitives.

We start by creating a Mesh object. As this is a manual Mesh, we have to set the bounds of it explicitly. 
\begin{DoxyCode}
\textcolor{keyword}{using namespace }\hyperlink{namespace_ogre}{Ogre};

        \hyperlink{class_ogre_1_1_shared_ptr}{MeshPtr} mesh = \hyperlink{class_ogre_1_1_mesh_manager_a2efefa307b7987c5fcff7e8c47f79758}{MeshManager::getSingleton}().
      \hyperlink{class_ogre_1_1_mesh_manager_ad99f5f2e2d045e5a4af301974e45c918}{createManual}(yourMeshName, \textcolor{stringliteral}{"General"});
        mesh->\hyperlink{class_ogre_1_1_mesh_a8c40c34ec7c32009904c0cd730f68b5d}{\_setBounds}(\hyperlink{class_ogre_1_1_axis_aligned_box}{AxisAlignedBox}(\{-100,-100,0\}, \{100,100,0\});
\end{DoxyCode}


Next we define what should end up in our vertex and index buffer. We will store all data interleaved in one buffer. This typically has some advantages due to cache coherency and also is what Manual\+Object does automatically for us.


\begin{DoxyCodeInclude}
        \textcolor{keywordtype}{float} vertices[32] = \{
            -100, -100, 0,  \textcolor{comment}{// pos}
            0,0,1,          \textcolor{comment}{// normal}
            0,1,            \textcolor{comment}{// texcoord}
            100, -100, 0,
            0,0,1,
            1,1,
            100,  100, 0,
            0,0,1,
            1,0,
            -100,  100, 0 ,
            0,0,1,
            0,0 
        \};

        \hyperlink{namespace_ogre_aa8263b218e7d187ad5ef03a73a6ad7fd}{uint16} faces[6] = \{0,1,2,
                           0,2,3 \};
\end{DoxyCodeInclude}
 However we could also split the data into multiple buffers with lower precision to save some bytes on texture coordinates and normals.

To describe the vertex sources, we have to create a \hyperlink{class_ogre_1_1_vertex_data}{Ogre\+::\+Vertex\+Data} object. Notably it stores how many vertices we have.


\begin{DoxyCodeInclude}
        mesh->\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData} = \textcolor{keyword}{new} VertexData();
        mesh->\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}->\hyperlink{class_ogre_1_1_vertex_data_a0b59b63cc2dbede1c5fc6a932fd2c10d}{vertexCount} = 4;
        VertexDeclaration* decl = mesh->\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}->
      \hyperlink{class_ogre_1_1_vertex_data_abac9cde9c001b97cf1fea7fd05b79cf4}{vertexDeclaration};
        VertexBufferBinding* bind = mesh->\hyperlink{class_ogre_1_1_mesh_a1fd9968ccd424f913a7f3f68639f3ecf}{sharedVertexData}->
      \hyperlink{class_ogre_1_1_vertex_data_a1cf7dacb2a133d71620abd59cb3180b0}{vertexBufferBinding};
\end{DoxyCodeInclude}
 The actual description of our vertex buffer however is stored inside the \hyperlink{class_ogre_1_1_vertex_declaration}{Ogre\+::\+Vertex\+Declaration}.


\begin{DoxyCodeInclude}
        \textcolor{keywordtype}{size\_t} offset = 0;
        decl->addElement(0, offset, \hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa9ccf920d2572b15896f75ccf30fb150c}{VET\_FLOAT3}, \hyperlink{group___render_system_gga0a62b3f2ede8992ff365bb013a8bc00dad04d50e91c2ec5377e610b3f5b9b07f2}{VES\_POSITION});
        offset += VertexElement::getTypeSize(\hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa9ccf920d2572b15896f75ccf30fb150c}{VET\_FLOAT3});
        decl->addElement(0, offset, \hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa9ccf920d2572b15896f75ccf30fb150c}{VET\_FLOAT3}, \hyperlink{group___render_system_gga0a62b3f2ede8992ff365bb013a8bc00da1dec7d36a64625348e23af26c9231227}{VES\_NORMAL});
        offset += VertexElement::getTypeSize(\hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa9ccf920d2572b15896f75ccf30fb150c}{VET\_FLOAT3});
        decl->addElement(0, offset, \hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa0993ccf616ec6e7bf60fff2ef1705ce6}{VET\_FLOAT2}, 
      \hyperlink{group___render_system_gga0a62b3f2ede8992ff365bb013a8bc00da17abb855311f3a67bc31414cad8d6212}{VES\_TEXTURE\_COORDINATES}, 0);
        offset += VertexElement::getTypeSize(\hyperlink{group___render_system_gga027109503a988ba85f4c63b55082907fa0993ccf616ec6e7bf60fff2ef1705ce6}{VET\_FLOAT2});
\end{DoxyCodeInclude}
 Now we can continue to create the Hardware Buffers and upload our data.


\begin{DoxyCodeInclude}
        \hyperlink{namespace_ogre_a05ef9b65d4ed446b994636e371bf5aab}{HardwareVertexBufferSharedPtr} vbuf =
            HardwareBufferManager::getSingleton().createVertexBuffer(
                offset, 4, HardwareBuffer::HBU\_STATIC\_WRITE\_ONLY);
        vbuf->\hyperlink{class_ogre_1_1_hardware_buffer_a8c313688a0df3c28a36738c31fcbc3ee}{writeData}(0, vbuf->getSizeInBytes(), vertices, \textcolor{keyword}{true});
        bind->setBinding(0, vbuf);

        \hyperlink{namespace_ogre_ae906cf8e579ba8ade19879ec05b1a456}{HardwareIndexBufferSharedPtr} ibuf = HardwareBufferManager::getSingleton
      ().createIndexBuffer(
            HardwareIndexBuffer::IT\_16BIT, 6, HardwareBuffer::HBU\_STATIC\_WRITE\_ONLY);
        ibuf->\hyperlink{class_ogre_1_1_hardware_buffer_a8c313688a0df3c28a36738c31fcbc3ee}{writeData}(0, ibuf->getSizeInBytes(), faces, \textcolor{keyword}{true});
\end{DoxyCodeInclude}
 Note how we used the symbolical constant {\ttfamily 0} to link the \hyperlink{class_ogre_1_1_hardware_vertex_buffer}{Ogre\+::\+Hardware\+Vertex\+Buffer} to the \hyperlink{class_ogre_1_1_vertex_declaration}{Ogre\+::\+Vertex\+Declaration}. This allows the underlying Render\+System to swap Vertex\+Buffers without changing the Vertex\+Declaration. i.\+e. render different Meshes that share the same vertex layout, without changing the state.

Finally we create the \hyperlink{class_ogre_1_1_sub_mesh}{Ogre\+::\+Sub\+Mesh} that will be ultimately rendered.


\begin{DoxyCodeInclude}
        SubMesh* sub = mesh->\hyperlink{class_ogre_1_1_mesh_a23d5c021503b8fac8938be4ba956f2ce}{createSubMesh}();
        sub->\hyperlink{class_ogre_1_1_sub_mesh_a931e3764e3bf1c3ef7431fc852770fb1}{useSharedVertices} = \textcolor{keyword}{true};
        sub->indexData->indexBuffer = ibuf;
        sub->indexData->indexCount = 6;
        sub->indexData->indexStart = 0;
\end{DoxyCodeInclude}
 Note that while our Vertex\+Buffer is shared, the Index\+Buffer is not. This allows rendering different faces of the same object using different Materials. Here each Sub\+Mesh links the faces (Index\+Buffer) to the according material. \hypertarget{profiler}{}\section{Using the Profiler}\label{profiler}
\begin{DoxyNote}{Note}
If you are using the \hyperlink{namespace_ogre}{Ogre} S\+DK and you want to use the Profiler, it is advisable to switch to the source code version of \hyperlink{namespace_ogre}{Ogre}, because the S\+DK is shipped with {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG=O\+FF}, so Profiling is disabled by default.
\end{DoxyNote}
First you want to initialize the Profiler like this\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}().\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}(\textcolor{keyword}{true});
\end{DoxyCode}
 This sets up the media that the profiler uses. The reason this is not in the constructor is because the profiler contains media dependencies that people who aren\textquotesingle{}t using the profiler shouldn\textquotesingle{}t have to worry about. The profiler will need you to specify the main program loop. To do this, you call the following at the very beginning of the frame\+Started() function in your Frame\+Listener class\+: 
\begin{DoxyCode}
\hyperlink{_ogre_profiler_8h_af9d7ab83c5a5d7de7579eebe9d27e53d}{OgreProfileBegin}(\textcolor{stringliteral}{"Ogre Main Loop"});
\end{DoxyCode}
 and add this at the very end of the frame\+Ended() function\+: 
\begin{DoxyCode}
\hyperlink{_ogre_profiler_8h_a292ec22b5d851ef26fa9d7685c18b1f5}{OgreProfileEnd}(\textcolor{stringliteral}{"Ogre Main Loop"});
\end{DoxyCode}
 Make sure the names match exactly, otherwise the profiler will fail an assert. Next you want to profile some of your code. You do this by calling \hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{Ogre\+Profile()} and using braces (\{\}) to limit the scope. Note that Ogre\+Profile cannot be called in the same scope as another \hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{Ogre\+Profile()}. Doing so will result in a compile-\/time error. Here is an example of using Ogre\+Profile\+: 
\begin{DoxyCode}
\{
   \hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{OgreProfile}(\textcolor{stringliteral}{"Collision Detection"});
   mISQR = mISQ->execute();
\}
\{
   \hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{OgreProfile}(\textcolor{stringliteral}{"Collision Response"});
   SceneQueryMovableIntersectionList::iterator iter;
   \textcolor{keywordflow}{for} (iter = mISQR.movables2movables.begin(); iter != mISQR.movables2movables.end(); iter++) \{
      \textcolor{comment}{// do stuff}
      \hyperlink{_ogre_profiler_8h_a1654899e6cfdec9f0972a45f3fa3fee7}{OgreProfile}(\textcolor{stringliteral}{"Explosions"});
      createExplosion();
   \}
\}
\end{DoxyCode}
 If you want a profile to last outside of its scope, use \hyperlink{_ogre_profiler_8h_af9d7ab83c5a5d7de7579eebe9d27e53d}{Ogre\+Profile\+Begin($<$name$>$)} and \hyperlink{_ogre_profiler_8h_a292ec22b5d851ef26fa9d7685c18b1f5}{Ogre\+Profile\+End($<$name$>$)} like you did when creating the main loop profile.

\section*{Reading the Display}

On the left side are the profile names with a number in parentheses next to it. This number is the number of times this profile was called during this frame. If this number is 0, that means that the profile was called before, but is not being called currently. The bars on the left represent the frame time statistics. You can see indicators above which show that a profile can take anywhere from 0\% to 100\% of the frame time. The big yellow bars show the current frame percentage that the profile is taking. The green line shows the minimum frame time, the red line is the maximum frame time, and the blue line is the average frame time. Big discrepancies between the average and maximum can possibly be the sign of a performance bottleneck (however it could be the profiler acting strangely, see the \textquotesingle{}\textquotesingle{}Known Issues\textquotesingle{}\textquotesingle{} section). These results will be printed to the log when the application ends or you can manually do it by calling log\+Results().

\section*{Features}

\subsection*{Disabling the Profiler}

You can disable the profiler by calling\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}().\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}(\textcolor{keyword}{false});
\end{DoxyCode}
 and enable it again by calling\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}().\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}(\textcolor{keyword}{true});
\end{DoxyCode}
 Note that this is a temporary solution. If you want to completely disable the profiler for your release version, see the section \textquotesingle{}\textquotesingle{}Release Version Considerations\textquotesingle{}\textquotesingle{}.

\subsection*{Disabling Individual Profiles}

Disabling profiles can be useful if there are certain core functions that you want to profile on occasion. For example, you could profile certain rendering operations when you are checking general performance and then disable those profiles when you want to profile your AI code. You can disable a profile like this\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_a144fc3944f41b1198a44590beda4ce3f}{disableProfile}(\textcolor{stringliteral}{"<profile name>"});
\end{DoxyCode}
 and you can enable it again with this\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_a52e2f0d3530febbbf7199173d91ad4e2}{enableProfile}(\textcolor{stringliteral}{"<profile name>"});
\end{DoxyCode}
 Please note that trying to enable or disable a profile while that profile is running will have no effect.

\subsection*{Analyzing Application State}

It is helpful to see the state of your application when a profile reaches a maximum level or some other condition. To check if a specific has reached a new maximum level, use\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_afc737d10ba6b5732df9a538a196ee3e6}{watchForMax}(\textcolor{stringliteral}{"<profile name>"}); \textcolor{comment}{// return
       true if it reaches a new maximum}
\end{DoxyCode}
 or to see if a profile has reached a new minimum level, use\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_ad37efd3a99cf736a0424fd0c1c92efb4}{watchForMin}(\textcolor{stringliteral}{"<profile name>"}); \textcolor{comment}{//
       returns true if it reaches a new minimum}
\end{DoxyCode}
 or to set an arbitrary level\+: 
\begin{DoxyCode}
\textcolor{comment}{//returns true when AI code takes over 60% of the frame time}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_adfd868a7f9213baece5687bd36e23279}{watchForLimit}(\textcolor{stringliteral}{"AI code"}, .6, \textcolor{keyword}{true});

\textcolor{comment}{//returns true when graphics code takes less than 10% of the frame time}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_adfd868a7f9213baece5687bd36e23279}{watchForLimit}(\textcolor{stringliteral}{"Graphics code"}, .1, \textcolor{keyword}{
      false});
\end{DoxyCode}


These functions should be used at the end of the main game loop for more accuracy. Otherwise, it will represent the results of the previous frame.

\subsection*{Logging Results}

You can log the results of the current profiler statistics like this\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().\hyperlink{class_ogre_1_1_profiler_a456a0f133ccea3eb515626edd22963ec}{logResults}();
\end{DoxyCode}
 This is called automatically when you quit your \hyperlink{namespace_ogre}{Ogre} application.

\subsection*{Changing the Frequency of Updating the Display}

You can change how frequently the display is updated to suit your tastes like this\+: 
\begin{DoxyCode}
\hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}.\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{getSingleton}().
      \hyperlink{class_ogre_1_1_profiler_ac29d425e0f0b531f2c7f643907c9402d}{setUpdateDisplayFrequency}(<numberOfFrames>);
\end{DoxyCode}
 Basically the tradeoff is between how accurate the display is and the amount of flicker. The default is that the display is updated every 10 frames.

\section*{Performance and Accuracy}

I\textquotesingle{}ve tried to minimize the performance hit from using the profiler. However, like anything else, it still takes some time to perform the necessary calculations. There are some steps you can take to increase the accuracy of the results. Firstly, although the profiler supports multiple calls of a profile during each frame, doing this more than a few times can cause the profiler to take significantly longer than the actual code you are trying to profile. Therefore it is recommended that you move the profile up one level (such as outside of a for loop) so that it is called fewer times.

To maximize the accuracy of a profile, it is best to remove the child profiles of the profile you are analysing. Child profiles increases the frame time of the parent due to the overhead of using the profiler.

Some tests I\textquotesingle{}ve conducted show that the profiling code will max out unexpectedly, so take the maximum frame time value with a grain of salt (See the {\itshape Known Issues} section). I think this only happens when a profile is first created, so you can possibly get around this issue by calling the reset() function after the first frame.

\section*{Release Version Considerations}

For the release version of your app, you should set {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG=O\+FF} in C\+Make. If the build you are using has been compiled with the {\ttfamily O\+G\+R\+E\+\_\+\+P\+R\+O\+F\+I\+L\+I\+NG=O\+FF} and you still want to use the profiler without recompiling your S\+DK, a quick workaround is to instantiate a dummy profiler like this\+:


\begin{DoxyCode}
\textcolor{comment}{// Create dummy profile to set singleton pointer}
\textcolor{keyword}{new} \hyperlink{class_ogre_1_1_profiler}{Ogre::Profiler}();

\textcolor{comment}{// Give it a timer and enable it}
\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}().\hyperlink{class_ogre_1_1_profiler_a53a2d2681a3995555df6d789c5596381}{setTimer}(Root::getSingleton().getTimer()
      );
\hyperlink{class_ogre_1_1_profiler_aaa925dad8392fe140d017a5766f3cd49}{Ogre::Profiler::getSingleton}().\hyperlink{class_ogre_1_1_profiler_a91c40e21a3fc96003504ea21fec80d77}{setEnabled}(\textcolor{keyword}{true});
\end{DoxyCode}


The profiler will now work but the 3 Ogre\+Profile macro will not work. You will have to manually use the begin\+Profile() and end\+Profile() method. You can also instantiate scope-\/limited Profile objects or simply define your own macros somewhere in your code.


\begin{DoxyCode}
\textcolor{preprocessor}{#define MyOgreProfile( a ) Ogre::Profile \_OgreProfileInstance( (a) )}
\textcolor{preprocessor}{#define MyOgreProfileBegin( a ) Ogre::Profiler::getSingleton().beginProfile( (a) )}
\textcolor{preprocessor}{#define MyOgreProfileEnd( a ) Ogre::Profiler::getSingleton().endProfile( (a) )}
\end{DoxyCode}
 \hypertarget{External-Texture-Sources}{}\section{External Texture Sources}\label{External-Texture-Sources}
This tutorial will provide a brief introduction of External\+Texture\+Source and External\+Texture\+Source\+Manager classes, their relationship, and how the Plug\+Ins work. For those interested in developing a Texture Source Plugin or maybe just wanting to know more about this system, take a look the ffmpeg\+Video\+System plugin, which you can find more about on the O\+G\+RE forums.

\label{_What-Is-An-External-Texture-Source_003f}%


\section*{What Is An External Texture Source?}

What is a texture source? Well, a texture source could be anything -\/ png, bmp, jpeg, etc. However, loading textures from traditional bitmap files is already handled by another part O\+G\+RE. There are, however, other types of sources to get texture data from -\/ i.\+e. mpeg/avi/etc movie files, flash, run-\/time generated source, user defined, etc.

How do external texture source plugins benefit O\+G\+RE? Well, the main answer is\+: adding support for any type of texture source does not require changing O\+G\+RE to support it... all that is involved is writing a new plugin. Additionally, because the manager uses the String\+Interface class to issue commands/params, no change to the material script reader is needs to be made. As a result, if a plugin needs a special parameter set, it just creates a new command in it’s Parameter Dictionary. -\/ see ffmpeg\+Video\+System plugin for an example. To make this work, two classes have been added to O\+G\+RE\+: External\+Texture\+Source \& External\+Texture\+Source\+Manager.

\label{_ExternalTextureSource-Class}%


\section*{External\+Texture\+Source Class}

The \hyperlink{class_ogre_1_1_external_texture_source}{Ogre\+::\+External\+Texture\+Source} class is the base class that Texture Source Plug\+Ins must be derived from. It provides a generic framework (via String\+Interface class) with a very limited amount of functionality. The most common of parameters can be set through the Texture\+Plug\+In\+Source class interface or via the String\+Interface commands contained within this class. While this may seem like duplication of code, it is not. By using the string command interface, it becomes extremely easy for derived plugins to add any new types of parameters that it may need.

Default Command Parameters defined in External\+Texture\+Source base class are\+:


\begin{DoxyParams}{Parameters}
{\em filename} & Sets a filename plugin will read from \\
\hline
{\em play\+\_\+mode} & Sets initial play mode to be used by the plugin -\/ \char`\"{}play\char`\"{}, \char`\"{}loop\char`\"{}, \char`\"{}pause\char`\"{} \\
\hline
{\em set\+\_\+\+T\+\_\+\+P\+\_\+S} & Used to set the technique, pass, and texture unit level to apply this texture to. As an example\+: To set a technique level of 1, a pass level of 2, and a texture unit level of 3, send this string \char`\"{}1 2 3\char`\"{}. \\
\hline
{\em frames\+\_\+per\+\_\+second} & Set a Frames per second update speed. (Integer Values only)\\
\hline
\end{DoxyParams}
\label{_ExternalTextureSourceManager-Class}%


\section*{External\+Texture\+Source\+Manager Class}

External\+Texture\+Source\+Manager is responsible for keeping track of loaded Texture Source Plug\+Ins. It also aids in the creation of texture source textures from scripts. It also is the interface you should use when dealing with texture source plugins.

\begin{DoxyNote}{Note}
The function prototypes shown below are mockups -\/ param names are simplified to better illustrate purpose here...
\end{DoxyNote}
Steps needed to create a new texture via External\+Texture\+Source\+Manager\+:


\begin{DoxyItemize}
\item Obviously, the first step is to have the desired plugin included in plugin.\+cfg for it to be loaded.
\item Set the desired Plug\+In as Active via Advanced\+Texture\+Manager\+::get\+Singleton().Set\+Current\+Plug\+In( String Type ); – type is whatever the plugin registers as handling (e.\+g. \char`\"{}video\char`\"{}, \char`\"{}flash\char`\"{}, \char`\"{}whatever\char`\"{}, etc).
\item Note\+: Consult Desired Plug\+In to see what params it needs/expects. Set params/value pairs via Advanced\+Texture\+Manager\+::get\+Singleton().get\+Current\+Plug\+In()-\/$>$set\+Parameter( String Param, String Value );
\item After required params are set, a simple call to Advanced\+Texture\+Manager\+::get\+Singleton().get\+Current\+Plug\+In()-\/$>$create\+Defined\+Texture( s\+Material\+Name ); will create a texture to the material name given.
\end{DoxyItemize}

The manager also provides a method for deleting a texture source material\+: Advanced\+Texture\+Manager\+::\+Destroy\+Advanced\+Texture( String s\+Texture\+Name ); The destroy method works by broadcasting the material name to all loaded Texture\+Source\+Plug\+Ins, and the Plug\+In who actually created the material is responsible for the deletion, while other Plug\+Ins will just ignore the request. What this means is that you do not need to worry about which Plug\+In created the material, or activating the Plug\+In yourself. Just call the manager method to remove the material. Also, all texture plugins should handle cleanup when they are shutdown.

\label{_Texture-Source-Material-Script}%


\section*{Texture Source Material Script}

As mentioned earlier, the process of defining/creating texture sources can be done within material script file. Here is an example of a material script definition -\/ Note\+: This example is based off the ffmpeg\+Video\+System plugin parameters.


\begin{DoxyCode}
material Example/MyVideoExample
\{
    technique
    \{
        pass
        \{
            texture\_unit
            \{
                texture\_source video
                \{
                    filename mymovie.mpeg
                    play\_mode play
                    sound\_mode on
                \}
            \}
        \}
    \}
\}
\end{DoxyCode}


Notice that the first two param/value pairs are defined in the External\+Texture\+Source base class and that the third parameter/value pair is not defined in the base class... That parameter is added to the param dictionary by the ffmpeg\+Video\+Plugin... This shows that extending the functionality with the plugins is extremely easy. Also, pay particular attention to the line\+: texture\+\_\+source video. This line identifies that this texture unit will come from a texture source plugin. It requires one parameter that determines which texture plugin will be used. In the example shown, the plugin requested is one that registered with \char`\"{}video\char`\"{} name.

\label{_Simplified-Diagram-of-Process}%


\section*{Simplified Diagram of Process}

This diagram uses ffmpeg\+Video\+Plugin as example, but all plug ins will work the same in how they are registered/used here. Also note that Texture\+Source Plugins are loaded/registered before scripts are parsed. This does not mean that they are initialized... Plugins are not initialized until they are set active! This is to ensure that a rendersystem is set up before the plugins might make a call the rendersystem.

 \hypertarget{ShadowMappingOgre}{}\section{Shadow Mapping in Ogre}\label{ShadowMappingOgre}
\hypertarget{_shadow_mapping_ogre_ShadowMappingIntro}{}\subsection{Introduction to the Shadow Mapping Algorithm}\label{_shadow_mapping_ogre_ShadowMappingIntro}
Shadow mapping, an algorithm introduced by Lance Williams  {\bfseries [W\+I\+L78]} and now prevalent in real-\/time and off-\/line rendering, is based on a simple idea\+: First, a snapshot of the scene is taken from the viewpoint of the light. Then, when creating an image from the perspective of the camera, the light’s snapshot is used to determine visibility. Parts of the scene seen by both the light and the camera must be lit (by the light in question). Parts of the scene visible only to the camera must be shadowed. We do not care about parts of the scene seen only by the light.

In practice, the snapshot from the viewpoint of the light is stored as a floating point depth buffer. It is important to use a format that supports enough precision to avoid shadow acne (z-\/fighting) on lit surfaces. In \hyperlink{namespace_ogre}{Ogre}, we can specify the depth format to use; in the example code, we will choose the 32-\/bit format.

Once shadow determination has occurred (whether a fragment is in shadow or not), \hyperlink{namespace_ogre}{Ogre} provides two different ways to render the shadows into the final image. The modulative technique will uniformly darken regions of the image determined to be in shadow. This is a cheaper and less accurate lighting model. For instance, specular highlights in shadow will appear as darkened specular highlights. The other technique is additive light masking. This technique builds up contributions from each light in non-\/shadowed areas and adds them together to create the final image. The code in section \hyperlink{_shadow_mapping_ogre_Implementation}{Implementation} will use additive light masking, but could just as easily be adapted for modulative shadows.\hypertarget{_shadow_mapping_ogre_sm_formalism}{}\subsubsection{Formalism}\label{_shadow_mapping_ogre_sm_formalism}
Mathematically, the process can be represented as follows\+: Let $P_l$ and $P_c$ be the projection matrices for the light and camera respectively. Let $M_l$ and $M_c$ be the modelview matrices for the light and camera coordinate systems. Let $\vec{x} = [x_1,x_2,x_3,1]^t$ be a point in object space, $\vec{y} = [y_1,y_2,y_3,1]^t$ the screen space coordinates, and $\vec{u} = [u_1,u_2,u_3,1]^t$ the shadow map coordinates.

\[ \begin{aligned} \left[ \begin{array}{c} u_1 w_l \\ u_2 w_l \\ u_3 w_l \\ w_l \end{array} \right] = P_l M_l \left[ \begin{array}{c} x_1 \\ x_2 \\ x_3 \\ 1 \end{array} \right]\end{aligned} \]

\[\begin{aligned} \left[ \begin{array}{c} y_1 w_c \\ y_2 w_c \\ y_3 w_c \\ w_c \end{array} \right] = P_c M_c \left[ \begin{array}{c} x_1 \\ x_2 \\ x_3 \\ 1 \end{array} \right]\end{aligned}\]

These equations can be written more concisely as\+: $\vec{u}w_l = P_l M_l \vec{x}$ and $\vec{y} w_c = P_c M_c \vec{x}$. Division of $\vec{u}w_l$ and $\vec{y}w_c$ by their respective homogeneous coordinates yields the Euclidean representations $\vec{u}$ and $\vec{y}$.

Note that while $P_c$ and $M_c$ are completely determined by the camera image we want to produce, we have some ambiguity in the $P_l$ and $M_l$ chosen for shadow mapping. The degrees of freedom here are later exploited to combat the aliasing issue.\hypertarget{_shadow_mapping_ogre_DepthBias}{}\subsubsection{Depth Biasing}\label{_shadow_mapping_ogre_DepthBias}


Due to the finite precision of floating point representations and inherent inability of one number to represent a range of values, it is often necessary to add a little bias to the depth values stored in a shadow map. One does not simply store the $u_3$ value. Figure \mbox{[}fig\+:bias\mbox{]} illustrates the issue. Here we have used blue dots on the light’s image plane to represent boundaries between shadow “texels.\+” The interval in between the dots then represents a shadow map sample for which a single depth value (float) is stored. For the sample whose boundary rays are shown, the red dot’s depth is saved. However, note that from the camera’s perspective, any (camera) image point in between the two drawn camera rays will hit the scene geometry within the shadow map sample’s interval. Hence, the same shadow map sample depth will be used to determine visibility for all such camera pixels. Camera pixels whose rays fall to the right of the red dot will be marked as shadowed, while pixels whose rays fall to the left of the red dot will be marked as lit. This is not the right behavior because clearly all the pixels should be marked as lit. As we can see, a depth bias is needed. By pushing the shadow map sample’s depth farther (to the 2nd red dot), we can achieve correct shadow determination.

One could approach the depth bias issue in a completely $\ast$ad hoc$\ast$ manner, but it is possible to do better. One would ideally compute a bias that depends on how depth ( $u_3$) changes between shadow map samples. The change in depth as one moves a unit step (to the next shadow map sample) represents the ambiguity of the depth value. Such a value may seem intractable to compute, but calculus and linear algebra save the day. From calculus, we learn that the derivative provides the best linear approximation to any function ( $u_3 = u_3(u_1, u_2)$ in particular). In multiple dimensions, this role is played by the Jacobian (matrix of partial derivatives). In other words, we want to compute $\frac{du_3}{du_1}$ and $\frac{du_3}{du_2}$, where we have treated $u_3$ as a function of $u_1$ and $u_2$. Once these values are computed, it makes sense to then add some weighted combination of these to the stored depth value (e.\+g., some scale of the Jacobian’s Frobenius norm).

But even if the light is staring at a plane straight on (view direciton lines up with plane’s normal), making $\frac{du_3}{du_1}$ and $\frac{du_3}{du_2}$ both zero, we would still need a slight offset because rounding due to the float’s finite representation may still cause shadow acne. In this case, we’d like to offset the depth by a small value that pushes it beyond rounding ambiguity. While one could use an arbitrary constant offset, this is unsatisfactory since the constant in light image space corresponds to varying amounts of offset in light space (pre-\/projection Euclidean space with light’s position at origin). Let us instead choose a constant offset in the z direction of $\ast$light space$\ast$ and compute what the offset for a particular sample should be in $\ast$light image space$\ast$. In Ogre’s example code, the small constant offset in light space is chosen to be 1 unit. If 1 is not a small amount in your engine’s chosen scale, you can easily change this choice. At any rate, the relevant quantity is $\frac{\partial u_3}{\partial X_3}$ where $\vec{X} = M_l \vec{x}$.

The choices here closely mirror what Open\+GL implements through gl\+Polygon\+Offset. The second adjustment is slightly different since Open\+GL chooses a vendor specific fudge factor.

Equations for computing the stated quantities are provided below. One need not wade through these to use the depth biasing code. Understanding what the relevant parameters explained above are (in case adjustment is needed) is sufficient.

\[\begin{aligned} \label{eqn:dxqdu} \frac{\partial (\vec{x} q_l)}{\partial u_i} = \mbox{i-th column of } M_l^{-1} P_l^{-1} V_l^{-1} \end{aligned}\]

where $V_l$ is the viewport matrix for the light and $i=1,2,3$. $q_l$ turns out to be $1/w_l$.

\[\begin{aligned} \label{eqn:dxdu} \frac{\partial \vec{x}}{\partial u_i} = \frac{1}{q_l} \left( \frac{\partial (\vec{x} q_l)}{\partial u_i} - \vec{x}\frac{\partial q_l}{\partial u_i} \right) \\ \label{eqn:du3du} \frac{du_3}{du_j} = \left( \vec{n} \cdot \frac{\partial \vec{x}}{\partial u_3} \right)^{-1} \left( \vec{n} \cdot \frac{\partial \vec{x}}{\partial u_j} \right)\end{aligned}\]

where $\vec{n}$ is the normal at point $\vec{x}$ and $j=1,2$. Note that (\mbox{[}eqn\+:du3du\mbox{]}) is exactly the set of values needed for the first part.

\[\begin{aligned} \label{eqn:duwdX3} \frac{\partial (\vec{u} w_l)}{\partial X_3} = \mbox{3rd column of } P_l \\ \label{eqn:dudX3} \frac{\partial \vec{u}}{\partial X_3} = \frac{1}{w_l} \left( \frac{\partial (\vec{u} w_l)}{\partial X_3} - \vec{u}\frac{\partial w_l}{\partial X_3} \right)\end{aligned}\]

Note that (\mbox{[}eqn\+:dud\+X3\mbox{]}) is the quantity needed for the second bias term. This is also the term to scale for different choices of small offset in light space. If 0.\+01 units is the small offset, scale this value by 0.\+01.\hypertarget{_shadow_mapping_ogre_sm_pcm}{}\subsubsection{Percentage Closest Filtering}\label{_shadow_mapping_ogre_sm_pcm}
As widely known, shadow mapping can exhibit significant aliasing. When this happens during texture mapping we apply filtering. We’d like to apply a similar principle with shadow maps, but filtering depth values is categorically the wrong thing to do. As described in  {\bfseries [R\+S\+C87]}, one should instead filter depth test results. This is termed percentage closest filtering. Ideally this would be a filtering technique much like anisotropic texture filtering, but for simplicity and efficiency, Ogre’s example code implements the bilinear analogue.\hypertarget{_shadow_mapping_ogre_sm_variants}{}\subsection{Variants}\label{_shadow_mapping_ogre_sm_variants}
There are many shadow mapping variants. Enumerating (much less describing) all of them would take us too far afield in this article. We instead defer to the provided references and google for such coverage. The many variants can, however, be broken up into three broad categories\+:
\begin{DoxyEnumerate}
\item Those that store additional information beyond a single float,
\item those that divide up shadow frusta into multiple frusta to be handled separately, and
\item those that propose less naive $P_l$ and $M_l$ to use and thereby affect the sampling distribution.
\end{DoxyEnumerate}

Algorithms in each category usually work quite independently and so many hybrid approaches are easily conceivable.\hypertarget{_shadow_mapping_ogre_sm_additional_info}{}\subsubsection{Storing Additional Info}\label{_shadow_mapping_ogre_sm_additional_info}
One example of this is Deep Shadow Maps  {\bfseries [L\+V00]}. In this work, instead of storing a single depth value and treating visibility as a binary value, a transfer function is stored and visibility is continuous. This algorithm is important in offline movie rendering, but also relevant to the Variance Shadow Mapping algorithm elucidated by the game developer community  {\bfseries [D\+L06]}.

While variance shadow maps are motivated by statistical considerations, it is perhaps more properly understood in the Deep Shadow Maps framework. Analyzing it in terms of distributions is flawed for two reasons\+:
\begin{DoxyEnumerate}
\item the inequality considered is valid only for unimodal distributions whereas depth values are often discontinuous in regions that matter;
\item the inequality is treated as equality. The equations are justified with a very specific example in which two planes are viewed straight on. In practice there are very noticeable halo effects around objects, which makes more heuristic tweaks necessary.
\end{DoxyEnumerate}

Recasting this into the framework of deep shadow maps, we see that the proposed equality is simply a particular functional approximation to the transfer function. Variance shadow maps proposes a two-\/parameter family of approximation functions whose parameters are linearly interpolated in the usual way. This viewpoint allows for analysis and also suggests the possibility of getting improvements via other approximating functional forms.\hypertarget{_shadow_mapping_ogre_sm_breaking_frusta}{}\subsubsection{Breaking up Shadow Frusta}\label{_shadow_mapping_ogre_sm_breaking_frusta}
Adaptive Shadow Maps  {\bfseries [F\+F\+B01]} are an example of this. It is still largely considered too expensive for real-\/time rendering, but continued research and growing G\+PU power may make some variant worthwhile.\hypertarget{_shadow_mapping_ogre_sect_planeopt}{}\subsubsection{Playing with Projection Matrices}\label{_shadow_mapping_ogre_sect_planeopt}
There are various heuristic approaches for choosing $P_l$ and $M_l$, but here we will focus on one method, the Plane Optimal algorithm  {\bfseries [Chong04]}, that provides a particular guarantee. For this algorithm, we specify a plane of interest (e.\+g., ground plane, wall, table top) for which we want perfect shadowing no matter the configuration of light and camera in the scene (even dueling frusta). The algorithm will then compute $P_l$ and $M_l$ so that the mapping between camera image and light image is the identity when restricted to the plane. If the shadow map matches the resolution of the screen, then each pixel gets exactly one shadow sample. Shadows off the plane of interest have no guarantees. One limitation of the method is shown in Figure \mbox{[}fig\+:planeopt\mbox{]}. Only region I will be shadowed and self-\/shadowed properly, with points on the plane being shadowed perfectly (alias-\/free). This makes the method perhaps most useful for games where the view is top-\/down or isometric (like R\+TS games). It is also useful for cases like dueling frusta (where just about all other methods fail).

\hypertarget{_shadow_mapping_ogre_sm_theory}{}\subsection{Theory and Analysis}\label{_shadow_mapping_ogre_sm_theory}
A full discussion of shadow map analysis is beyond the scope of this article. For those interested, the references  {\bfseries [Chong06]} and  {\bfseries [Chong04]} are good (in my extremely biased opinion). Note that as research papers, they are quite concise. Unfortunately there don’t seem to more step-\/by-\/step expositions available at this moment.

There has been a lot of academic and industry research on improving shadow maps. However, analyses presented on shadow maps often do not say what people claim they say. These faulty conclusions usually come from considering very special cases and assuming the general case is very similar. For clarification, we explore some of these misconceptions here.\hypertarget{_shadow_mapping_ogre_sm_nonopt}{}\subsubsection{(\+Non)\+Optimality of Logarithmic Shadow Maps}\label{_shadow_mapping_ogre_sm_nonopt}
We start with one {\itshape heuristic} that has gained quite a bit of traction\+: the idea of using some logarithmic mapping between light space and light image space instead of a projective transform. A number of algorithms based on this idea have been proposed, and even some hardware changes. Much of this work seems to be motivated by the incorrect assumption that logarithmic mappings are optimal.

The very special motivating case is this\+: The camera looks down the z axis. Directional light illuminates the scene perpendicular to the z axis. An angled piece of a plane is viewed by the camera. As the angled piece of plane is pulled along the camera ray direction, using a logarithmic shadow map gives us constant shadow quality on this geometric piece. But unless we’re rendering translucent dust particles along a camera ray, this analysis is irrelevant. If the dust particles are not translucent, we only care about shadow determination on the first one, not a whole line of them. If we are rendering continuous surfaces (resp. curves), we care about the quality as one moves in the tangent plane (resp. tangent) direction because this is the best linear approximation to the surface (resp. curve), not the camera ray direction.

In fact, in the case of a chosen plane of interest for example, we know we can get completely alias free shadow mapping using a projective transform (section \hyperlink{_shadow_mapping_ogre_sect_planeopt}{Playing with Projection Matrices}). Logarithmic shadow maps may be an interesting heuristic to try out, but certainly not worth changing hardware over in my opinion. If you’re going to change hardware, might as well aim for true optimality.\hypertarget{_shadow_mapping_ogre_sm_aliasing}{}\subsubsection{Sampling Aliasing versus Depth Precision Aliasing}\label{_shadow_mapping_ogre_sm_aliasing}
Sometimes people tend to conflate these two sources of aliasing. They note that after applying some sort of custom projective transform, the depth values are warped as well. This problem can be completely overcome via the depth replacement method prescribed in Trapezoidal Shadow Maps  {\bfseries [M\+T04]}. So this is a completely orthogonal issue. Depth precision can be just as good as “normal” shadow maps, no matter the perspective warp used to affect sampling.\hypertarget{_shadow_mapping_ogre_sm_proj_aliasing}{}\subsubsection{Projective versus Perspective Aliasing}\label{_shadow_mapping_ogre_sm_proj_aliasing}
The terms perspective and projective aliasing appeared in the Perspective Shadow Maps  {\bfseries [S\+D02]} paper and has since been used extensively by those who work on improving shadow heuristics. Often it is claimed that methods ameliorate perspective aliasing while projective aliasing is either unavoidable or must be addressed via completely separate means. However, the distinction between the two is somewhat artificial. Both result from not allocating enough shadow map samples to regions that matter to the viewer. As the Plane Optimal algorithm demonstrates, it is possible to completely remove projective aliasing (as well as perspective aliasing) in certain scenes. In general, there should be one combined measure of aliasing and algorithms must minimize this quantity. See  {\bfseries [Chong06]} for a unified notion of aliasing.\hypertarget{_shadow_mapping_ogre_Implementation}{}\subsection{Implementation}\label{_shadow_mapping_ogre_Implementation}
\hyperlink{namespace_ogre}{Ogre} provides a powerful framework that allows us to do a lot of shadow map customization. In \hyperlink{namespace_ogre}{Ogre}, we turn on custom shadow mapping through the scene manager (here, scene\+Mgr). It is recommended that this happen early as it may affect how certain resources are loaded.


\begin{DoxyCode}
\textcolor{comment}{// Use Ogre's custom shadow mapping ability}
sceneMgr->setShadowTexturePixelFormat(\hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39ca2da3ec4fe727d552337e02069cd9efd9}{PF\_FLOAT32\_R});
sceneMgr->setShadowTechnique( \hyperlink{group___general_gga79dcd426d291c31072c1ad6f183715d6a8a2b43e30e6d8d590e6853e4f46b8103}{SHADOWTYPE\_TEXTURE\_ADDITIVE} );
sceneMgr->setShadowTextureCasterMaterial(\textcolor{stringliteral}{"Ogre/DepthShadowmap/Caster/Float"});
sceneMgr->setShadowTextureReceiverMaterial(\textcolor{stringliteral}{"Ogre/DepthShadowmap/Receiver/Float"});
sceneMgr->setShadowTextureSelfShadow(\textcolor{keyword}{true}); 
sceneMgr->setShadowTextureSize(1024);
\end{DoxyCode}


The set\+Shadow\+Technique call is all that is required for Ogre’s default shadow mapping. In the code above, we have told \hyperlink{namespace_ogre}{Ogre} to use the R channel of a floating point texture to store depth values. This tends to be a very portable method (over graphics cards and A\+P\+Is). The sample uses 1024x1024 shadow maps. Self-\/shadowing is turned on, but be warned that this will only work properly if appropriate depth biasing is also used. The example code will manually account for depth biasing via the method described above in section \hyperlink{_shadow_mapping_ogre_DepthBias}{Depth Biasing}. The shadow caster and shadow receiver materials are defined in a materials script. They tell \hyperlink{namespace_ogre}{Ogre} which shaders to use when rendering shadow casters into the shadow map and rendering shadow receivers during shadow determination.

The {\ttfamily Depth\+Shadowmap.\+material} script is given below\+:


\begin{DoxyCodeInclude}
\textcolor{comment}{// Generic Shadow caster material (floating point shadowmap)}
material \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/Caster/Float
\{
    technique
    \{
        pass 
        \{
            vertex\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/CasterVP
            \{
            \}
            fragment\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/CasterFP
            \{
            \}
        \}
    \}
\}

\textcolor{comment}{// Generic Shadow receiver material (floating point shadowmap)}
material \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/Receiver/Float
\{
    technique
    \{
        pass 
        \{
            vertex\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/ReceiverVP
            \{
            \}
            fragment\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/ReceiverFP
            \{
            \}
            texture\_unit ShadowMap
            \{
                tex\_address\_mode clamp
                filtering none
            \}
        \}
    \}
\}


\textcolor{comment}{// Specific receiver material for rockwall}
material \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/Receiver/RockWall
\{

    \textcolor{comment}{// This is the preferred technique which uses both vertex and}
    \textcolor{comment}{// fragment programs, supports coloured lights}
    technique
    \{
        \textcolor{comment}{// Base ambient pass}
        pass
        \{
            \textcolor{comment}{// base colours, not needed for rendering, but as information}
            \textcolor{comment}{// to lighting pass categorisation routine}
            ambient 1 1 1
            diffuse 0 0 0 
            specular 0 0 0 0 
            
            depth\_bias -1
        \}
        \textcolor{comment}{// Now do the lighting pass}
        \textcolor{comment}{// NB we don't do decal texture here because this is repeated per light}
        pass lighting
        \{
            \textcolor{comment}{// base colours, not needed for rendering, but as information}
            \textcolor{comment}{// to lighting pass categorisation routine}
            ambient 0 0 0 
            
            \textcolor{comment}{// do this for each light}
            iteration once\_per\_light

        
            scene\_blend add
            
            \textcolor{comment}{// Vertex program reference}
            vertex\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/ReceiverVP
            \{
            \}
            shadow\_receiver\_vertex\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/ReceiverVP
            \{
            \}

            \textcolor{comment}{// Fragment program}
            fragment\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/ReceiverFP
            \{
            \}
            shadow\_receiver\_fragment\_program\_ref \hyperlink{namespace_ogre}{Ogre}/DepthShadowmap/ReceiverFP
            \{
            \}

            \textcolor{comment}{// shadowmap texture will be bound by code}

        \}
        
        \textcolor{comment}{// Decal pass}
        pass
        \{
            \textcolor{comment}{// base colours, not needed for rendering, but as information}
            \textcolor{comment}{// to lighting pass categorisation routine}
            lighting off


            scene\_blend dest\_colour zero

            depth\_bias 1
            
            texture\_unit
            \{
                texture rockwall.tga
            \}
            
        \}
    \}


\}
\end{DoxyCodeInclude}
 The material uses unified programs for H\+L\+SL, G\+L\+SL and G\+L\+S\+L\+ES. We’ll present the G\+L\+SL code below. Note that while most of the shader files are direct translations of each other, DirectX H\+L\+SL shaders must handle percentage closest filtering slightly differently from Open\+GL. Open\+GL chooses the convention of having integers index sample centers whereas DirectX chooses integers to index sample corners. Also note the variable names in the shaders presented below are slightly different from those presented earlier in this document. This is due in part to the awkwardness of expressing subscripts in variable names and also in part because $u_3$ is less evocative of depth than $z$, etc. With minimal effort one can match the shader equations with those presented earlier. The code is presented here mostly to demonstrate how things fit together.


\begin{DoxyCodeInclude}
\textcolor{preprocessor}{#version 120}

uniform mat4 worldViewProj;
uniform vec4 texelOffsets;

attribute vec4 vertex;

varying vec2 depth;

\textcolor{keywordtype}{void} main()
\{
    vec4 outPos = worldViewProj * vertex;
    outPos.xy += texelOffsets.zw * outPos.w;
    \textcolor{comment}{// fix pixel / texel alignment}
    depth = outPos.zw;
    gl\_Position = outPos;
\}

\end{DoxyCodeInclude}


This is a pretty standard vertex shader.


\begin{DoxyCodeInclude}
\textcolor{preprocessor}{#version 120}

varying vec2 depth;

\textcolor{keywordtype}{void} main()
\{
    \textcolor{keywordtype}{float} finalDepth = depth.x / depth.y;

    \textcolor{comment}{// just smear across all components }
    \textcolor{comment}{// therefore this one needs high individual channel precision}
    gl\_FragColor = vec4(finalDepth, finalDepth, finalDepth, 1.0);
\}

\end{DoxyCodeInclude}


Just write out the depth values here. We compute the bias and derivatives in the receiver.


\begin{DoxyCodeInclude}
\textcolor{preprocessor}{#version 120}

uniform mat4 world;
uniform mat4 worldIT;
uniform mat4 worldViewProj;
uniform mat4 texViewProj;
uniform vec4 lightPosition;
uniform vec4 lightColour;

attribute vec4 vertex;
attribute vec3 normal;

varying vec4 oUv;
varying vec4 outColor;

\textcolor{keywordtype}{void} main()
\{
    gl\_Position = worldViewProj * vertex;
    
    vec4 worldPos = world * vertex;

    vec3 worldNorm = (worldIT * vec4(normal, 1.0)).xyz;

    \textcolor{comment}{// calculate lighting (simple vertex lighting)}
    vec3 lightDir = normalize(
        lightPosition.xyz - (worldPos.xyz * lightPosition.w));

    outColor = lightColour * max(dot(lightDir, worldNorm), 0.0);

    \textcolor{comment}{// calculate shadow map coords}
    oUv = texViewProj * worldPos;
\}

\end{DoxyCodeInclude}


This is a pretty standard vertex shader as well.


\begin{DoxyCodeInclude}
\textcolor{preprocessor}{#version 120}

uniform \textcolor{keywordtype}{float} inverseShadowmapSize;
uniform \textcolor{keywordtype}{float} fixedDepthBias;
uniform \textcolor{keywordtype}{float} gradientClamp;
uniform \textcolor{keywordtype}{float} gradientScaleBias;

uniform sampler2D shadowMap;

varying vec4 oUv;
varying vec4 outColor;

\textcolor{keywordtype}{void} main()
\{
    vec4 shadowUV = oUv;
    \textcolor{comment}{// point on shadowmap}
    shadowUV = shadowUV / shadowUV.w;
    \textcolor{keywordtype}{float} centerdepth = texture2D(shadowMap, shadowUV.xy).x;
    
    \textcolor{comment}{// gradient calculation}
    \textcolor{keywordtype}{float} pixeloffset = inverseShadowmapSize;
    vec4 depths = vec4(
        texture2D(shadowMap, shadowUV.xy + vec2(-pixeloffset, 0)).x,
        texture2D(shadowMap, shadowUV.xy + vec2(+pixeloffset, 0)).x,
        texture2D(shadowMap, shadowUV.xy + vec2(0, -pixeloffset)).x,
        texture2D(shadowMap, shadowUV.xy + vec2(0, +pixeloffset)).x);

    vec2 differences = abs( depths.yw - depths.xz );
    \textcolor{keywordtype}{float} gradient = min(gradientClamp, max(differences.x, differences.y));
    \textcolor{keywordtype}{float} gradientFactor = gradient * gradientScaleBias;

    \textcolor{comment}{// visibility function}
    \textcolor{keywordtype}{float} depthAdjust = gradientFactor + (fixedDepthBias * centerdepth);
    \textcolor{keywordtype}{float} finalCenterDepth = centerdepth + depthAdjust;

    \textcolor{comment}{// shadowUV.z contains lightspace position of current object}
\textcolor{preprocessor}{#if PCF}
    \textcolor{comment}{// use depths from prev, calculate diff}
    depths += depthAdjust;
    \textcolor{keywordtype}{float} \textcolor{keyword}{final} = (finalCenterDepth > shadowUV.z) ? 1.0 : 0.0;
    \textcolor{keyword}{final} += (depths.x > shadowUV.z) ? 1.0 : 0.0;
    \textcolor{keyword}{final} += (depths.y > shadowUV.z) ? 1.0 : 0.0;
    \textcolor{keyword}{final} += (depths.z > shadowUV.z) ? 1.0 : 0.0;
    \textcolor{keyword}{final} += (depths.w > shadowUV.z) ? 1.0 : 0.0;
    
    \textcolor{keyword}{final} *= 0.2;

    gl\_FragColor = vec4(outColor.xyz * \textcolor{keyword}{final}, 1);
    
\textcolor{preprocessor}{#else}
    gl\_FragColor = (centerdepth > shadowUV.z) ? vec4(outColor.xyz,1) : vec4(0,0,0,1);
\textcolor{preprocessor}{#endif}
\}

\end{DoxyCodeInclude}


This shader computes the two depth bias pieces described in section \hyperlink{_shadow_mapping_ogre_DepthBias}{Depth Biasing}. These are used to offset the stored depth value. This is where the notation differs from above, but the translation is quite straightforward.

Additionally this file implements percentage closest filtering. To use unfiltered shadow mapping, comment out the P\+CF block as noted and uncomment the Non-\/\+P\+CF block. Note that after doing this, the u\+S\+Tex\+Width and u\+S\+Tex\+Height variables are likely to be optimized away and so you should uncomment these variables in the materials script as well.

The following shows how to activate plane optimal shadow mapping given some pointer to a Movable\+Plane and a pointer to a light.


\begin{DoxyCode}
\hyperlink{class_ogre_1_1_plane_optimal_shadow_camera_setup}{Ogre::PlaneOptimalShadowCameraSetup} *planeOptShadowCamera = 
                                \textcolor{keyword}{new} PlaneOptimalShadowCameraSetup(movablePlane);
\hyperlink{class_ogre_1_1_entity}{Ogre::Entity} *movablePlaneEntity = sceneMgr->createEntity( \textcolor{stringliteral}{"movablePlane"}, \textcolor{stringliteral}{"plane.mesh"} );
\hyperlink{class_ogre_1_1_scene_node}{Ogre::SceneNode} *movablePlaneNode = 
                sceneMgr->getRootSceneNode()->\hyperlink{class_ogre_1_1_scene_node_aeaee9cb1cb0c23fab2cc9bab08f51181}{createChildSceneNode}(\textcolor{stringliteral}{"MovablePlaneNode"});
movablePlaneNode->\hyperlink{class_ogre_1_1_scene_node_a51052c58747a77a6cf7451b700e7eb87}{attachObject}(movablePlaneEntity);
light->setCustomShadowCameraSetup(\hyperlink{class_ogre_1_1_shared_ptr}{Ogre::ShadowCameraSetupPtr}(planeOptShadowCamera
      ));
\end{DoxyCode}
 \hypertarget{deferred}{}\section{Deferred Shading}\label{deferred}
This wiki article is complementary to the deferred shading demo that is part of the \hyperlink{namespace_ogre}{Ogre} S\+DK. It will reference the code quite a bit and explain some of the decisions made when implementing the deferred shading framework for the demo.\hypertarget{deferred_what}{}\subsection{What is Deferred Shading?}\label{deferred_what}
Deferred shading is an alternative approach to rendering 3d scenes. The classic rendering approach involves rendering each object and applying lighting passes to it. So, if an ogre head is affected by 6 lights, it will be rendered 6 times, once for each light, in order to accumulate the affection of each light. Deferred shading takes another approach \+: In the beginning, all of the objects render their \char`\"{}lighting related info\char`\"{} to a texture, often called the G-\/\+Buffer. This means their colours, normals, depths and any other info that might be relevant to calculating their final colour. Afterwards, the lights in the scene are rendered as geometry (sphere for point light, cone for spotlight and full screen quad for directional light), and they use the G-\/buffer to calculate the colour contribution of that light to that pixel.

See the links in \hyperlink{deferred_further}{Further reading} to read more about it. It is recommended to understand deferred shading before reading this article, as the article focuses on implementing it in ogre, and not explaining how it works.

\subsection*{Deferred Shading Advantages}

The main reason for using deferred shading is performance related. Classing rendering (also called forward rendering) can, in the worst case, require num\+\_\+objects $\ast$ num\+\_\+lights batches to render a scene. Deferred shading changes that to num\+\_\+objects + num\+\_\+lights, which can often be a lot less. Another reason is that some new post-\/processing effects are easily achievable using the G-\/\+Buffer as input. If you wanted to perform these effects without deferred shading, you would\textquotesingle{}ve had to render the whole scene again.

\subsection*{Deferred Shading Disadvantages}

There are several algorithmic drawbacks with deferred shading -\/ transparent objects are hard to handle, anti aliasing can not be used in D\+X9 class hardware, additional memory consumption because of the G-\/\+Buffer. In addition to that, deferred shading is harder to implement -\/ it overrides the entire fixed function pipeline. Pretty much everything is rendered using manual shaders -\/ which probably means a lot of shader code.\hypertarget{deferred_creating}{}\subsection{Creating the G-\/\+Buffer}\label{deferred_creating}
The first part of the deferred shading pipeline involves rendering all the (non-\/transparent) objects of the scene to the G-\/\+Buffer. This is done using a compositor \+:


\begin{DoxyCodeInclude}
compositor DeferredShading/GBuffer
\{
    technique
    \{
        \textcolor{comment}{// temporary textures}
        texture mrt\_output target\_width target\_height \hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caf91793bc9707d6541f4851722267317a}{PF\_FLOAT16\_RGBA} 
      \hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39caf91793bc9707d6541f4851722267317a}{PF\_FLOAT16\_RGBA} chain\_scope
        
        target mrt\_output
        \{
            input none
            pass clear
            \{
            \}
            
            shadows off
            material\_scheme GBuffer
            
            \textcolor{comment}{// everything but the lights and their meshes}
            \textcolor{comment}{// could do this with something like a visibility mask too}
            pass render\_scene
            \{
                \textcolor{comment}{//These values are synchronized with the code}
                first\_render\_queue 10
                last\_render\_queue  79   
            \}
        \}
    \}
\}
\end{DoxyCodeInclude}
 Things to note about this compositor \+:
\begin{DoxyItemize}
\item mrt\+\_\+output (the G\+Buffer) is an M\+RT because there are two pixel formats defined.
\item mrt\+\_\+output will be accessible to the next compositors in the chain because it is marked as chain\+\_\+scope, meaning it is visible to the next compositors in the chain.
\item The material scheme tells ogre that objects shouldn\textquotesingle{}t be rendered in normal fashion, but in some other way (we\textquotesingle{}ll get to that soon)
\item Not all the objects are rendered to the G\+Buffer. Skies and \textquotesingle{}late objects\textquotesingle{} (which can be specified manually using render queues) will be forward rendered.
\item This compositor does N\+OT have a target\+\_\+output pass, because it does not contribute directly to the final image.
\end{DoxyItemize}

\subsection*{Deciding on the G\+Buffer format}

This in an important decision in deferred shading, as it has performance and visual implications.

Also, the entire pipeline has to be coordinated with this format -\/ all the writing shaders have to write the same data to the same places, and all the reading shaders (for lighting later) have to be synchronized with it.

We chose two P\+F\+\_\+\+F\+L\+O\+A\+T16\+\_\+\+R\+G\+BA textures. The first one will contain the colour in R\+GB, specular intensity in A.

The second one will contain the view-\/space-\/normal in R\+GB (we keep all 3 coordinates) and the (linear) depth in A.

See the references for other possibilities.

\subsection*{Preparing the objects for G-\/\+Buffer rendering}

The only indicator that ogre has when rendering the scene is that the material scheme is different. Material schemes in ogre allow materials to specify different rendering techniques for different scenarios. In this case, we would like to output the lighting related information instead of the lighting calculation result.

Materials that have a technique associated with the G\+Buffer scheme will render using that, but we don\textquotesingle{}t want to modify the materials of all the objects in our art pipeline to use them in deferred shading.

The solution is to use scheme listeners! The material manager has a method for registering listeners when objects don\textquotesingle{}t have a technique defined for the current scheme\+: \hyperlink{class_ogre_1_1_material_manager_a8ac18f4bd2e6302f1d92ae8f64195694}{Ogre\+::\+Material\+Manager\+::add\+Listener()}.

The listener has a callback method that gets called whenever an object is about to be rendered without a matching technique\+: \hyperlink{class_ogre_1_1_material_manager_1_1_listener_a54bc384ab1102063aa00db4c3a5f3fc4}{Ogre\+::\+Material\+Manager\+::\+Listener\+::handle\+Scheme\+Not\+Found()}.

We will implement such a listener for the G\+Buffer scheme. It is G\+Buffer\+Scheme\+Handler from the demo. The G\+Buffer\+Scheme\+Handlers works like this \+:

\subsubsection*{Inspect the classic technique}

For each pass in the technique that would have been used normally, the G\+Buffer\+Scheme\+Handler\+::inspect\+Pass is called, inspects the pass, and returns the Pass\+Properties -\/ does this pass have a texture? a normal map? is it skinned? tranpsarent? Etc. The Pass\+Properties (should) contain all the information required to build a G\+Buffer technique for an object.

\subsubsection*{Generate the G-\/\+Buffer technique}

After a pass has been inspected and understood, the next stage is to generate the G-\/\+Buffer-\/writing technique. This is done using the class G\+Buffer\+Material\+Generator. The class receives the flags of the features needed by the material, and dynamically generates the (CG) shaders and material to render an object with those properties to the G-\/\+Buffer. This greatly reduces the number of shaders that you need to manage when using deferred shading, as most of them are created on the fly. Here is an example of what they look like \+:


\begin{DoxyCode}
\textcolor{keywordtype}{void} ToGBufferVP(
         float4 iPosition : POSITION,
         float3 iNormal   : NORMAL,
         float2 iUV0 : TEXCOORD0,

         out float4 oPosition : POSITION,
         out float3 oViewPos : TEXCOORD0,
         out float3 oNormal : TEXCOORD1,
         out float2 oUV0 : TEXCOORD2,

         uniform float4x4 cWorldViewProj,
         uniform float4x4 cWorldView
         )
 \{
         oPosition = mul(cWorldViewProj, iPosition);
         oNormal = mul(cWorldView, float4(iNormal,0)).xyz;
         oViewPos = mul(cWorldView, iPosition).xyz;
         oUV0 = iUV0;
 \}

 \textcolor{keywordtype}{void} ToGBufferFP(
         float3 iViewPos : TEXCOORD0,
         float3 iNormal   : TEXCOORD1,
         float3 iTangent : TEXCOORD2,
         float3 iBiNormal : TEXCOORD3,
         float2 iUV0 : TEXCOORD4,

         out float4 oColor0 : COLOR0,
         out float4 oColor1 : COLOR1,

         uniform sampler sNormalMap : \textcolor{keyword}{register}(s0),
         uniform sampler sTex0 : \textcolor{keyword}{register}(s1),
         uniform float4 cDiffuseColour,
         uniform \textcolor{keywordtype}{float} cFarDistance,
         uniform \textcolor{keywordtype}{float} cSpecularity
         )
 \{
         oColor0.rgb = tex2D(sTex0, iUV0);
         oColor0.rgb *= cDiffuseColour.rgb;
         oColor0.a = cSpecularity;
         float3 texNormal = (tex2D(sNormalMap, iUV0)-0.5)*2;
         float3x3 normalRotation = float3x3(iTangent, iBiNormal, iNormal);
         oColor1.rgb = normalize(mul(texNormal, normalRotation));
         oColor1.a = length(iViewPos) / cFarDistance;
 \}
\end{DoxyCode}
 (This is for an object with a texture and a normal map)

\subsubsection*{Add the G-\/\+Buffer technique to the original material}

We don\textquotesingle{}t want to inspect the passes and generate the material each time an object is rendered, so we create a technique in the original material, and fill it with the auto-\/generated information. After copying the information from the G\+Buffer technique, texture references have to be updated, to use the correct textures when rendering the object. This happens in {\ttfamily G\+Buffer\+Scheme\+Handler\+::fill\+Pass}. The next time the object will be rendered, it W\+I\+LL have a technique for the G\+Buffer scheme, so the listener won\textquotesingle{}t get called.

\subsubsection*{Postponing transparent objects}

We don\textquotesingle{}t want to render transparent objects to the G\+Buffer, as it doesn\textquotesingle{}t work properly later.

To address this, we also create a technique with a scheme called called \textquotesingle{}No\+G\+Buffer\textquotesingle{}. If the inspect\+Pass decided that the object is transparent, we will not add an auto-\/generated pass to the \textquotesingle{}G\+Buffer\textquotesingle{} technique, but instead copy the regular pass to the \textquotesingle{}No\+G\+Buffer\textquotesingle{} technique, to render it regularly later.

\subsubsection*{Putting it all together}

This is how {\ttfamily G\+Buffer\+Scheme\+Handler\+::handle\+Scheme\+Not\+Found} works\+:


\begin{DoxyCodeInclude}
Technique* GBufferSchemeHandler::handleSchemeNotFound(\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{short} schemeIndex, 
        \textcolor{keyword}{const} \hyperlink{namespace_ogre_af73bbdc8bed8a3e6fcd56bb8fa188c45}{String}& schemeName, Material* originalMaterial, \textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{short} lodIndex, 
        \textcolor{keyword}{const} Renderable* rend)
\{
    \hyperlink{class_ogre_1_1_material_manager}{Ogre::MaterialManager}& matMgr = 
      \hyperlink{class_ogre_1_1_material_manager_a100f413d9d2316028e7ae740e5a43161}{Ogre::MaterialManager::getSingleton}();
    \hyperlink{namespace_ogre_af73bbdc8bed8a3e6fcd56bb8fa188c45}{String} curSchemeName = matMgr.\hyperlink{class_ogre_1_1_material_manager_ad03ea02e140fc1e7312d14626e59d45d}{getActiveScheme}();
    matMgr.\hyperlink{class_ogre_1_1_material_manager_a95decc3900f547bb68b74ba28d3013e0}{setActiveScheme}(MaterialManager::DEFAULT\_SCHEME\_NAME);
    Technique* originalTechnique = originalMaterial->getBestTechnique(lodIndex, rend);
    matMgr.\hyperlink{class_ogre_1_1_material_manager_a95decc3900f547bb68b74ba28d3013e0}{setActiveScheme}(curSchemeName);

    Technique* gBufferTech = originalMaterial->createTechnique();
    gBufferTech->removeAllPasses();
    gBufferTech->setSchemeName(schemeName);

\textcolor{preprocessor}{#ifdef OGRE\_BUILD\_COMPONENT\_RTSHADERSYSTEM}
    RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton();
    rtShaderGen.createShaderBasedTechnique(*originalMaterial, originalTechnique->getSchemeName(), \textcolor{stringliteral}{"
      NoGBuffer"});
\textcolor{preprocessor}{#else}
    Technique* noGBufferTech = originalMaterial->createTechnique();
    noGBufferTech->removeAllPasses();
    noGBufferTech->setSchemeName(\textcolor{stringliteral}{"NoGBuffer"});
\textcolor{preprocessor}{#endif}

    \textcolor{keywordflow}{for} (\textcolor{keywordtype}{unsigned} \textcolor{keywordtype}{short} i=0; i<originalTechnique->getNumPasses(); i++)
    \{
        Pass* originalPass = originalTechnique->getPass(i);
        PassProperties props = inspectPass(originalPass, lodIndex, rend);
        
        \textcolor{keywordflow}{if} (!props.isDeferred)
        \{
\textcolor{preprocessor}{#ifdef OGRE\_BUILD\_COMPONENT\_RTSHADERSYSTEM}
            rtShaderGen.validateMaterial(\textcolor{stringliteral}{"NoGBuffer"}, originalMaterial->getName(), originalMaterial->
      getGroup());
\textcolor{preprocessor}{#else}
            \textcolor{comment}{//Just copy the technique so it gets rendered regularly}
            Pass* clonePass = noGBufferTech->createPass();
            *clonePass = *originalPass;
\textcolor{preprocessor}{#endif}
            \textcolor{keywordflow}{continue};
        \}

        Pass* newPass = gBufferTech->createPass();
        MaterialGenerator::Perm perm = getPermutation(props);

        \textcolor{keyword}{const} \hyperlink{class_ogre_1_1_shared_ptr}{Ogre::MaterialPtr}& templateMat = mMaterialGenerator.getMaterial(perm);
        
        \textcolor{comment}{//We assume that the GBuffer technique contains only one pass. But its true.}
        *newPass = *(templateMat->\hyperlink{class_ogre_1_1_material_a011abd64ab54e84c516068caa5001c91}{getTechnique}(0)->\hyperlink{class_ogre_1_1_technique_ab0014ffd501b4e1bef5eaae0340e71a7}{getPass}(0));
        fillPass(newPass, originalPass, props);    
    \}
    
    \textcolor{keywordflow}{return} gBufferTech;
\}
\end{DoxyCodeInclude}
 \subsection*{Overriding the automatic process}

In some cases the automatic material generation will not be good enough. We want to keep the option of manually writing G\+Buffer materials and shaders.

How do we do this? Easily! Since G\+Buffer\+Scheme\+Handler\+::handle\+Scheme\+Not\+Found only gets called when an object doesn\textquotesingle{}t already have a G\+Buffer scheme, adding a \textquotesingle{}G\+Buffer\textquotesingle{} technique to the material will cause it to not get passed to the listener even once.

\subsection*{Seeing it in action}

Using tools like N\+V\+I\+D\+IA\textquotesingle{}s Perf\+H\+UD, we can see the texture being built during the frame \+:



Note that nothing has been written to the final output yet (main view is completely black) and that two textures are being written to (see right hand side).\hypertarget{deferred_lighting}{}\subsection{Lighting the scene}\label{deferred_lighting}
In the G\+Buffer compositor, we built the G-\/\+Buffer for the current frame. It is now the time to use it to calculate the final lighting of the scene. This is what the compositor looks like \+:


\begin{DoxyCodeInclude}
compositor DeferredShading/ShowLit
\{

    technique
    \{
        \textcolor{comment}{//Reference the main Gbuffer texture}
        texture\_ref mrt\_output DeferredShading/GBuffer mrt\_output
        
        target\_output
        \{
            input none
            \textcolor{comment}{//We will dispatch the shadow texture rendering ourselves}
            shadows off
            
            pass clear
            \{
                
            \}
            
            \textcolor{comment}{// render skies and other pre-gbuffer objects}
            pass render\_scene
            \{
                first\_render\_queue 1
                last\_render\_queue  9            
            \}
            
            \textcolor{comment}{//Render the lights and their meshes}
            pass render\_custom DeferredLight
            \{
                input 0 mrt\_output 0
                input 1 mrt\_output 1
            \}
            
            \textcolor{comment}{//Render the objects that skipped rendering into the gbuffer}
            pass render\_scene
            \{
                material\_scheme NoGBuffer
                first\_render\_queue 10
                last\_render\_queue 79
            \}
            
            \textcolor{comment}{//Render the post-GBuffer render queue objects}
            pass render\_scene
            \{
                \textcolor{comment}{//This value is synchronized with the code}
                first\_render\_queue 80
            \}
        \}
    \}
\}
\end{DoxyCodeInclude}
 Yes, it\textquotesingle{}s a long one. Here is a breakdown of the compositor \+:
\begin{DoxyItemize}
\item The \textquotesingle{}texture\+\_\+ref\textquotesingle{} definition means that we are referencing a texture from another compositor. In the case of a chain-\/scoped texture (like the G\+Buffer), this means that we can only apply this compositor on chains that have the G\+Buffer creating compositor earlier in the chain than this one. \hyperlink{namespace_ogre}{Ogre} will check that this is the case.
\end{DoxyItemize}

There are four target passes in this compositor.
\begin{DoxyEnumerate}
\item Render the skies and then the lights using the render\+\_\+custom directive (more on this later)
\item Render the objects that are in the G\+Buffer render queues but didn\textquotesingle{}t get rendered to the G\+Buffer
\item Render the post-\/\+G\+Buffer render queue objects
\item Output the result
\end{DoxyEnumerate}

\subsubsection*{Why do we need four target passes ?}

This is mainly a limitation of \hyperlink{namespace_ogre}{Ogre}. Ideally, we could use a single target\+\_\+output pass and do all the passes there. The problem is that material\+\_\+scheme is at the target scope and not at the pass scope. This is hard to change, because material schemes are resolved during scene preparing time and not during scene rendering. So even if the scope would change, it would not affect the rendering, as the material scheme will not get tested after we switch to it. Perhaps this will be addressed, and then this compositor will get simplified.\hypertarget{deferred_lightgeom}{}\subsubsection{Rendering the light geometry}\label{deferred_lightgeom}
The geometry that we want to render to calculate lighting information doesn\textquotesingle{}t really fit in any classic category. It is not really a part of the scene, as the light geometry aren\textquotesingle{}t objects in the world. But it is geometry (not always a quad) that needs to be rendered.

For these kind of operations, the render\+\_\+custom target pass was introduced into \hyperlink{namespace_ogre}{Ogre}. It is possible to register custom (named) composition passes that will be performed in the compositor. In this case, it is \textquotesingle{}Deferred\+Light\textquotesingle{}. The composition pass will receive a call each frame telling it \textquotesingle{}it\textquotesingle{}s your turn, do your thing\textquotesingle{}. The class in the demo is Deferred\+Light\+CP.

The registration of the custom composition pass has to be done once, using \hyperlink{class_ogre_1_1_compositor_manager_ae9b8ca4c2a51c0720bb31393d20fe7c9}{Ogre\+::\+Compositor\+Manager\+::register\+Custom\+Composition\+Pass()}.

Custom\+Composition\+Pass is essentially just a factory for Render\+System\+Operations, which are the operations that get executed during a compositor chain. This is the single A\+PI call\+: \hyperlink{class_ogre_1_1_custom_composition_pass_a6b8c7a3743f9bb44e27c0348a0035e7b}{Ogre\+::\+Custom\+Composition\+Pass\+::create\+Operation()}.

So, now we get called exactly when we want, after the G-\/\+Buffer has been built and the (early) skies have been rendered. What will we do?

\subsubsection*{Prepare ambient colour and rebuild original depth buffer}

Since we rendered the original scene to a different R\+TT, the depth buffer won\textquotesingle{}t necessarily get reused for the output target, so we need to rebuild it so that future objects (lights and non-\/g-\/buffer objects) will be able to interact with the depth naturally.

Also, we need to apply the ambient light to the scene. For the purpose of the demo, the ambient light is not a separate colour channel, just the object\textquotesingle{}s original textures applied with the scene\textquotesingle{}s global ambient light factor. In theory, you could set up a different G-\/\+Buffer to allow more flexibility, but we didn\textquotesingle{}t do that.

These two actions happen in a single full-\/screen quad render, that comes from the Ambient\+Light class.

\subsubsection*{Render the light geometries}

The most important stage is the light geometry. The code scans the original scene\textquotesingle{}s lights, builds a matching D\+Light (deferred light) instance for each light in the scene, and renders away using the G-\/\+Buffer.

These lights use pretty sophisticated shaders, since they perform the lighting calculations of the fixed function pipeline themselves, and have to account for many options (specularity, attenuation, different light types and shadows, which will get talked about soon). In contrast to the G-\/\+Buffer building stage, the shaders here do not get generated on the fly. There is one big shader (sometimes referred to as an Uber-\/\+Shader) with many preprocessor options that account for all the options. (See Light\+Material\+\_\+ps.\+cg) Note that the shaders have to be synchronized with the G-\/\+Buffer layout. A change in the layout would need a parallel change in the deferred lighting shaders.

The material generator for this section (Light\+Material\+Generator class) just scans the flags of input and generates the correct preprocessor defines for the uber-\/shader. Some people prefer to use this approach for the G-\/\+Buffer stage as well, but I wanted to show both options in the demo.

In order to dispatch render operations manually, the following call exists in Scene\+Manager\+: \hyperlink{class_ogre_1_1_scene_manager_a1593fab748d1b0820e93e49d5732350b}{Ogre\+::\+Scene\+Manager\+::\+\_\+inject\+Render\+With\+Pass()}.

When rendering a light, we pass the light we are rendering as the manual light list in order to have the auto params for that light available in the shader.

\subsubsection*{Rendering shadow casting lights}

The \textquotesingle{}classic\textquotesingle{} approach to rendering texture shadows is to prepare all of them before the scene rendering starts, and then apply them to the rendered objects using shadow receiver passes or integrated shaders. The downside of this approach is that you need to allocate a texture per-\/light (5 shadow casting lights -\/$>$ 5 shadow textures) and that if you don\textquotesingle{}t integrate it in your shaders you also contribute even more passes to the scene.

One of the advantages of deferred shading is that we render the lights completely, and one by one. So, we can generate the shadow texture for a light just before the light\textquotesingle{}s geometry is rendered, allowing us to reuse the same texture for as many lights as we want. (We still have an overhead of rendering the scene from the light\textquotesingle{}s perspective per-\/light).

The A\+PI call that prepares shadow textures on demand is \hyperlink{class_ogre_1_1_scene_manager_a95cd8ff86a7178c2e37b2fcb485f64fa}{Ogre\+::\+Scene\+Manager\+::prepare\+Shadow\+Textures()}. The light\+List parameter allows specification of which lights to prepare shadow textures for.

Important note -\/ Render\+System\+Operations get executed in the middle of scene rendering. This means that there is an active render target being rendered to. In order to render the shadow texture we need to be able to pause rendering mid frame, render the shadow texture, and resume rendering immediately afterwards. For this, Scene\+Manager has two methods that do just that \hyperlink{class_ogre_1_1_scene_manager_a90d0e7484ed4580ec980eef15808bfee}{Ogre\+::\+Scene\+Manager\+::\+\_\+pause\+Rendering()} and \hyperlink{class_ogre_1_1_scene_manager_a794e03ea25dd798346414c1dba31337d}{Ogre\+::\+Scene\+Manager\+::\+\_\+resume\+Rendering()}, so the prepare\+Shadow\+Textures call has to be inside this.

The demo currently supports just spotlight shadow casting (since it is the cheapest to implement) but the other options can be supported as well.

\subsubsection*{Putting it all together}


\begin{DoxyCodeInclude}
\textcolor{keywordtype}{void} DeferredLightRenderOperation::execute(SceneManager *sm, RenderSystem *rs)
\{
    \hyperlink{class_ogre_1_1_camera}{Ogre::Camera}* cam = mViewport->getCamera();

    mAmbientLight->updateFromCamera(cam);
    Technique* tech = mAmbientLight->\hyperlink{class_ogre_1_1_frustum_a2a54dff8ade9ab6838c1517062f0eb98}{getMaterial}()->\hyperlink{class_ogre_1_1_material_a37ae7259ce89bdc38828ea1b977bdbcf}{getBestTechnique}();
    injectTechnique(sm, tech, mAmbientLight, 0);

    \textcolor{keyword}{const} \hyperlink{group___general_gaab30ef14aae93306a6044cb38d835f0c}{LightList}& lightList = sm->\_getLightsAffectingFrustum();
    \textcolor{keywordflow}{for} (LightList::const\_iterator it = lightList.begin(); it != lightList.end(); it++) 
    \{
        Light* light = *it;
        \hyperlink{class_ogre_1_1_hashed_vector}{Ogre::LightList} ll;
        ll.\hyperlink{class_ogre_1_1_hashed_vector_a87bfcde773502ee964a677580724188f}{push\_back}(light);

        \textcolor{comment}{//if (++i != 2) continue;}
        \textcolor{comment}{//if (light->getType() != Light::LT\_DIRECTIONAL) continue;}
        \textcolor{comment}{//if (light->getDiffuseColour() != ColourValue::Red) continue;}

        LightsMap::iterator dLightIt = mLights.find(light);
        DLight* dLight = 0;
        \textcolor{keywordflow}{if} (dLightIt == mLights.end()) 
        \{
            dLight = createDLight(light);
        \}
        \textcolor{keywordflow}{else} 
        \{
            dLight = dLightIt->second;
            dLight->updateFromParent();
        \}
        dLight->updateFromCamera(cam);
        tech = dLight->getMaterial()->getBestTechnique();

        \textcolor{comment}{//Update shadow texture}
        \textcolor{keywordflow}{if} (dLight->getCastChadows())
        \{
            SceneManager::RenderContext* context = sm->\_pauseRendering();

            sm->prepareShadowTextures(cam, mViewport, &ll);
            sm->\_resumeRendering(context);
            
            Pass* pass = tech->getPass(0);
            TextureUnitState* tus = pass->getTextureUnitState(\textcolor{stringliteral}{"ShadowMap"});
            assert(tus);
            \textcolor{keyword}{const} \hyperlink{namespace_ogre_aa381890787803da43b614dee8d9c8994}{TexturePtr}& shadowTex = sm->getShadowTexture(0);
            \textcolor{keywordflow}{if} (tus->\_getTexturePtr() != shadowTex)
            \{
                tus->\_setTexturePtr(shadowTex);
            \}
            
        \}
        
        injectTechnique(sm, tech, dLight, &ll);
    \}
\}
\end{DoxyCodeInclude}
 \subsubsection*{Seeing it in action}

Here is a screenshot from Perf\+H\+UD of the draw call that renders a spotlight that casts shadows. See the two G-\/\+Buffer textures and one shadow texture on the left \+:



Here is a visualization of the texture being built \+:



After all the lights are rendered, the scene is fully lit!\hypertarget{deferred_post}{}\subsection{Post Processing}\label{deferred_post}
The compositor framework used to be a post processing framework, but as this article shows -\/ it is now a \textquotesingle{}custom render pipeline\textquotesingle{} framework, allowing different rendering approaches. However, it can still be used to post process the scene, even under deferred rendering.

\subsection*{Screen Space Ambient Occlusion}

\textquotesingle{}Screen Space Ambient Occlusion\textquotesingle{} is a global illumination technique that adds a bit of realism to the scene, where classic lighting often fails. However, it requires the normals and depths of the scene in order to calculate its contribution. Normally, the S\+S\+AO compositor would have a render\+\_\+scene directive that does that.

However, with deferred shading, we already have that information from the G-\/\+Buffer stage, so we just need to access it!

This is what the compositor looks like \+:


\begin{DoxyCodeInclude}
compositor DeferredShading/SSAO
\{
    technique
    \{
        compositor\_logic SSAOLogic
        
        texture\_ref geom DeferredShading/GBuffer mrt\_output
        texture scene target\_width target\_height \hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39ca74ea3b1c0c5f4ae06b1a7136c5523eca}{PF\_R8G8B8A8}
        texture ssao target\_width\_scaled 0.5 target\_height\_scaled 0.5 \hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39ca32d32d3a5a8b68c1495d5c494575a6d8}{PF\_R8G8B8}
        texture ssaoBlurX target\_width target\_height \hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39ca32d32d3a5a8b68c1495d5c494575a6d8}{PF\_R8G8B8}
        texture ssaoBlurY target\_width target\_height \hyperlink{group___image_gga7e0353e7d36d4c2e8468641b7303d39ca32d32d3a5a8b68c1495d5c494575a6d8}{PF\_R8G8B8}

        \textcolor{comment}{// the scene we want to modulate}
        target scene
        \{
            input previous
        \}

        

        target ssao
        \{
            input none

            pass clear
            \{
            \}

            pass render\_quad
            \{
                \textcolor{comment}{// our SSAO listener number}
                identifier 42

                material ssao
                \textcolor{comment}{// pass in the "geometry map"}
                input 0 geom 1
            \}
        \}

        target ssaoBlurX
        \{
            input none

            pass clear
            \{
            \}

            pass render\_quad
            \{
                identifier 43

                material ssaoBlurX
                input 0 ssao
                input 1 geom 1
            \}
        \}

        target ssaoBlurY
        \{
            input none

            pass clear
            \{
            \}

            pass render\_quad
            \{
                identifier 43

                material ssaoBlurY
                input 0 ssaoBlurX
                input 1 geom 1
            \}
        \}



        target\_output
        \{
            input none

            pass render\_quad
            \{
                \textcolor{comment}{// just output something, for example, use a modulate}
                \textcolor{comment}{// material to just multiply the scene by the ssao}
                material modulate
                input 0 scene
                input 1 ssaoBlurY
                \textcolor{comment}{//input 1 ssao}
            \}
        \}
    \}
\}
\end{DoxyCodeInclude}


Some notes \+:
\begin{DoxyItemize}
\item Again, texture\+\_\+ref is used to access a chain\+\_\+scoped texture from the G\+Buffer compositor
\item compositor\+\_\+logic is used to couple between the compositor and some code that it requires to run. A Compositor\+Logic class is created and registered with the Compositor\+Manager with \hyperlink{class_ogre_1_1_compositor_manager_a9c7d4168d56868599badb2789d54157c}{Ogre\+::\+Compositor\+Manager\+::register\+Compositor\+Logic()}. Which will cause the binding code to run whenever an instance of this compositor is created.
\item \textquotesingle{}Regular\textquotesingle{} compositors that don\textquotesingle{}t use the G\+Buffer are also still possible of course, they can be used regularly, as long as they are placed after the Deferred\+Shading/\+Show\+Lit compositor.
\end{DoxyItemize}\hypertarget{deferred_realprojects}{}\subsection{Integration in real projects}\label{deferred_realprojects}
The framework that this demo uses was designed to be pluggable into other projects. Some of the design considerations that contribute to that are \+:
\begin{DoxyEnumerate}
\item The scene setup does not change in any way. You still set the scene up with normal lights and modify their parameters just like you would regularly.
\item The G\+Buffer scheme handler and shader generator allow existing materials to work in a deferred shading pipeline unmodified. It might not cover all the cases, but it can.
\item Easy to integrate -\/ see next section
\end{DoxyEnumerate}

\subsection*{Integration steps}

The framework created for a demo fits the plugin architecture pretty well. The G\+Buffer\+Scheme\+Handler and Deferred\+Light\+Composition\+Pass classes could be instantiated once on plugin setup and registered with ogre\textquotesingle{}s systems. This is not the case currently just to keep the S\+DK build simpler.

So, the steps are \+:
\begin{DoxyEnumerate}
\item Register G\+Buffer\+Scheme\+Handler and Deferred\+Light\+Composition\+Pass with their respective managers.
\item Add the G\+Buffer and Show\+Lit compositors to the viewports you want deferred shaded.
\end{DoxyEnumerate}

And thats it! In the demo, the Deferred\+Shading class takes care of that.

\subsection*{Adapting the framework}

The deferred shading framework in the demo was designed to be usable in real applications. Where would one want to modify it ?
\begin{DoxyEnumerate}
\item G\+Buffer\+Scheme\+Handler / Material\+Generator -\/ support more options out of the box. Skinning, specular maps, and whatever you have in your project that can be solved in a generic fashion.
\item Light\+Material\+Generator -\/ support more lighting options (fog, etc), more shadow types, different shadow techniques (currently using very basic depth shadow mapping)
\item Tweak the framework to your pipeline -\/ The material inspection relies on naming (among other things) to decide what its looking at. Just modify it to fit your art pipeline\textquotesingle{}s conventions! (For example, how does a texture get flagged as a normal map?)
\end{DoxyEnumerate}

Indeed, it means that the framework is not 100\% plug and play. But, if understood correctly, it can be adapted to real life scenarios with relative ease.

\subsection*{Adding features to the framework}

Post processing compositors that rely on certain aspects of the scene (like S\+S\+AO does) are now much easier to create and integrate with the earlier processes. An example could be edge-\/based anti aliasing, to address the lack of anti aliasing in D\+X9-\/based deferred shading systems.

In addition to that, the deferred shading implementation was focused on simplicity. There are many optimization options and most of them were not done, mainly to keep the demo as simple and understandable as possible.\hypertarget{deferred_summary}{}\subsection{Summary}\label{deferred_summary}
Deferred Shading is an advanced rendering technique, that brings a pretty big implementation challenge along with it. This article, along with the demo, shows that it is possible to implement without relying on hacks and bypassing ogre\textquotesingle{}s systems. Yes, it involves more advanced usage of ogre\textquotesingle{}s A\+P\+Is and requires a bit of knowledge about what happens behind the scenes, but is in no way impossible.\hypertarget{deferred_further}{}\subsubsection{Further reading}\label{deferred_further}

\begin{DoxyItemize}
\item \href{http://www.guerrilla-games.com/publications/dr_kz2_rsx_dev07.pdf}{\tt Kill\+Zone 2 Deferred Shading overview} -\/ Great resource for understanding deferred shading in general before diving into implemeting it in \hyperlink{namespace_ogre}{Ogre}.
\item \href{http://www.ogre3d.org/tikiwiki/tiki-index.php?page=SoC2009+Compositor}{\tt Improving Ogre\textquotesingle{}s Compositor Framework G\+SoC project page}
\item \href{http://www.gamedev.net/page/reference/index.html/_//feature/fprogramming/deferred-rendering-demystified-r2746}{\tt Deferred Rendering Demystified} -\/ An article written around this project that explains the design behind the deferred renderer. 
\end{DoxyItemize}\hypertarget{pczscenemanager}{}\section{Using the P\+CZ Scene Manager}\label{pczscenemanager}
The Portal-\/\+Connected-\/\+Zone Scene Manager (P\+C\+Z\+SM) is a plugin for Ogre3D (see www.\+ogre3d.\+org for more information about Ogre3d) which allows traversal of a scene which is non-\/homogeneous in structure. Specifically, the P\+C\+Z\+SM uses \char`\"{}\+Zones\char`\"{} which have their own hierarchy. Zones are connected to other zones by \char`\"{}\+Portals\char`\"{} which can be envisioned as 4-\/point convex planar polygons (or Spheres or A\+AB\textquotesingle{}s).

This document gives basic information on the usage of the P\+C\+Z\+Scene\+Manager. It is not complete, and will change \& expand as needed. Note that as of this writing, the P\+C\+Z\+SM has not undergone very extensive testing, nor is it optimized very much. Assistance in these two areas would be greatly appreciated. For support or to report bugs, please see the Developer Forum at Ogre3\+D.\+org

Cheers,

Eric \char`\"{}\+Chaster\char`\"{} Cha

\subsection*{U\+S\+I\+NG T\+HE P\+C\+Z\+\_\+\+S\+C\+E\+N\+E\+M\+A\+N\+A\+G\+ER}

N\+O\+TE\+: For an example of P\+C\+Z\+SM usage, see the P\+C\+Z\+Test\+App Application. It is probably a lot easier to understand than trying to figure it all out from this.

\subsection*{L\+O\+A\+D\+I\+NG \& I\+N\+I\+T\+I\+A\+L\+I\+Z\+A\+T\+I\+ON\+:}

The P\+C\+Z\+SM is loaded just like any other Scene Manager plugin. Included in the standard P\+C\+Z\+SM plugin is the \char`\"{}default\char`\"{} zone. If the user wishes to utilize the Octree\+Zone or Terrain\+Zone, the \char`\"{}\+Plugin\+\_\+\+Octree\+Zone\char`\"{} should be loaded {\itshape after} the P\+C\+Z\+SM plugin is loaded.

Before using the P\+C\+Z\+SM, the P\+C\+Z\+Scene\+Manager\+::init(zone\+Type) function should be called. During intialization, the user specifies what type of zone (Zone\+Type\+\_\+\+Default, Zone\+Type\+\_\+\+O\+Ctree, Zone\+Type\+\_\+\+Terrain) the P\+C\+Z\+SM should use for the default zone. The default zone is the zone where entities are placed if they are not specified to be in other zones.

\subsection*{C\+R\+E\+A\+T\+I\+NG Z\+O\+N\+ES\+:}

Once the P\+C\+Z\+SM has been initialized, the user can proceed with creating zones (P\+C\+Z\+Scene\+Manager\+::create\+Zone(zone\+Type, zone\+Name)). Zones can be anything from the outdoors (i.\+e. a Terrain) to a room in a building, or a tunnel in a dungeon. Zones can be of any size or shape, and can move.

N\+O\+TE\+: In the P\+C\+Z\+SM, sky rendering (domes, boxes, planes) is associated with a specific zone. For example, if the user has a building on a terrain, the sky could be associated with the terrain (i.\+e. the \char`\"{}outdoors\char`\"{}) using the function P\+C\+Z\+Scene\+Manager\+::set\+Sky\+Zone(zone). This tells the P\+C\+Z\+SM to only draw the sky when the designated zone is visible. (i.\+e. only draw the sky when the \textquotesingle{}outdoor\textquotesingle{} zone is visible). Usually, the Sky should be associated with the default zone (which is usually used as the \char`\"{}all
encompassing exterior zone\char`\"{}).

\subsection*{C\+R\+E\+A\+T\+I\+NG P\+O\+R\+T\+A\+LS\+:}

Once the user has created a zone (in addition to the default zone), they can create portals to attach two zones together.

$\ast$$\ast$$\ast$ N\+EW AS OF 9/25/07\+:

To create a portal, the user just calls P\+C\+Z\+Scene\+Manager\+::create\+Portal(). N\+O\+TE\+: The user should N\+OT just instantiate a portal manually (i.\+e. portal = new Portal) because the clean up of portals is handled by the scene manager directly. Instantiating portals using the C++ \textquotesingle{}new\textquotesingle{} command will result in memory leaks and errors if the scene is destroyed and recreated.

To destroy a portal use P\+C\+Z\+Scene\+Manager\+::destroy\+Portal(\+Portal $\ast$p) or P\+C\+Z\+Scene\+Manager\+::destroy\+Portal(\+String \& portal\+Name).

Then set the portal corner points, attaches it to a node, and then adds it to the zone (see P\+C\+Z\+Test\+App -\/$>$ Room\+Object.\+cpp -\/$>$ create\+Portals() function).

N\+O\+TE\+: Portals currently only connect different zones. The user can\textquotesingle{}t connect portals to the same zone yet (i.\+e. no teleporters). This functionality could be added later.

U\+P\+D\+A\+TE as of 3/17/09\+: Portals can be \char`\"{}closed\char`\"{} (and opened) by calling Portal\+::set\+Enable(false) (and Portal\+::set\+Enable(false)). Disabling a portal prevents the scene manager from traversing through the portal and also prevents scenenodes \& ray queries from crossing the portal. Basically, it turns a portal \char`\"{}off\char`\"{}. Disabling an antiportal (see note below about Creating antiportals) prevents the antiportal from blocking scene traversal through regular portals.

N\+EW IN V\+E\+R\+S\+I\+ON 1.\+2\+: Portals can take 3 different forms\+: quad portals, A\+AB portals, and Sphere portals. A\+AB and Sphere portals do not add any culling planes to the frustum, and just serve to serve as enclosures for zones which aren\textquotesingle{}t naturally surrounded by geometry. They function a little different than traditional quad portals in that they are volumetric, instead of planar (crossing is determined by going from \char`\"{}inside\char`\"{} to \char`\"{}outside\char`\"{} or vice versa).

Quad Portals require 4 corner points which are co-\/planar and form a polygon which is convex. Quad Portal corners are specified in right-\/handed counter-\/ clockwise winding order so that the norm of the portal would be facing the viewer.

A\+AB Portals require 2 corner points (minimum \& maximum corners) and form an axis-\/ aligned box around the zone. I\+M\+P\+O\+R\+T\+A\+NT\+: The A\+AB portals that are associated with a node require a node which has the correct size A\+AB (node-\/$>$\+\_\+get\+World\+A\+A\+B\+B()).

Sphere Portals require 2 corner points (center point, and point on the surface of the sphere).

The \char`\"{}direction\char`\"{} norm of A\+AB and Sphere portals is specified as either Vector3\+::\+U\+N\+I\+T\+\_\+\+N\+E\+G\+A\+T\+I\+V\+E\+\_\+Z or Vector3\+::\+U\+N\+I\+T\+\_\+Z. The first corresponds to a portal with norm facing \textquotesingle{}inward\textquotesingle{} and the latter corresponds to a portal with norm facing \textquotesingle{}outward\textquotesingle{}.

N\+O\+TE regarding Portal Norms\+: The Norm of a portal should always point away from the zone the portal leads to. Another way to think of this is a node will only cross a portal if it crosses the portal traveling opposite direction of the norm).

Portals also (currently) require a \char`\"{}matching\char`\"{} portal for proper scene traversal. In other words, portals always exist in pairs -\/ one in each zone connected and co-\/existing in the same location, but facing in opposite directions.

It is R\+E\+Q\+U\+I\+R\+ED that a portal be associated with a scene node. Use Portal\+::set\+Node() to associate the portal with a scene node. Once the portal is associated with a scene node, it will move with the scene node (including rotations or translations). Because of this, it is also highly recommended (although not required) that the node a portal is associated with be located at the center of the portal.

N\+O\+TE\+: Scaling of a portal is not yet {\itshape tested}. Scaling a node should scale the portal (but don\textquotesingle{}t cry to me if it doesn\textquotesingle{}t work right yet...)

Once all portals in the scene have been created, the user can either manually assign their zone targets (i.\+e. the zone which they connect to) or they can call P\+C\+Z\+Scene\+Manager\+::connect\+Portals\+To\+Target\+Zones\+By\+Location() to do it automatically. Note that this function requires all portals to have a matching portal in the target zone.

\subsection*{A\+N\+T\+I\+P\+O\+R\+T\+A\+LS $\ast$$\ast$ N\+EW As of 3/17/09 $\ast$$\ast$}

Antiportals are a new feature (thanks to Lf3thn4d). Antiportals prevent traversal of portals located behind them (as viewed from the camera). They are created and manipulated the same as regular portals (except you don\textquotesingle{}t need to create them in pairs, since they block scene traversal to other zones instead of connecting them). Only Quad Antiportals are supported.

To Create an antiportal, it\textquotesingle{}s very similar to regular portals. All you need to do is call P\+C\+Z\+Scene\+Manager\+::create\+Anti\+Portal(\char`\"{}name of the antiportal\char`\"{}), set the corner values, attach it to a node, and add it to the proper zone.

\subsection*{C\+R\+E\+A\+T\+I\+NG O\+B\+J\+E\+C\+T\+S/\+E\+N\+T\+I\+T\+I\+ES\+:}

Once the zones and portals have been created, the user can create objects/entities. The user should use Scene\+Manager\+::create\+Scene\+Node() to create all scene nodes.

N\+O\+TE\+: A\+LL O\+B\+J\+E\+C\+TS {\itshape M\+U\+ST} BE A\+T\+T\+A\+C\+H\+ED TO S\+C\+E\+N\+E\+N\+O\+D\+E\+S!!! Unlike the other SM\textquotesingle{}s available in Ogre3d, the P\+C\+Z\+SM relies on Scene Nodes to determine zone locality of all entities -\/ including cameras and lights. Consequently, when a camera (or light) is created, the user should also attach the camera (or light) to a scene node and use that node to manipulate the object.

Scene\+Nodes can be assigned (by the user) to a zone upon creation of the Scene\+Node. Use the functions \char`\"{}\+P\+C\+Z\+Scene\+Node\+::set\+Home\+Zone(\+P\+C\+Zone $\ast$ zone)\char`\"{} followed by \char`\"{}\+P\+C\+Zone\+::\+\_\+add\+Node(\+P\+C\+Z\+Scene\+Node $\ast$ node)\char`\"{} to do this.

If the user doesn\textquotesingle{}t do this, the P\+C\+Z\+SM will try to figure out which zone the node belongs in using volumetric testing, but since there are situations when this can fail, it is highly recommended that the user does so explicitly instead of relying on the SM to figure it out. Note that this only has to be done when adding a node to the scene. Once the node is in the proper zone, the SM will handle moving it to other zones as necessary.

N\+O\+TE\+: In order for the automatic zone assignment function to work, zones must have an \char`\"{}enclosure\char`\"{} object/node assigned to them (using the "P\+C\+Zone\+::set\+Enclosure\+Node() function). The enclosure node (or more specifically, the object attached to it) supplies the axis-\/aligned bounding box that determines the bounds of the zone. So for example, the enclosure node/object for a room would be the model of the walls, ceiling, and floor (assuming they are all modeled as one object or at least all attached to the same node). See the P\+C\+Z\+Test\+App for an example.

\subsection*{S\+C\+E\+NE Q\+U\+E\+R\+I\+ES\+:}

I have implemented Scene Query functions for Default \& Octree Zones. In general, they are used the same way as Scene Queries for any other Scene Manager, with one difference. The user must specify the \char`\"{}start zone\char`\"{} for any scene query using X\+X\+X\+Scene\+Query\+::set\+Start\+Zone(zone) where \char`\"{}\+X\+X\+X\char`\"{} is Ray, Sphere, Axis\+Aligned\+Box, etc.

\subsection*{K\+N\+O\+WN B\+U\+GS\+:}


\begin{DoxyItemize}
\item Light traversal is not quite correct. In order to avoid infinite recursion, I had to put in a hack which can potentially result in lighting not traversing into some zones properly. It will probably not be noticeable in most situations, but could potentially show up in very complex portal/zone setups. 
\end{DoxyItemize}