%tutorialhelp%

Introduction

This tutorial covers the basics of rendering a scene to a texture. This technique is used for a variety of effects. It is particularly useful in combination with shaders. Motion blur effects can be created in this way.

The basic idea is rather simple. Instead of just sending render information strictly to our render window, we will also send the information to be rendered directly to a texture in our scene. This texture will then be used like a texture loaded from the hard drive.

The full source for this tutorial is here.

Note: There is also source available for the BaseApplication framework and Ogre 1.7 here.

rtt_visual1.png

Prerequisites

This tutorial assumes that you already know how to set up an Ogre project and compile it successfully. Knowledge of the topics from previous tutorials is also assumed.

The base code for this tutorial is here.

Setting Up the Scene

First, as usual, we are going to set up a basic scene. Add the following variables to your project.

BasicApp.h
Ogre::MovablePlane* mPlane;
Ogre::Entity* mPlaneEntity;
Ogre::SceneNode* mPlaneNode;
Ogre::Rectangle2D* mMiniScreen;

Remember to initalize them all in the constructor.

BasicApp.cpp
mPlane(0),
mPlaneEntity(0),
mPlaneNode(0),
mMiniScreen(0)

Finally, we'll set up the basic scene elements we need. Add the following to createScene:

mSceneMgr->setAmbientLight(Ogre::ColourValue(0.2, 0.2, 0.2));

Ogre::Light* light = mSceneMgr->createLight("MainLight");
light->setPosition(20, 80, 50);

mCamera->setPosition(60, 200, 70);
mCamera->lookAt(0,0,0);

