Skip to content
This repository has been archived by the owner on Jun 12, 2019. It is now read-only.

RenderTextures

pdinklag edited this page Dec 31, 2012 · 2 revisions

Until now, RenderWindows are the only type of RenderTarget we rendered to. This chapter will go into off-screen rendering into a texture, which can then be used for post-processing (e.g. using shaders, which will be presented at a later point).

Off-screen rendering

The RenderTexture represents these off-screen rendering targets. They are generally used like windows. The difference is, however, that whatever is rendered to it will not be displayed on the screen when [display](http://jsfml.org/javadoc/org/jsfml/graphics/RenderTexture.html#display(\)) is called, but drawn to a texture. You can then retrieve that texture using the [getTexture](http://jsfml.org/javadoc/org/jsfml/graphics/RenderTexture.html#getTexture(\)) method and use it for a Sprite, for instance.

This is useful for post-effects on the whole scene, or to improve performance by pre-rendering more complex objects that only change rarely.

Before a RenderTexture can be used, much like a window, it has to be created first using the [create](http://jsfml.org/javadoc/org/jsfml/graphics/RenderTexture.html#create(int, int)) method. It can be of any size [that is allowed by the hardware](http://jsfml.org/javadoc/org/jsfml/graphics/Texture.html#getMaximumSize(\)).

Note that this method may throw a TextureCreationException if the render texture could not be created. That might happen if the hardware does not support textures of the given size, or if it does not support render textures in general. This case should be properly handled by your application, since there is still a lot of hardware around that does not support this.

##The Code The following code is an example that creates a RenderTexture and uses it as the main render target for the scene. The texture is used by a sprite to realize some basic post-effects.

// ... (create window and other objects)

//Create the render texture, which will be the same size as the window
RenderTexture renderTex = new RenderTexture();
try {
    renderTex.create(window.getSize().x, window.getSize().y);
} catch(TextureCreationException ex) {
    System.err.println("The render texture could not be created, you will probably see a black screen...");
    ex.printStackTrace();
}

//Create a post-effect sprite that will mirror the whole screen
Sprite postEffect = new Sprite(renderTex.getTexture());
postEffect.setScale(-1, 1);

//Main loop
while(window.isOpen()) {
    //Draw the scene to the render texture instead of the window
    renderTex.clear();
    renderTex.draw(/* ... the scene ... */);
    renderTex.display();

    //Draw the post effect sprite to the window
    window.clear();
    window.draw(postEffect);
    window.display();

    // ... (handle input events)
}
Clone this wiki locally