Creating a Direct2D game for WinRT

Posted by Filip Ekberg on October 1 2012 7 Comments

If you want to write a game for Windows 8 and was thinking of using XNA, think again. When creating games for Windows 8 you’ll have to go back to using DirectX. But don’t worry, with Visual Studio 2012 on Windows 8, you’ll get a lot of help doing so. Let’s have a look on how to create a Direct2D game for WinRT!

The first thing we would have to do is to fire up Visual Studio and create a new Direct2D project. Can’t find it in the C# section for Windows Store applications? That’s because we’ll have to use C++ for this! You’ll find the project template in Other Languages -> Visual C++ -> Windows Store -> Direct2D App (XAML):

When the project is created, we will have a lot of sample files in our solution. As you can see, there are also XAML files in the project! We’ve got the App.xaml that will tell us which the default view is, which in this case will be DirectXPage.xaml. Let’s run it in a simulated mode and see what this default code gives us. With Visual Studio 2012 we get a very handy simulator, to run the application inside it, simply change the target from Local Machine to Simulator:

This will bring up the simulator and the application that we got by default will let us drag around the title and if we right click the surface, we get an app bar that will allow us to change the background:

Here’s a small video on YouTube showing what this looks like when it’s running:

What’s interesting about this demo is that it combines XAML, C++ and Direct2D. The text in the center that says “Hello, XAML!” is actually just a normal XAML TextBox:

<TextBlock x:Name="SimpleTextBlock" HorizontalAlignment="Center" FontSize="42" Height="72" Text="Hello, XAML!" Margin="0,0,0,50"/>

The TextBox lives inside a content panel called SwapChainBackgroundPanel and this is something new. According to MSDN, this panel will only be used when we interop with DirectX:

Implements a XAML layout surface target for Microsoft DirectX interoperation scenarios. This panel has some atypical restrictions on its usage within an app window; see Remarks.

MSDN also says that this only applies to Windows Store applications.

We’re getting a lot of DirectX code free here which we don’t have to write ourselves. What we do want to take a look at though is the SimpleTextRenderer. This class handles drawing the text “Hello, DirectX!” on the screen. It inherits from the DirectXBase class which will do all the DirectX magic.

Have a look in the method SimpleTextRenderer::Render(), if we were to add a rectangle instead of the text, like this:

auto rect = D2D1_RECT_F();
rect.bottom = 100.0f;
rect.top = 0.0f;
rect.left = 0.0f;
rect.right = 100.0f;

m_d2dContext->DrawRectangle(rect, m_blackBrush.Get());

We could run the application and it would look like this:

Now, try to move the rectangle around, notice that it moves around just like the text we had before did? That’s magical! Actually, it’s just a transformation going on; the Direct2D context is transformed and the area is moved to wherever the mouse was. These are the lines in that method which changes the transformation:

Matrix3x2F translation = Matrix3x2F::Translation(
    m_windowBounds.Width / 2.0f - m_textMetrics.widthIncludingTrailingWhitespace / 2.0f + m_textPosition.X,
    m_windowBounds.Height / 2.0f - m_textMetrics.height / 2.0f + m_textPosition.Y
    );
m_d2dContext->SetTransform(translation * m_orientationTransform2D);

If we simply comment these out, we’ll see a completely different result. You should now see the rectangle at the top of the screen being 100 pixels wide and 100 pixels high:

Now to make this a bit more interesting, let’s make the box move around a little bit. In order for it not to rely on the point & move event, we need to go back to the DirectXPage and remove something from the event handler DirectXPage::OnRendering. As it is now, it checks if it needs to be rendered by falling back on a boolean variable, but this bool is only set to true when we’ve moved the mouse (or finger) around. That means that the event handler should look like this instead:

void DirectXPage::OnRendering(Object^ sender, Object^ args)
{
    m_timer->Update();
    m_renderer->Update(m_timer->Total, m_timer->Delta);
    m_renderer->Render();
    m_renderer->Present();
    m_renderNeeded = false;
}

In order for the box to actually move around, we need to change a couple of things in SimpleTextRenderer::Render as well as in SimpleTextRenderer::Update. First we need to introduce a couple of global variables, I’ve called them x and y. These two variables will be in charge of telling us where the rectangle should be drawn on the screen. This means that SimpleTextRenderer::Render can look like this:

float x = 0.0f;
float y = 0.0f;
void SimpleTextRenderer::Render()
{
    m_d2dContext->BeginDraw();

    m_d2dContext->Clear(ColorF(BackgroundColors[m_backgroundColorIndex]));

    auto rect = D2D1_RECT_F();
    rect.top = y;
    rect.left = x;
   
    rect.bottom = rect.top + 100.0f;
    rect.right = rect.left + 100.0f;

    m_d2dContext->DrawRectangle(rect, m_blackBrush.Get());

    HRESULT hr = m_d2dContext->EndDraw();
    if (hr != D2DERR_RECREATE_TARGET)
    {
        DX::ThrowIfFailed(hr);
    }

    m_renderNeeded = false;
}