Ogre::MaterialPtr mat =
  Ogre::MaterialManager::getSingleton().create(
    "PlaneMat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

Ogre::TextureUnitState* tuisTexture =
  mat->getTechnique(0)->getPass(0)->createTextureUnitState("grass_1024.jpg");

mPlane = new Ogre::MovablePlane("Plane");
mPlane->d = 0;
mPlane->normal = Ogre::Vector3::UNIT_Y;

Ogre::MeshManager::getSingleton().createPlane(
  "PlaneMesh",
  Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
  *mPlane,
  120, 120, 1, 1,
  true,
  1, 1, 1,
  Ogre::Vector3::UNIT_Z);
mPlaneEntity = mSceneMgr->createEntity("PlaneMesh");
mPlaneEntity->setMaterialName("PlaneMat");

mPlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
mPlaneNode->attachObject(mPlaneEntity);


You might need to include these

BasicApp.h
#include <OgreMaterialManager.h>
#include <OgreTechnique.h>
#include <OgreMovablePlane.h>
#include <OgreMeshManager.h>


If any of this is confusing, refer to previous tutorials. Compile and run your application. You should see a rotating grass-textured plane.

rtt_visual2.png

Creating a Texture

The first step is to create a texture we can render to. Add the folowing to createScene:

Ogre::TexturePtr rttTexture =
  Ogre::TextureManager::getSingleton().createManual(
    "RttTex", 
    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
    Ogre::TEX_TYPE_2D, 
    mWindow->getWidth(), mWindow->getHeight(), 
    0, 
    Ogre::PF_R8G8B8, 
    Ogre::TU_RENDERTARGET);

The first parameter of this function is the name to give the texture ("RttTex" is somewhat standard). The second specifies the default resource group. The third specifies the type of the texture to be 2D. The fourth and fifth specify the width and height of the texture. The sixth parameter is the number of mipmaps to be used. The seventh is a texture format, and the last is a usage flag.

There are many different texture formats, but the simplest one is PF_R8G8B8. This produces a 24-bit RGB texture. If you need an alpha channel, then PFR8G8B8A8 will work fine.

Next we need to get a pointer to the render target of this texture in order to set some parameters. It will also be used later to add a RenderTargetListener.

Ogre::RenderTarget* renderTexture = rttTexture->getBuffer()->getRenderTarget();
 
renderTexture->addViewport(mCamera);
renderTexture->getViewport(0)->setClearEveryFrame(true);
renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
renderTexture->getViewport(0)->setOverlaysEnabled(false);


You might need to include these headers:
{CODE(wrap="1", colors="c++", caption="BasicApp.h)}

  1. include <OgreRenderTexture.h>
  2. include <OgreHardwarePixelBuffer.h>{CODE}


After retrieving the render texture, we add the camera's viewport to it. This is the viewport that will be rendered to our texture. We also tell the viewport to clear itself every frame. If we didn't do this, then we would get the infinite trails effect. Try it, it's fun. We also set the background color to black, and we disable overlays so that they won't be rendered on top of our texture if we were to use them.

Writing Our Texture to a File

We are now going to save our texture to a file. The RenderTexture class is derived from RenderTarget, so they already have a function to store their content to a file. Before saving the texture, be sure to update it once.

renderTexture->update();
renderTexture->writeContentsToFile("start.png");

If you compile and run the application now, you will find 'start.png' in the directory that includes your executable. It should show the content of your screen.

Note there is also a function called setAutoUpdated which will automatically update the RenderTexture if Ogre's rendering loop or Root::_updateAllRenderTargets is being used. Keep in mind that it does not update the RenderTexture immediately when it is called.

Implementing the Miniscreen

Now we will add a miniscreen to the upper right corner of our application window. To do this, we'll use a Rectangle2D with our RenderTexture applied to it. Our scene will be shown twice. It will be rendered to our RenderWindow normally and rendered a second time on to our miniscreen.

You can use this method to create security camera monitors or computer screens with rendered graphics on them. Of course you don't need to simply replicate the camera's viewpoint. You can attach a different viewport to the RenderTexture, allowing you to do things like remote controlled robots with their own camera that feeds back to a miniscreen.

First, we'll set up the Rectangle2D.

mMiniScreen = new Ogre::Rectangle2D(true);
mMiniScreen->setCorners(.5, 1.0, 1.0, .5);
mMiniScreen->setBoundingBox(Ogre::AxisAlignedBox::BOX_INFINITE);

The first line tells the Rectangle2D to generate texture coordinates. These are what we'll use to apply our texture. In the second line we set the coordinates for our miniscreen. These are coordinates that run from the top-left (-1.0, 1.0) to the bottom-right (1.0, -1.0). This places our rectangle in the upper right corner of the screen with a width and height that are equal to 1/4 of the screen's dimensions. You'll just have to get used to the fact that a number of different coordinate systems are used in graphics programming. It's not a total loss because understanding simple coordinate transformations like this may help you understand the more complicated transformations you'll see in other areas.

Now that we have the rectangle, we need to attach it to a SceneNode as usual.

Ogre::SceneNode* miniScreenNode =
  mSceneMgr->getRootSceneNode()->createChildSceneNode();

miniScreenNode->attachObject(mMiniScreen);


You might need to add this:

BasicApp.h
#include <OgreRectangle2D.h>


If you compile and run the application now, you'll see a white rectangle where our texture will soon be.

rtt_visual3.png

Creating a Material From Scratch

The next step is to apply our RenderTexture to the Rectangle2D we've just created. We have to create a material for it. This could be done in a material script or directly in code during runtime. We will use the second method to keep everything to one file for the tutorial.

Ogre::MaterialPtr renderMaterial = 
  Ogre::MaterialManager::getSingleton().create(
    "RttMat", 
    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

renderMaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
renderMaterial->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex");

The first part creates an empty material called RttMat. Then we disable the lighting to prevent our miniscreen from being darker than the actual texture (if we didn't, the lighting would essentially be applied twice to our miniscreen rendering). The last line creates a new TextureUnitState using the RttTex we created earlier.

Now we simply set this material to be used by our miniscreen.

mMiniScreen->setMaterial("RttMat");

If you compile and run the application now, you'll see that something is wrong. The miniscreen...has a miniscreen. To solve this we'll make use of a RenderTargetListener.

Using a RenderTargetListener

There may be cases where you only want certain objects from your scene to be used by your RenderTexture. In our case, we don't want our miniscreen to be rendered again in our miniscreen. What we have to do is hide our miniscreen right before the window output is stored to our RenderTexture. This is what we can use the RenderTargetListener for.

The listener has two important functions for our problem: preRenderTargetUpdate and postRenderTargetUpdate. The names practically tell you exactly what they do. The first function is called automatically by the listener before the RenderTexture is filled, and the second function is called after the RenderTexture has been filled.

To implement a RenderTargetListener we will simply have our application inherit from RenderTargetListener. This class can be included with OgreRenderTargetListener.h. Add the following to your project:

BasicApp.h
#include <OgreRenderTargetListener.h>

class BasicApp
  : public Ogre::WindowEventListener,
    public Ogre::FrameListener,
    public Ogre::RenderTargetListener,
    public OIS::KeyListener,
    public OIS::MouseListener
{
  ...

  //////////////////////
  // Tutorial Section //
  //////////////////////
  virtual void preRenderTargetUpdate(const Ogre::RenderTargetEvent& rte);
  virtual void postRenderTargetUpdate(const Ogre::RenderTargetEvent& rte);

  ...

};

Then we will add these methods and toggle the visibility off right before updating the RenderTexture and then right back on afterwards.

BasicApp.cpp
void BasicApp::preRenderTargetUpdate(const Ogre::RenderTargetEvent& rte)
{
  mMiniScreen->setVisible(false);
}

void BasicApp::postRenderTargetUpdate(const Ogre::RenderTargetEvent& rte)
{
  mMiniScreen->setVisible(true);
}

All that is left is to add the listener to our RenderTexture so the methods are actually called automatically. Remember, our application has inherited from RenderTargetListener so it can be passed directly as the listener. Add the following to createScene, right after we set the miniscreen material:

renderTexture->addListener(this);

Compile and run your application. You should have a working RTT texture mapped to your miniscreen.

rtt_visual4.png

Render to Texture and Shaders

This process is often used together with shaders to create a vast array of effects. So it will be useful to know how to pass a RenderTexture to a shader.

The simplest case is where the texture never changes for the shader during runtime. You just have to tell your material script the name of the texture you create during runtime, in our case "RttTex". So in your material script, the texture_unit would look like this:

texture_unit
{
    texture RttTex
}

If you need to change the shader's texture during runtime, then you would use the following two lines:

Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("Sepia");
material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(
  "OtherRttTex");

The first line gets a pointer to the material. The second line sets the desired texture name.

After setting the correct texture name, you can access the texture in your Cg shader with the following line:

uniform sampler2D SceneSampler : register(s0)

That's all there is to it. Download the files and try it out with your application.

 Plugin disabled
Plugin attach cannot be executed.


rtt_visual1.png

Conclusion

In this tutorial, we learned how to set up a RenderTexture that we can use to display the contents of a viewport. This involved creating a texture from scratch, then building a material from that texture, and finally applying that texture to a Rectangle2D object. We also introduced the RenderTargetListener. This allowed us to customize what would be rendered from our chosen viewport. The listener provides callback methods that allow us to manipulate the scene before and after the RenderTexture is applied to our miniscreen. Finally, we covered passing our RenderTexture through a Cg shader.

For further information on Cg shaders see Getting Started With Ogre CG Materials.

Exercises

Easy

  1. Add more objects to your scene and then hide some of them from the RenderTexture using the listener.

Intermediate

  1. Add a second miniscreen that displays the same scene from a different angle.

Difficult

  1. Set up and display a viewport in your miniscreen other than your main camera.

Advanced

  1. Model a security camera monitor by setting up a viewport with an aerial view of the scene, and then rendering it to on the front of a cube sitting on a table. Remember you can manually create these meshes if you don't already know how to build an ogre mesh in a program like Blender.

Full Source

The full source for this tutorial is here.

Next

This is the end of the Intermediate Tutorial series. You can start browsing Snippets for more information about Ogre's features.


Alias: Intermediate_Tutorial_7

<HR>
Creative Commons Copyright -- Some rights reserved.


THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  • "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
  • "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
  • "Licensor" means the individual or entity that offers the Work under the terms of this License.
  • "Original Author" means the individual or entity who created the Work.
  • "Work" means the copyrightable work of authorship offered under the terms of this License.
  • "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  • "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.

2. Fair Use Rights

Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant

Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  • to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
  • to create and reproduce Derivative Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
  • to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
  • For the avoidance of doubt, where the work is a musical composition:
    • Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
    • Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
    • Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).


The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.

4. Restrictions

The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  • You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
  • You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
  • If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability.

EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination

  • This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  • Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  • Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  • Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  • If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  • No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
  • This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.