Simple2D can be used to draw simple 2D stuff onto a graphics device. We initialize it on the stack between SimpleSetup::Start and the mainloop:

Simple2D painter(setup.GetGraphicsDevice());

Next up, we need to load a texture to use for painting. Find a JPG, PNG or TGA image i.e. on google and save it in a folder named “data” in the same directory as your project. Then, enter this line to load the texture:

RTexture2D image("data/something.jpg");

What this is all about will be explained in detail in the next part of this tutorial. For now, we’ll just say that this loads the texture “something.jpg” from the data folder into the object “image”.

Now it’s time to draw the image onto the screen. This is done inside the main loop using Simple2D::DrawQuad(). Remove the keyboard-fuzz from the last part of the tutorial and replace it with:

setup.GetGraphicsDevice()->Clear(Graphics::ClearBuffersAll, 0, 0, 0, 0, 1, 0);
painter.DrawQuad(setup.GetState(), Math::Vector2i(100, 100), image);

And there you go :) an image on the screen!

Blending
If you want the 2D sprite (the image) to blend against the background (i.e. use transparency), you need to enable blending. This is done using the State object inside SimpleSetup. During initialization, we set up a BlendStateDescriptor which describes the blending mode we want to use. If you use a PNG with transparency, you would want to use the blend mode presented here:

// Initialize blend mode used to draw the sprite
Graphics::BlendStateDescriptor blend;
blend.BlendEnabled = true;
blend.BlendSrcRGB = Graphics::BlendOperandSrcAlpha;
blend.BlendDstRGB = Graphics::BlendOperandOneMinusSrcAlpha;

To use this blend mode, Push() it onto the Blend stack before calling DrawQuad(). Remember to Pop() it afterward to restore the default blend settings.

setup.GetState()->Blend.Push(blend);
painter.DrawQuad(setup.GetState(), Math::Vector2i(100, 100), image);
setup.GetState()->Blend.Pop();

Challenges

  • Try letting the user move the image arround using the arrow keys.

Source code
Complete source code for this tutorial can be found at http://svn2.assembla.com/svn/fwg/trunk/tutorials/simple/part3/




FireStats icon Powered by FireStats