There’s a second pair of global variables that I want to add at this point, these will tell us in which direction the rectangle should be moving. As you might have figured out, I want to make the rectangle bounce around the window!

float x_direction = 1.0f;
float y_direction = 1.0f;

Last but not least, I want to make some changes to SimpleTextRenderer::Update, since this is where we get information about the delta time, the time since the last frame was updated. Basically I want to increase both x and y with timeDelta * 200 and then multiply that with the current direction of which we’re moving the rectangle.

When bouncing something around, we need to know the bounds of the window so that the rectangle does not exit outside the window. Luckily for us, the class that we’re inheriting from has a member variable called m_windowBounds which is a rectangle that tells us the current window bounds.

We can use this rectangle to check if we’re outside of the bounds and then we also need to check that we don’t reach below 0 in either x or y direction. This leaves us with a method looking like this:

float x_direction = 1.0f;
float y_direction = 1.0f;
void SimpleTextRenderer::Update(float timeTotal, float timeDelta)
{
    x += (timeDelta * 200) * x_direction;
    y += (timeDelta * 200) * y_direction;

    if(x > m_windowBounds.Width - 100.0f || x <= 0) {
        y_direction *= 1.0f;
        x_direction *= -1.0f;
    }
    if(y > m_windowBounds.Height - 100.0f || y <= 0) {
        y_direction *= -1.0f;
        x_direction *= 1.0f;
    }
}

Side note: The global variables need to be defined before they’re used, add the floats to the top of the file

Here’s a video of what this looks like when the application is running inside the Windows 8 Simulator:

Combining XAML with C++ and DirectX will let us create very nice applications and games. Go ahead and great your cool game today and play around with the DirectX samples that come with Visual Studio 2012!

Vote on HN

Creating a Windows Metro style application in C++

Posted by Filip Ekberg on May 2 2012 2 Comments

I am going to step out of my comfort zone a bit and write a post that touches the surface of C++ in Windows 8. Let us start off by looking at an image of what the new WinRT(Windows Runtime) look like:

As you can see, there are a lot of powerful ways to create both metro style and desktop applications. Notice that in Metro style applications, XAML is connected to both C++ and C#/VB.

During my years of .NET development, the reason for using C# or VB has been; RAD(Rapid Application Development). In a world filled with consultants where the customers only see the end result, it can often be hard to convince that putting down 200% more time using C++ is a great idea.

Because let’s face it, it takes a lot more time creating a desktop application in C++ using MFC than what it would to use C# and XAML. Before someone throws a stick at me I have to say that it of course depends on what kind of application you are creating.

The downside from using a managed programming language is that it tends to be a bit slower; in some cases this is critical. Most customers do not care if they have to wait a couple of extra nano-seconds for a control to render.

What does this have to do with Windows 8 and the Windows Runtime?

I really got a nice tingly feeling in my stomach when I first saw that you could use XAML with C++ in Windows 8. But that is not the best part, the best part is that it is fully native!

This means that the designers can make the interface in expression blend and we can dig down into C++ on the backend.

Let us have a look at this! You will need to have Windows 8 Consumer Preview and Visual Studio 11 beta installed (or later) in order follow these examples.

Start off by creating a new blank Windows Metro style application, this is found under “Other languages -> Visual C++”:

When the project is created, you will see some files that have been generated, these are pretty similar to what we are used to see in a normal XAML application in .NET:

Open up the file “BlankPage.xaml”, this will bring you into the designer view of the XAML file. Add a TextBlock to the page:

As you can see in the preview, it shows a tablet with the current view inside it. Remember that we are working with a Metro application, the idea is that you have a metro application in fullscreen or pinned to one of the sides on your screen.

By only adding the TextBlock, this is the XAML that we have now:

<Page
   x:Class="WinRTDemo.BlankPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="using:WinRTDemo"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
        <TextBlock x:Name="MyTextBlock"></TextBlock>
    </Grid>
</Page>

If we now navigate to the file “BlankPage.xaml.cpp”, this is where we can actually access the TextBlock. When you compile your solution, the XAML will also be compiled to C++, just like the XAML in a normal .NET application is compiled.

However, to access the TextBlock and set the text of it to the current date, what do we write?

The TextBlock is actually a TextBlock^, the “^” is called a “hat”. Think of this as a pointer, but a pointer that you do not have to worry about disposing.

This means that you do not have to do delete on the object yourself, because it will be automatically removed once the context of it has been exited.

So in order to set the value of the TextBlock we do:

MyTextBlock->Text = "Hello World!";

We can test-run this before we display the current time. First, let’s select to run it in a simulator like this:

This will bring up a tablet emulator that mirrors your system:

Now let’s take a look at how to get the current date there instead of that “Hello World!” text. In WinRT you can access an object called Calendar which you can use to get the date and time.

In order to get a pointer/hat, you need to modify the instantiation a tiny bit. Instead of just writing this:

new Calendar();

You write:

ref new Calendar();

This lets the compiler know that this will in fact be a hat/”managed pointer”. Something that I have missed a lot when not working in C# is the keyword var and this has finally come to C++ with the more appropriate name auto.

So in order to get a calendar object, calibrate it to the current time and then set the text to the current date we can simple do it like this:

auto calendar = ref new Windows::Globalization::Calendar();

MyTextBlock->Text = calendar->YearAsString() + " " +
                    calendar->MonthAsString() + " " +
                    calendar->DayAsString();

This has been a short post about how to create your first C++ Metro style application in Windows 8 and I hope you enjoyed the read, if you have any questions do not hesitate to leave a comment, tweet or e-mail.

Vote on HN

Polymorphism – A Practical Example

Posted by Filip Ekberg on November 13 2008 2 Comments

Classes, inheritance and polymorphism can sometimes be somewhat hard to understand. So a practial example suits many well. Therefore this will be a tutorial where i will touch the areas of classes, pointers, inheritance and polymorphism.

So to just clearify some expressions i will add a little dictionary at the top:

Class
A class can somewhat be seen as a blueprint of your object. I.e. having a blueprint for a building, then this would be the class. Then a Constructor would build this to become an actuall touchable object.

Inheritance
When you inherit something you can think of it more like you extend this thing. I.e. having a Car and then having a Sports Car where there are some new variables to it. The Sports Car is actually a Car but it’s also extended with new properties.

Polymorphism
This is taken from Wikipedia: “In simple terms, polymorphism is the ability of one type, A, to appear as and be used like another type, B. In strongly typed languages, this usually means that type A somehow derives from type B, or type A implements an interface that represents type B”. Read more here

Pointer
For a pointer explenation look here

I will be using Visual Studio 2008 with the built in C++ compiler for the following examples.

A good practice will be to create a Bank, when you get a new assignment or just want to create something new, start by thinking about the structure, what actuall needs does this have? Well when creating a Bank i think to myself that i’d like to be able to create Bank Accounts, attatch these to People and you can go on and on.

But, for the example i will only go as far as creating a Bank, a Bank Account ( Abstract ) and a Student Bank account which is the only Bank account you can actually get.

So creating a simple diagram over the project, i got something like this:diagram So now we have a Bank, Account and Student Account, what kind of variables do we need?

Bank
Bank Name
Accounts

Account
Balance
Interest
Max Loan
Account Holder

Student Account
Amount of Deposits
Last Deposite Month

So the big difference between Account and Student Account is that the Student Account have different rules than Account and therefore calculate a lot of things differently. We won’t go through all the logics. There will of course be a window for you to evolve this application as you feel nessesary.

Now when we have a defined structure we can start by creating a new Project and it’s files. My project will be called Bank and the following files will be placed in it:

  1. main.cpp
  2. Bank.h
  3. Bank.cpp
  4. BankAccount.h
  5. BankAccount.cpp
  6. StudentAccount.h
  7. StudentAccount.cpp

When all my files are created a start by definint my program entry point, this being my main. Notice that i will be posting code snippets as pictures, because you should Write this yourself and not copy my code!

1

We prepare for an input/output stream by including <iostream> and setting using namespace std;

Now the next part is to define the Bank.h We need an appropriet constructor, desctructor and some access methods, remember to never open up member variables publicly!

The #ifndef part is important for the compiler, we dont want to define our header file more than once, because that is not nessesary!

2

I assume all the parts are clear except the last one, read more about how that pointer type works in the previous post here on my wordpress.

The implementation itself will be up to you, i will only be showing the structure, header-files and some code from main and where polymorphism is concerned!

The next file to create would be the BankAccount, remember to add #include “BankAccount.h”  to Bank.h when it has been done. Otherwise the BankAccount *accounts array will fail because undefined symbol.

Back to the third file, the BankAccount.h this is how i would structure it:

3

The part to look deeply on here is the Deposite method, watch closely, it’s defined as followed: virtual void Deposite(double amount) = 0; So this method is expected to be overrided in a inherited class and it has the return type of void and an in parameter of the type double.

Now the next file to create is the StudentAccount.h where we will be deriving from BankAccount.

4

So the following class StudentAccount is extending a class called BankAccount. So this means that StudentAccount is a BankAccount with extended properties and/or overrided functions.

Now, look closely again, here we have the virtual void Deposite part again, but without the =0, so this means we will be creating a definition for this function.

Also the Amount of Deposits and Last Deposit Month is just there to simulate some properties that might be nessesary to do something on a student accont. In my case this is for the Deposite. A Student Can’t deposite money more than three times per month, this is because a student gets 2% interest everytime they deposite money.

This is my Constructor for StudentAccount

5

As you can see, we pass the Variables Owner and Deposite back to the constructor of the base type, being BankAccount.

Now this is how my Deposite Method is implemented:

6 

Now the last think i want you to look at, is my final Main:

7

dth="450" border="0" />

I want you to try and create all the nessesary functions in Bank.cpp, BankAccount.cpp and in StudentAccount.ccp to get the following output from this Main.cpp:

8

I would happily answer any questions about this project. A link to the complete source code is here

Vote on HN

Pointers & Double Pointers

Posted by Filip Ekberg on November 11 2008 3 Comments

Definitions
First off, we need to clearify what a some of the expressions i will use mean. These are the following expressions:

Stack
Assuming that you know about a computer having RAM ( Random Access Memory ) which allows you to store information and have this accessable faster than you would on a secondary memory like a harddrive and/or cd-rom.

When a program is executed there is a part in the memory reserved for this application to use, this “space” is called the Stack; The stack is always the same size and it’s not possible to change it’s size on any way.

Heap
The Heap is also a “space” on your memory, actually it’s all the memory not allocated as a stack. So when your stack is defined, everything else can be expressed as the Heap.

Pointers
What is a pointer really? A pointer is a globally used expression to reference that your somewhat “point” to something. See the following illustration

p1
On this image we have something that we point to, let’s call A our Object. So having A as the actualy object, play with the thought that B and C isnt there, and there are no pointers to it.

This would infact mean that we had A allocated on the Stack. When does this become a problem? So play with the thought you have a really big information base such as a User Layer where you store a lot of data on each user. Then havnig a big register on all the people attending a course would take up somewhat a bigger space than we have free.

When is is an issue, we can use a pointer, to reference to this object. You can of course point to an object that you have on the stack, but that’s not. afaik, what it’s initially intended for.

So we tell our program that we want to create a Pointer, this pointer will in fact be stored on the stack, but a pointer only takes up 4 bytes so this wont be a problem.

After creating the pointer, we create the object itself and have the pointer B point to this.

Pointer, Objects s & Arrays
Assuming you know about some object orientation and how an object is constructed i will not go in to this very deeply. I.e. we have a class called Person and we want to create somewhat a register over students attending a course, what we initially want to do is create an object array, where we can store all our persons, using c++, as i will do in the following examples you would write something like this:

Person *attendingStudents = new Person[size];

Where size is equal to the max amount of students.

Running this code, the constructor of Person will be runned as many times as the size of the array attendingStudents. How is this a problem? This becomes a problem when we dont want to run the default constructor and allocate the object size  as many times as the total array size, this has too much overhead.

First of all, how does this look in memory? 

p2

On adress 0 to adress 3 wnicn means 4 bytes; every memoy block is 4 bytes; the pointer attendingStudents is allocated and on that area a 4 byte long adress is stored which in our case is 84. The size of the given Person object is not given but just play with the thought that its 4 bytes and the size is 10 this would mean the total size of the Person array would be 10 * 4 = 40 Bytes going from the address 84 to 124.

However, let’s say that the Person object takes up 4 times as much so it takes up 16 bytes per Person object, this would result in 16 * 10 = 160 bytes, going from address 84 to 244. Now, there is a big overhead if we dont use all the persons and it would be stupid to call the constructors twice.

So, how about, we just point to something that we know is a pointer, and then let this poitner take care of the rest? But we just initialize the first step?

Double pointers
Thjis is were double pointers comes in handy, look at the following code:

Person **attedningStudents = new Person*[size]:

This code is not as straight forward to look at, as the pervious one, but it basically means, 

Person **attendingStudents

  = Create a reference, to a pointer, what is a pointer? A pointer is something that will in the end point to a data type, so what we do here is saying that Point to a Pointer, this pointer will eventually have the data type Person.

Just to clearify, a pointer to an array, initially points to the first index in that array. So after creating the Pointer to a Pointer we tell it to point to a new list of Pointers, the amount of pointers to create is the same as the digit in size.

This might not make any sense, but take a look at the following

p3

Initally these pointers don’t point to anything at all so what we can do is: attendingStudents[i] which will take us to the adress 84 and then create an object on this index by doing this:

attendingStudents[i] = new Person();

Why is this method better than the one before? Well this assures that we Only have the 11 pointers which takes 4 bytes per pointer. 1 pointer on the stack, referencing 10 pointers on the stack. When does this give us overhead? This gives us a 4 byte overhead when we start creating our Persons. But the execution time saved and just given 4 bytes ovearhead per pointer, this is a preffered method by me.

Vote on HN